Traffic light with button problem, help guys :)

if i hold on pressing the button the traffic lights will change ,
i wan to cancel that please, any help?

const int greenPin = 4; // green led pin
const int yellowPin = 3;
const int redPin = 2;
const int buttonPin = 12;
int ali = 0;

void setup() {
  
for (int i = 2; i <= 4; i++) { // setting outputs
  pinMode(i, OUTPUT);
}

pinMode(buttonPin, OUTPUT);

}

void turnlightsoff() { // a function
  digitalWrite(redPin, LOW);
  digitalWrite(yellowPin, LOW);
  digitalWrite(greenPin, LOW);
}



void loop() {

boolean  buttonStatus = digitalRead(buttonPin);

  if (buttonStatus == HIGH) {
    delay(1000);
 if (buttonStatus == HIGH) {
    ali = ali + 1;
    if (ali > 2) {
 ali = 0; 
}
  }
 }

if (ali == 0) {
  digitalWrite(greenPin, LOW);
  digitalWrite(redPin, HIGH); delay(500);
 
  } 
  else if (ali == 1) {
  digitalWrite(redPin, LOW);
  digitalWrite(yellowPin, HIGH);delay(500);

  }
  else if (ali == 2) {
    
  digitalWrite(yellowPin, LOW);
  digitalWrite(greenPin, HIGH);delay(500);
  
  }
  
  else 
  { 
    turnlightsoff();
  }
  }

Well for starters:

pinMode(buttonPin, OUTPUT);

chummer1010:
Well for starters:

pinMode(buttonPin, OUTPUT);

it's weird that the button is functioning well :o

Hi,
Welcome to the Forum

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?
Please not a fritzy diagram.

How have you got your buttons wired, do you have pullup or pulldown resistors on them.

Thanks.. Tom... :slight_smile:

How about remembering the last status and not doing anything unless it goes from LOW to HIGH?

const int greenPin = 4; // green led pin
const int yellowPin = 3;
const int redPin = 2;
const int buttonPin = 12;
int ali = 0;
boolean  oldButtonStatus = LOW;

void setup() {

  for (int i = 2; i <= 4; i++) { // setting outputs
    pinMode(i, OUTPUT);
  }

  pinMode(buttonPin, INPUT);

}

void turnlightsoff() { // a function
  digitalWrite(redPin, LOW);
  digitalWrite(yellowPin, LOW);
  digitalWrite(greenPin, LOW);
}



void loop() {

  boolean  buttonStatus = digitalRead(buttonPin);

  if (buttonStatus == HIGH && buttonStatus != oldButtonStatus) {
    delay(1000);
    if (buttonStatus == HIGH) {
      ali = ali + 1;
      if (ali > 2) {
        ali = 0;
      }
    }
  }

  oldButtonStatus = buttonStatus;

  if (ali == 0) {
    digitalWrite(greenPin, LOW);
    digitalWrite(redPin, HIGH); delay(500);

  }
  else if (ali == 1) {
    digitalWrite(redPin, LOW);
    digitalWrite(yellowPin, HIGH); delay(500);

  }
  else if (ali == 2) {

    digitalWrite(yellowPin, LOW);
    digitalWrite(greenPin, HIGH); delay(500);

  }

  else
  {
    turnlightsoff();
  }
}