LED & Alarm together using Millis() with initial long alarm

Hi,
I have an Uno which had an LED on pin 2 and audible alarm on pin 9.
I am wanting a sketch to do the following Using multiple timers ;

  1. blink a Led forever ,
  2. Sound iitial 1st alrm for 1min after first 6 mins (do this only once) then
  3. Alarm off off 1 min
  4. Sound alarm for 1 minute
  5. Do steps 3 & 4 forever (whilst blinking the LED throughout)

The code below will blink the led & sound the alarm (& turn it off) in a loop , however I'm unable to get the initial first alarm to work. Any help is appreciated, I'm not wanting to use the delay function as it stops the LED.

const int LEDpin = 2;
const int ALMpin = 9;

const long LEDonDuration = 200;// ON time for LED
const long LEDoffDuration = 300;// OFF time for LED

const long ALMonDuration = 60000;      // Alm ON duration (milliseconds) 1mins=60000 
const long ALMoffDuration = 120000;      // Alm OFF duration (milliseconds) 2mins=120000 

long rememberTime=0;// this is used by the code for LED
long rememberALMTime=0;// this is used by the code for ALM

int LEDState =LOW;// initial state of LED
int ALMState =LOW;// initial state of ALM

int value = 0;

void setup() {

  pinMode(LEDpin,OUTPUT);// define LEDpin as output
  digitalWrite(LEDpin,LEDState);// set initial state
  digitalWrite(ALMpin,ALMState);// set initial state
    
//  pinMode (9, OUTPUT);
  Serial.begin (9600); // initialize serial communications:
  Serial.println("Alarm pin Status = LO");
   }
void loop() {
      if( LEDState ==HIGH )
       {
          if( (millis()- rememberTime) >= LEDonDuration){   
          LEDState =LOW;// change the state of LED
          rememberTime=millis();// remember Current millis() time
          }
       }
       else
       {   
          if( (millis()- rememberTime) >= LEDoffDuration){     
          LEDState =HIGH;// change the state of LED
          rememberTime=millis();// remember Current millis() time
          }
       }

if( ALMState ==HIGH )
 {
    if( (millis()- rememberALMTime) >= ALMonDuration){   
    ALMState =LOW;// change the state of ALM
        Serial.println("Pin Status = LO");
    rememberALMTime=millis();// remember Current millis() time
    }
 }
 else
 {   
    if( (millis()- rememberALMTime) >= ALMoffDuration){     
    ALMState =HIGH;// change the state of ALM
        Serial.println("Pin Status = HI");
    rememberALMTime=millis();// remember Current millis() time
    }
 }

 digitalWrite(LEDpin,LEDState);// turn the LED ON or OFF
 digitalWrite(ALMpin,ALMState);// turn the ALM ON or OFF
}

Never long. Always unsigned long.

2 Likes

One way to achieve this is to introduce a new variable, like firstTime and set it to TRUE. When you loop() executes, you use this variable to determine if you are doing the first time or not and act accordingly.

Sorted it with another nested if. All good now

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.