Example 2: Buzzer

Code


/*In this simulation we will test the speaker that comes by default in the robot, making it loop the song "Fugue in D minor"*/

/*We include the appropriate libraries to be able to activate certain commands and instructions*/

#include <Wire.h>
#include <Zumo32U4.h>

/*With the following code we call the component that we are going to use in the code*/

Zumo32U4Buzzer buzzer;

/*We will first save the song to the program space using the PROGMEM macro. Later, we can play it directly from the program space,
avoiding the need to load everything into RAM first*/

/*The song is then composed by dividing it into different phrases, in which the notes would be (DO=C, RE=D, MI=E, FA=F, SOL=G, LA=A, SI=B).
In addition, the octave (tone) in which the notes must be played is also indicated, it is also said if they are sharp or flat with the signs
"#" and "b" and finally it is said if they are minor and major notes with the signs "<" and ">"*/

const char fugue[] PROGMEM =
  "! O5 L16 agafaea dac+adaea fa<aa<bac#a dac#adaea f"
  "O6 dcd<b-d<ad<g d<f+d<gd<ad<b- d<dd<ed<f+d<g d<f+d<gd<ad"
  "L8 MS <b-d<b-d MLe-<ge-<g MSc<ac<a ML d<fd<f O5 MS b-gb-g"
  "ML >c#e>c#e MS afaf ML gc#gc# MS fdfd ML e<b-e<b-"
  "O6 L16ragafaea dac#adaea fa<aa<bac#a dac#adaea faeadaca"
  "<b-acadg<b-g egdgcg<b-g <ag<b-gcf<af dfcf<b-f<af"
  "<gf<af<b-e<ge c#e<b-e<ae<ge <fe<ge<ad<fd"
  "O5 e>ee>ef>df>d b->c#b->c#a>df>d e>ee>ef>df>d"
  "e>d>c#>db>d>c#b >c#agaegfe f O6 dc#dfdc#<b c#4";

/*In the void setup section it is not necessary to add anything since in the circuit we do not have to assign pins, outputs, inputs, etc*/

void setup()
{
}

/*In the void loop we can loop the song that has already been programmed previously*/

void loop()
{

/*In the following line of code, the robot's speaker is called, ordering it to play a wave frequency of 440Hz,
a time of 200 milliseconds, and a volume of 15*/

  buzzer.playFrequency(440, 200, 15);

/*We apply a margin of one second before giving it another instruction*/
  
  delay(1000);

/*Later, the speaker is asked again to play this time the note A (LA), the octave 4 (key), at volume 15 (maximum) and for a time of two seconds*/

  buzzer.playNote(NOTE_A(4), 2000, 15);

/*After a delay of 0.2 seconds, we command the speaker to stop ringing*/

  delay(200);
  buzzer.stopPlaying();

/*We apply another time a margin of one second before giving it another instruction*/

  delay(1000);

/*Finally, we order the speaker to play the entire song that we have previously loaded into the CPU*/
  
  buzzer.playFromProgramSpace(fugue);

/*With the following line we can know if the song is still playing or not*/
  
  while(buzzer.isPlaying()){ }

/*This one second delay will be the margin time between the end of the song and the beginning, at the moment in which it is repeated*/

  delay(1000);
}

Video of the Circuit