I want to create a Toggle Push Button switch, when LED HIGH, then i want to show " LED IS ON" either "LED IS OFF", Please can any one help me?

#include<LiquidCrystal.h>
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

int pushbutton = 11;// connect output to push button
int led = 12;// Connected to relay (LED)
int ledstate=0;
int buttonState;
int previousbuttonState=0;
void setup() {

pinMode(led, OUTPUT);
pinMode(pushbutton, INPUT);

}

void loop() {
buttonState=digitalRead(pushbutton);
if (buttonState==1 && previousbuttonState==0) {
if(ledstate==0) {
digitalWrite(led, HIGH);
ledstate=1;
}

else {
digitalWrite(led, LOW);
ledstate=0;
}

}
previousbuttonState=buttonState;
delay(100);

if (led== HIGH){
lcd.setCursor(0,0);
lcd.clear();
lcd.print("LED IS ON");}

else{(led==LOW);

lcd.setCursor(0,0);
lcd.clear();
lcd.print("LED IS OFF");}
}

Hi, @ibrahimet
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".

This will help with advice on how to present your code and problems.

Can you post a circuit diagram of your project please?
Just an image of a drawn diagram will be fine.
Please include power supplies, component names and pin labels.

Tom... :smiley: :+1: :australia: :coffee:

Hello ibrahimet
The IDE provides an example called State change detection
You may use this example to control the LEDs.
Have a nice day and enjoy coding in C++.

1 Like

isn't led the value of the pin?
should you compare ledstate instead?

while not an error, it does nothing. should simply be

   else {
1 Like

This will not print anything because led is equal to 12, not HIGH or LOW. You probably meant to use ledstate. I would recommend always using HIGH and LOW rather than 0 and 1 for digital inputs and outputs.

  if (led == HIGH) {
    lcd.setCursor(0, 0);
    lcd.clear();
    lcd.print("LED IS ON");
  }
  else {
    (led == LOW);
    lcd.setCursor(0, 0);
    lcd.clear();
    lcd.print("LED IS OFF");
  }

It will print "LED IS OFF" every time because there is no "if" after the else and because led = 12 as you said. The bare (led == LOW) will apply the comparison operator, determine it to be 0 and then discard it because there isn't a LHS variable to assign it to or an if statement to use it for a branch, if the compiler doesn't optimize it away altogether.

1 Like

You are correct. I was in a hurry when I responded!

1 Like

Yes, now its working, Many many thanks to ToddL1962 and DeveX. but at power starting time it no word shows in the lcd display .

Sounds like a job for setup(){...}.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.