Hello, I would like to ask for your guidance.
I have searched online about "multi-threading" for Arduino, and based on what I've read, that is not possible. But there's an alternative. http://forum.arduino.cc/index.php/topic,5686.0.html
The code below was given by dmesser in that thread.
#define ledPin1 11
#define ledPin2 12
#define led1Cycle 100U
#define led2Cycle 275U
unsigned long led1LastMillis = 0;
unsigned long led2LastMillis = 0;
boolean led1State = false;
boolean led2State = false;
boolean cycleCheck(unsigned long *lastMillis, unsigned int cycle)
{
unsigned long currentMillis = millis();
if(currentMillis - *lastMillis >= cycle)
{
*lastMillis = currentMillis;
return true;
}
else
return false;
}
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
}
void loop()
{
if(cycleCheck(&led1LastMillis, led1Cycle))
{
digitalWrite(ledPin1, led1State);
led1State = !led1State;
}
if(cycleCheck(&led2LastMillis, led2Cycle))
{
digitalWrite(ledPin2, led2State);
led2State = !led2State;
}
}
How do I determine this two #define led1Cycle 100U, #define led2Cycle 275U? I have an alarm clock project. I want to use the toneAC library. Unfortunately, the delay with the toneAC is about 4 seconds which lags the display by 4 seconds. I want both function (playing the toneAC, and displaying the time) to be executed almost simultaneously.
Btw, I am using the toneAC_demo sample code. Below is the fragment of my code
{
display_time(seconds,minutes,hours);
display_date(day,date,month,year);
delay(300);
if (hours==alarmHours && minutes==alarmMinutes&&seconds==alarmSeconds){
alarmLength = 1;/
temp = minutes;
Serial.println("ALARM TIME!!!");
}
//Serial.println(A0);
//Serial.println(A1);
if ((alarmLength > 0 && alarmLength < 31 && temp!=minutes)){
temp = minutes;
alarmLength++;
Serial.println("ALARM TIME!!!");
Serial.println(alarmLength);
}
if ((alarmLength > 0 && alarmLength < 31))
{
Serial.println(A3);
if((digitalRead(A3) == LOW))
{
//digitalWrite(A2,HIGH);
play_alarm();
digitalWrite(A0,HIGH);
digitalWrite(A1,HIGH);
}
else
{
digitalWrite(10,LOW);
digitalWrite(A0,LOW);
digitalWrite(A1,LOW);
}
}
else
{
digitalWrite(10,LOW);
digitalWrite(A0,LOW);
digitalWrite(A1,LOW);
}
}
-------
void play_alarm(){
for (unsigned long freq = 125; freq <= 15000; freq += 10) {
toneAC(freq); // Play the frequency (125 Hz to 15 kHz sweep in 10 Hz steps).
delay(1); // Wait 1 ms so you can hear it.
}
toneAC(); // Turn off toneAC, can also use noToneAC().
delay(300); // Wait a second.
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000/noteDurations[thisNote];
toneAC(melody[thisNote], 10, noteDuration, true); // Play thisNote at full volume for noteDuration in the background.
delay(noteDuration * 4 / 3); // Wait while the tone plays in the background, plus another 33% delay between notes.
}
}[/code