State change with toggle switch and LED?

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.

Thanks!

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.

nice graphic.

try something like this untested bit of code…

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);
  }
}

Hey man, thanks for answering my question (http://forum.arduino.cc/index.php?topic=262784.0). But I have an additional question. How would you change this code so that there could be 5 led and 5 toggle switches. Thank you very much in advance,

Nicoss18

I might do it with arrays:

this is partially tested…

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);
    }
  }
}