Hi,
I'm building a project where I need an Led to light up for half a second when the toggle switch is on the 'on' position then switch off until until the toggle switch is put on the off position, when the Led will light up for half a second then switch off etc...
I am pretty new o Arduino so please make the answers easy. I attached a diagram to the post if you didn't understant.
The state change detection example show how to detect that the switch has become pressed. When the switch becomes pressed, note the time and turn the LED on.
Then, periodically, see if the LED is on and it has been on long enough. If so, turn it off.
The blink without delay examples will give you some ideas.
int buttonPin = 3;
int ledPin = 13;
int lastButtonState;
unsigned long startTime;
void setup()
{
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP); //you can utilize the onboard pull-up resistor or just use INPUT if you have that hardware managed already
pinMode(ledPin, OUTPUT);
}
void loop()
{
int buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState)
{
startTime = millis();
}
lastButtonState = buttonState;
flash();
}
void flash()
{
if (millis() - startTime < 500UL)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
}
int buttonPin[] = {3,4,5,6,7};
int ledPin [] = {13,8,9,10,11};// i tested with onboard led and button pin 3
int lastButtonState[5];
int buttonState[5];
unsigned long startTime [5];
//
void setup()
{
Serial.begin(115200);
for (int i = 0; i < 5; i++)
{
pinMode(buttonPin[i], INPUT_PULLUP);
pinMode(ledPin [i], OUTPUT);
}
}
//
void loop()
{
for (int i = 0; i < 5; i++)
{
buttonState[i] = digitalRead(buttonPin[i]);
if (buttonState[i] != lastButtonState[i])
{
startTime[i] = millis();
}
lastButtonState[i] = buttonState[i];
}
flash();
//put your other program stuff here
}
void flash()
{
for (int i = 0; i < 5; i++)
{
if (millis() - startTime[i] < 500UL)
{
digitalWrite(ledPin[i], HIGH);
}
else
{
digitalWrite(ledPin[i], LOW);
}
}
}