Name change upon button click

Hi,

I have written a programme in which display print change upon button clicking.

but some time print change twice upon single click, i dont found any solution please help me.

My code is

#include <LiquidCrystal.h>

const byte buttonPin = 7;

int buttonPushCounter = 0; // counter for the number of button presses
boolean buttonState = LOW; // current state of the button
boolean lastButtonState = LOW; // previous state of the button

// lcd constructor made global in scope so the whole program can sse it
LiquidCrystal lcd(32, 30, 28, 26, 24, 22);

void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.setCursor(0, 0);
lcd.print("Hi I am Robocook");
lcd.setCursor(5, 2);
// Print a message to the LCD.
lcd.print("2018");
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);

}

void loop()
{
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState)
{
if (buttonState == HIGH)
{
// if the current state is HIGH then the button
// went from off to on:
buttonPushCounter++; // add one to counter
lcd.clear();
if (buttonPushCounter > 3) // if couter over 3 reset the counter to 1 to show "Jon"
// and not "Hello All"
{
buttonPushCounter = 1;
}
Serial.println(buttonPushCounter);
switch (buttonPushCounter) // choose what to display based on buttonPushCounter value
{
case 0:
lcd.print("I am Robocook"); // show "Hello All until first button press
break;
case 1:
lcd.print("Ram");
break;
case 2:
lcd.print("Jimmy");
break;
case 3:
lcd.print("Sid");
break;
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
}

You probably want some button debouncing.

Just to test if that is the problem, you can change this:

    // save the current state as the last state,
    //for next time through the loop
    lastButtonState = buttonState;

to this:

    // save the current state as the last state,
    //for next time through the loop
    delay( 100) ;
    lastButtonState = buttonState;

If that solves the problem, then restructure the logic so the sketch does not accept a button press, if the last accepted button press was less than 100 mS ago.

ok i will let you soon

this worked for me , thanks sir :slight_smile:

OK. That was for testing. Generally, although there can be exceptions, it is not a good idea to have delay() statements in the loop.