I'm trying to call a function to keep an LED on for a certain amount of time. The function is called when the button is pushed but the LED stays on. I used the same code in the void loop before moving it into a function and it worked.
const int ledPin2 = 2;
const int buttonPin7 = 7;
const unsigned long onTime = 1000;
unsigned long previousMillis = 0;
//
void timer(){
unsigned long currentMillis = millis();
digitalWrite(ledPin2, HIGH);
if (currentMillis - previousMillis >= onTime){
digitalWrite(ledPin2, LOW);
previousMillis = millis();
}
}
void setup(){
Serial.begin(9600);
pinMode(ledPin2, OUTPUT);
pinMode(buttonPin7, INPUT);
}
void loop(){
int buttonState = digitalRead(buttonPin7);
if (buttonState == HIGH) timer();
}