Hi there!
I'm currently working on a project where I want to add some brief jingles to notify some events to the user. These are:
- Joystick button pressed.
- A task has started.
- A task has finished.
For that I'm using a passive buzzer. Since I don't want to block the code while playing the melodys, I've merged the examples from pitcher.h with the allmighty BlinkWithoutDelay. I actually achieved that, here's the code:
#include <pitches.h>
#include <Button.h>
#define Buzzer 11
bool PlayingButtonJingle;
unsigned long currentMillis;
Button JoystickButton(2);
void setup() {
JoystickButton.begin();
}
void loop() {
currentMillis = millis();
if(JoystickButton.pressed()){ PlayingButtonJingle = HIGH;}
if(PlayingButtonJingle){ ButtonJingle();}
}
int ButtonJingleNotes[] = {
NOTE_A7, NOTE_C8, NOTE_D8
};
int ButtonJingleNotesDuration[] = {
32, 16, 16
};
bool PlayingToneBJ = LOW;
int currentNoteBJ = 0;
unsigned long previousMillisBJ = 0, pauseBetweenNotesBJ = 0, noteDurationBJ = 0;
void ButtonJingle(){
if(!PlayingToneBJ){
noteDurationBJ = 1000 / ButtonJingleNotesDuration[currentNoteBJ];
pauseBetweenNotesBJ = noteDurationBJ * 1.30;
previousMillisBJ = currentMillis;
tone(Buzzer, ButtonJingleNotes[currentNoteBJ], noteDurationBJ);
PlayingToneBJ = HIGH;
}
else{
if(currentMillis - previousMillisBJ >= pauseBetweenNotesBJ){
noTone(Buzzer);
currentNoteBJ++;
PlayingToneBJ = LOW;
}
}
if(currentNoteBJ > (sizeof(ButtonJingleNotes) / sizeof(ButtonJingleNotes[0]))){
currentNoteBJ = 0;
PlayingButtonJingle = LOW;
}
}
The issue is that I really think this code could be much cleaner, but I'm not capable of doing it. At the end, I will only have three different jingles so I would repeat the code below the loop() just thrice as well as the two lines inside the loop() itself. But what if I have 15 different jingles, for example?
Furthermore, I'm pretty sure that this code could be improved in some many ways, I'm whiling to hear you about it. Memory/Lines saving, more readable code, programmer good practices... Whatever.
The most upsetting thing from my point of view, are the declarations of the variables and the arrays just above the ButtonJingle(), but I think that if they were at the very begining of the code, it would be even worse. However, I suspect that there is a ton of things that I can't actually see in there, so I need your proffessional eyes!
Thanks in advance four y'all!
Wyzed.