Hi, I have a strange "non-problem" with my code. For simplification I've written a smaller program. The program should control two LED's. Each LED will turn on for 1 second, and then turn off for 3 seconds. My initial problem was that I wanted one LED to turn on after the second LED has been off for 1 second.
So basically it would look like: both off, LED1 on, both off, LED2 on, both off, LED1 on, both off... and so on.
The following code seems to work, but I feel like it's not supposed to.
int led1 = 2;
int led2 = 3;
long off_interval = 3000;
long on_interval = 1000;
int d = 2000; //delay
unsigned long prev_ms1 = 0;
unsigned long prev_ms2 = -d; //delay added
void setup()
{
Serial.begin(9600);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}
void loop()
{
unsigned long curr_ms = millis();
if((curr_ms - prev_ms1) > off_interval)
{
digitalWrite(led1, HIGH);
}
if((curr_ms - prev_ms1) > off_interval+on_interval)
{
digitalWrite(led1, LOW);
prev_ms1 = millis();
}
if((curr_ms - prev_ms2) > off_interval)
{
digitalWrite(led2, HIGH);
}
if((curr_ms - prev_ms2) > off_interval+on_interval)
{
digitalWrite(led2, LOW);
prev_ms2 = millis();
}
}
The lines I am worried about are the if statements involving prev_ms2:
if((curr_ms - prev_ms2) > off_interval)
I thought this line should not work, since I defined int d=2000, and unsigned long prev_ms2 = -d. I was trying to "shift" the output of the second LED so that it would blink when the first LED was off. I feel like this line should give me an error, since at the beginning, wouldn't we have a negative value - and thus some sort of rollover - in an unsigned long? Somehow I'm not having this issue and the code works fine. Could someone please tell me why? Am I accidentally casting something?