Step 5: The Code

Now let's get the board to work! Let's setup Arduino. If you don't already have the Gemma M0 board driver installed, check out this link:

After you have that installed, we need to put the Gemma M0 into Bootloader Mode. To do so, press the reset button twice, and the red LED should start flashing. Make sure that your board selection is right (tools-board-Gemma M0) and so is your port (tools-port), and then upload this code:

/*
 Interactive Gift Box
 When you shake the box, it will light up the tree and play music!
*/


int speakerPin = 2;
int buttonPin = 1;
int ledsPin = 0;
int length = 26;
int buttonState = 0;
char notes[] = "eeeeeeegcde fffffeeeeddedg";
int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2};

int tempo = 200;
void playTone(int tone, int duration) {
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
  }
}
void playNote(char note, int duration) {
  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
  
  for (int i = 0; i < 8; i++) {
    if (names[i] == note) {
      playTone(tones[i], duration);
    }
  }
}
void setup() {
  pinMode(speakerPin, OUTPUT);
  pinMode(ledsPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}
void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledsPin, HIGH);
  for (int i = 0; i < length; i++) {
    if (notes[i] == ' ') {
      delay(beats[i] * tempo);
    } else {
      playNote(notes[i], beats[i] * tempo);
    }
    
    delay(tempo / 2); 
  }
  digitalWrite(ledsPin, LOW);
  delay(1000);
  }
}

Press the upload arrow and the light on the board should turn purple! Hit it on the side, and it should light up and play music! Now you have an awesome gift box!

This guide was first published on Dec 22, 2017. It was last updated on Sep 22, 2018. This page (Step 5: The Code) was last updated on Jan 09, 2018.