Can anybody tell whats wrong with code

Please guide what is wrong with code. Without pressing button, both If and else statement are executing.

#include <Wire.h>
#include <hd44780.h>
#include <hd44780ioClass/hd44780_I2Cexp.h> // i2c expander i/o class header
hd44780_I2Cexp lcd;

#define LCD_CHEXECTIME 2000
#define LCD_INSEXECTIME 38

const int LCD_COLS = 16;
const int LCD_ROWS = 2;

int pushButton = 3;
int pinLED = 8;
int stateLED = 0;
int stateButton = 0;

void setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
lcd.begin(LCD_COLS, LCD_ROWS);
lcd.setBacklight(200);
lcd.setCursor(0, 0);
lcd.print("HELLO! ");
delay(2000);

pinMode(pushButton, INPUT); // set up as push button
pinMode(pinLED, OUTPUT); // set up LED

}

void loop() {
stateButton = digitalRead(pushButton); // read pushbutton state at digital input

if (stateButton == 1) {
lcd.setCursor(0, 1);
lcd.print("HIGH ");
digitalWrite(pinLED, 1);
delay(2000);
lcd.clear();

}
else
{
lcd.setCursor(0, 0);
lcd.print("LOW ");
digitalWrite(pinLED, 0);
delay(5000);
lcd.clear();
}
stateButton = 0;
}

Please guide what is wrong with code

It is too long.
It is not in code tags.
It uses delay.
We're missing a schematic, but you're probably missing a pullup or pulldown.

You have something called pushbutton which setup() says is a Relay button and later in loop() you claim it's on an analog input. Way too confusing for me. Comments should be there for a purpose and it's not just to confuse things.

Steve

Welcome to the Forum. Start by reading the stickies at the top of every section which tell you how to post on the forum and what information to provide. This will help others to help you get the answer you need.


In particular make sure that your code is inside code tags. You can edit a post to include them. If the code is too big attach it as a file or create a smaller code that is able to compile and incudes the problem (do not use snippets). It is preferable if you auto format your code before loading it as this will make it easier to read (use CTRL T in the IDE).

Schematics are often useful. You can draw them using a pencil and paper, or use an online tool and then post a picture of it. To post a picture upload it to an image hosting site and then put the link between image tags

If you do these simple things you will get Karma and are much more likely to get the answers you are looking for.

Do you have pullup or pulldown resistors on input pins to keep the pins from "floating" and causing false HIGHs or LOWs when the button is not pressed? Best way is like S3 in the diagram, no external resistor needed, logic is reversed though (pin is LOW when button is pressed).

Thanks :slight_smile: it worked

what worked! This is a forum for people to learn, it is common practice to leave enough information for others to learn from your issue.