How to use random function? Please Help

adwsystems:
This is one of those rare times when the error is quite literal, the variable last_buttonState is not delcared.

First, you need to declare last_buttonState just like you did buttonState.

Then you need to read on if...else statements and comparison operators, including not equal to

You have some comments, but should have more. I will add some for you.

if (last_buttonState != buttonState) // is this button state not equal to the last button state

{
last_buttonState = buttonState; // record current button state as last

if (buttonState == HIGH) // is current button state HIGH
{
  lcd.clear();
  lcd.print("Press button to get a random phrase.");
}
else if (buttonState == LOW) // is current button state low
{

byte index = random(0, 4);  //get a number between 0 and 4 :smiley:
  lcd.setCursor(0, 0);
  lcd.clear();
  lcd.print(phrases[index]); //use it as the index to the array of phrases
}

}




As I mentioned, you need to stop clearing the lcd if you want to stop the flickering. The information on the display only need to be updated when the button get pressed. Before you determine the state of the button, you need to determine if the state has changed (this is what I added).

Okay so what CURRENT code is,

const int buttonPin = 7;
int buttonState = 0;  
int last_buttonState = LOW;     
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
char * phrases[] = {"Phrase 1", "Phrase 2", "Phrase 3", "Phrase 4"};

void setup()
{
  Serial.begin(115200);
  pinMode(buttonPin, INPUT);
  lcd.begin(16, 2);
  pinMode(9, OUTPUT);
  analogWrite(9,50);
  randomSeed(analogRead(A0)); 
}

void loop()
{
   buttonState = digitalRead(buttonPin);
  if (last_buttonState != buttonState) // is this button state not equal to the last button state
{
 last_buttonState = buttonState; // record current button state as last
 
 if (buttonState == HIGH) // is current button state HIGH
 {
   lcd.clear();
   lcd.print("Press button to get a random phrase.");
 }
 else if (buttonState == LOW) // is current button state low
 {

   byte index = random(0, 4);  //get a number between 0 and 4 :D
   lcd.setCursor(0, 0);
   lcd.clear();
   lcd.print(phrases[index]); //use it as the index to the array of phrases
 }

}}

The project is working fine expect what I can see is when Button is not pressed, I can see "Random Phrase (?) " and the "Press button" too both swapping very very fast...

When button is pressed, I succesfully see a normal Phrase selected randomly..

But

sometimes LCD goes crazy

with thousands of characters scrolling !

Sorry for deleting last answer as there were some illogical errors which were reapired now.

Thank you.