LED blinks with a momentary switch.

Hi…arduino experts. I’m in Thailand. I’m starting learning arduino. It’s very new to me. I have tried to write codes to blink a LED with a momentary switch. But no success. What I want is > pressing the momentary switch > the LED goes brink ON-OFF…ON-OFF…ON-OFF… with 100 milliSec delay > and OFF/stop if switch is pressed again. Can someone help me for the codes.
Many thanks,

Hi Manu_sri,

Welcome in Arduino land, what you need to make is a state machine that has 2 states running and stopped. The switch will let you switch between these states. A state machine is a very powerful technique for solving programming problems. Define a system in terms of states and their (allowed) transitions. Note: can be quite big!

A partial sketch, completing it is the homework for the weekend ;)

#define RUNNING 1
#define STOPPED 0

int state = STOPPED;
int lastRead = LOW;

void loop()
{
  // read switch
  int current = digitalRead(switchPin);
  if ( current == HIGH && lastRead == LOW)
  {
    lastRead = HIGH;
    state = RUNNING;
  }
  if (current == LOW && lastRead == HIGH)
  {
    lastRead = LOW;
    state = STOPPED;
  }
  
  // do the LED
  if (state == RUNNING)
  {
   ....
  }
}

Thank you...Rob, It's a good homework for a newbie like me. 5555 :grin:

Hi..Rob,

This is my homework. I added---- to your codes. But not sure it will be correct.

int ledPin=9;

int switchPin=12;


pinMode(ledPin,OUTPUT);

pinMode(switchPin,INPUT);

and for RUNNING

digitalWrite(ledPin,HIGH); delay(100); digitalWrite(ledPin,LOW);

delay(100);

after uploading, when switch is pressed > the LED blinks on-off, on-off......but I have to hold the switch to make it blinks. And it will stop after switch is released. Actually The LED should blink repeatedly when the switch is momentarily pressed. And stop when the switch is pressed again. What wrong I did. :( Here is the codes:

define RUNNING 1

define STOPPED 0

int ledPin = 9; int switchPin = 12;

int state = STOPPED; int lastRead = LOW;

void setup() { pinMode(ledPin,OUTPUT); pinMode(switchPin,INPUT); }

void loop() { // read switch int current = digitalRead(switchPin); if ( current == HIGH && lastRead == LOW) { lastRead = HIGH; state = RUNNING; } if (current == LOW && lastRead == HIGH) { lastRead = LOW; state = STOPPED; }

// do the LED if (state == RUNNING) { digitalWrite(ledPin,HIGH); delay(100); digitalWrite(ledPin,LOW); delay(100); } }

But not sure it will be correct.

JUst try it out is the proof.

Please use the # button if you post code ==> give [ code] tags to put

Think you need a pull-up resistor with the momentary switch. If there is no pull up switch the line might float giving random 1's and 0's ... The switch should be between GND and the pin.

This pullup can be enabled by adding the following command in setup()

void setup()
{
  pinMode(ledPin,OUTPUT);
  pinMode(switchPin,INPUT);
  digitalWrite(switchPin, HIGH); // enable pullup.
}

give it a try.