Basically the user presses a button and cycles thru 3 different modes. Mode 1 the LED is on, mode 2 the LED is off and mode 3 the LED is kept on for a certain amount of time. I'm using the millis() to keep track of the time. the LED in the third mode just stays on and never switches to off. I have the Serial.Writes in there to help me debug. I have the delay after the button read since if I didnt put it in it would register a lot of button presses.
int ledPin = 5;
int buttonApin = 9;
int ledMode = 0;
boolean lastButton = HIGH;
boolean currentAButton = HIGH;
// debounce button
boolean debounceFUNC(boolean last)
{
boolean current = digitalRead(buttonApin);
if (last != current)
{
delay(5);
current = digitalRead(buttonApin);
}
return current;
}
void setMode(int ledMode)
{
// turns on led
if (ledMode == 1)
{
digitalWrite(ledPin, HIGH);
}
// turns off led
if (ledMode == 2)
{
digitalWrite(ledPin, LOW);
}
// timer - turns off after 5000
if (ledMode == 3)
{
long interval = 5000;
unsigned long cMillis = millis();
static unsigned long pMillis;
if (cMillis - pMillis > interval)
{
pMillis = cMillis;
digitalWrite(ledPin, HIGH);
Serial.println("On");
Serial.println(interval - cMillis);
}
else
{
digitalWrite(ledPin, LOW);
Serial.println("Off");
}
}
}
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
}
void loop()
{
// sets led mode
currentAButton = debounceFUNC(lastButton);
delay(500);
if (currentAButton == LOW)
{
ledMode++;
Serial.println(ledMode);
}
else if (ledMode > 3)
{
ledMode = 0;
}
// ledMode function call
setMode(ledMode);
}
screenshot of the serial monitor.