I've got a question regarding the use of Millis() on a Leonardo Arduino. I'm currently using it to time 4 seconds elapsed while sending a serial message every second. These messages play a sound. On the fourth message the sound is different to signify that the Arduino has started an event.
I'm running into an issue where the sounds are occasionally being played sporadically without a consistent 1 second between them. I'm wondering if there is a better way of doing what I'm doing? During the timing the Arduino is doing nothing else, and the receiving computer is also generally not doing anything taxing. Is this even an issue from the Arduino side? My receiving program is written in C# using System.IO.Ports.SerialPort.
The reason this is done through Arduino is because the event started by the Arduino needs to correspond exactly to the sounds, though if this remains unresolved I will need to rework this.
Edit: Code as requested.
void setup()
{
//Setup Code
}
void loop()
{
//Code that handles other serial messages and various states
if (isSpecificState == true)
onSpecificState();
}
void onSpecificState()
{
//Setup to handle state
long holdStart = millis();
long holdDuration = 0;
boolean print1 = false;
boolean print2 = false;
boolean print3 = false;
boolean print4 = false;
while(holdDuration <= 4000)
{
if (holdDuration >= 4000 && !print4)
{
Serial.println("tt_sound:2");
print4 = true;
}
else if (holdDuration >= 3000 && !print3)
{
Serial.println("tt_sound:1");
print3 = true;
}
else if (holdDuration >= 2000 && !print2)
{
Serial.println("tt_sound:1");
print2 = true;
}
else if (holdDuration >= 1000 && !print1)
{
Serial.println("tt_sound:1");
print1 = true;
}
holdDuration = millis() - holdStart;
}
//Handle state
}
As I mentioned in the comments, the Arduino is doing nothing else while the timing is happening.
if
, typically that firstif
should be located after thewhile
loop. Important question: what are the types ofholdDuration
andholdStart
?millis()
is actuallyunsigned long
but that is probably not the issue unless you are running for more than 24 days.