/*
Forum:https://forum.arduino.cc/t/solved-if-statement-running-regardless-of-whether-condition-is-met/1216652/37
Wokwi: https://wokwi.com/projects/388097069591716865
*/
// include the library code:
#include <LiquidCrystal.h>
const byte buttonPin = 12;
int buttonState = 0; // variable for reading the pushbutton status
int randNumber; // the variable which is supposed to hold the random number
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(6, 7, 8, 9, 10, 11); /// REGISTER SELECT PIN,ENABLE PIN,D4 PIN,D5 PIN, D6 PIN, D7 PIN
void setup()
{
// initialize the serial port, 115200 is usually the state-of-the-art baudrate
Serial.begin(115200);
// initialize the pushbutton pin as an input; this requires to
// connect it to HIGH level and the buttonPin connection to GND via a resistor
// ... usually using INPUT_PULLUP is easier to realize ...
pinMode(buttonPin, INPUT);
// initialize the pseudo-random number generator
randomSeed(analogRead(0));
// set up the LCD’s number of columns and rows:
lcd.begin(16, 2);
}
void loop()
{
// Set randNumber to Zero; if the button is pressed randNumber will
// get a value between 1 and 3 anyway
// So we can check later if randNumber is greater than zero
// to take action, if randNumber is zero we do nothing!
randNumber = 0;
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
// turn LED on:
randNumber = random(1, 4); // generate a random number
Serial.println(randNumber);
lcd.setCursor(15, 0); // set the cursor to column 0, line 2
lcd.print(randNumber);
delay(20);//delay of 0.02sec to "debounce" the button
}
// switch evaluates the value of randNumber is uses the according case
// "break;" at the end of each case avoids that the program runs into the
// next case
switch (randNumber) {
case 0 :
// We do nothing!!!
break;
case 1:
Serial.println("Do the stuff here for 1");
delay(1000); // Give some time to release the button!
// Reset randNumber so that nothing happens in the next loop()!
randNumber = 0;
break;
case 2:
Serial.println("Do the stuff here for 2");
delay(1000); // Give some time to release the button!
// Reset randNumber so that nothing happens in the next loop()!
randNumber = 0;
break;
case 3:
Serial.println("Do the stuff here for 3");
delay(1000); // Give some time to release the button!
// Reset randNumber so that nothing happens in the next loop()!
randNumber = 0;
break;
}
}