[S.H.] Metronome doen't work as expected
For school I have an assignment that I have to make a metronome in arduino, but I don't see (yet) why the code I wrote doesn't work the way I anticipated.
// Set the properties of the metrognome.
long interval = 500; // The amount of millis between ticks.
int rhitm = 4; // the rhitm: every now and then a different tick sounds.
String message1 = "Tik!"; // the message for a short tick.
String message2 = "Tok!"; // the message for a long tick.
long lastaction = 0; //notes the time when the last tick/tock was printed.
int teller = 0; //internal counter for the longer tick.
void setup() {
Serial.begin(9600);
}
void loop() {
if ((millis() >= ( lastaction + interval )) && (teller != rhitm)) {
Serial.println( message1 );
} else if((millis() >= ( lastaction + interval )) && (teller == rhitm)) {
Serial.println( message2 );
teller = 0;
}
if (millis() >= ( lastaction + interval )) {
lastaction = millis();
teller++;
}
}
Problem solved, I have intergrated the serial.prints into the first time bound 'If' condition, with then another 'If' for the 2nd message, and an 'Else' for the 1st condition.
Posted Sep 17, 2021, 6:57 AM UTC · edited
Help us to help you: what does it do that you don't want?
With the current properties it should print 3 tik's in the monitor, and then one tok. and repeat.
But the current situation is that it prints 2 tiks, one tok, and then just goes tik tok, OR it prints 3 tiks, then waits, and repeat.
I'm trying to give you clues without doing your homework for you.
I think if you tidied up your if statements you'd probably find the error. Use a nested structure something like this:
Remember that mills() returns an unsigned long (not a long).