Assignment due in an hour and im screwed - problem with my microswitch


Im doing a set of traffic lights and when the microswitch is pushed it is meant to start the changeLights sequence but it doesn’t do that.

Here is my code

#include <Servo.h>
Servo servoMain; // Define our Servo      // servo paramaters and definitions added 
const int buttonPin = 7;
int buttonState = 0;
int servo = 5;
void setup() {
  // put your setup code here, to run once:
  servoMain.attach(5); // servo on digital pin 5       // servo assigned to digital pin;
  // put your main code here, to run repeatedly:
  // intialise digital pin 9 as green. pinMode(9, GREEN);
  // intialise digital pin 10 as red. pinMode(10, RED);
  // intialise digital pin 11 as yellow, pinMode(11, YELLOW);
  // intialise digital pin 2 as red2, pinMode(2, RED2);
  // intialise digital pin 3 as yellow2, pinMode(3, YELLOW2);
  // intialise digital pin 4 as green2, pinMode(4, GREEN2);
  // initialize the pushbutton pin as an input:
  pinMode (9, OUTPUT);
  pinMode (10, OUTPUT);
  pinMode (11, OUTPUT);
  pinMode (2, OUTPUT);
  pinMode (3, OUTPUT);
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (7, INPUT);
  digitalWrite (2, HIGH);
  digitalWrite (9, HIGH);
  buttonState = digitalRead(buttonPin);
void loop() {
if ((buttonState) == HIGH){
        delay(15); // software debounce
 if (buttonState == HIGH) {
  changeLights ();
  } else {
 digitalWrite (9, HIGH);
    digitalWrite (2, HIGH);
void changeLights () {
  delay (1000);
  digitalWrite(9, HIGH);
  digitalWrite (2, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(11, HIGH);
  digitalWrite(11, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(2, LOW);
  digitalWrite (4, HIGH);
  // this is where the servo code was spliced in
  servoMain.write(0);   // Turn Servo Left to 0 degrees
  delay(8000);          // Wait 2 seconds
  digitalWrite(4, LOW);
  delay (1000);
  digitalWrite(3, HIGH);
  digitalWrite(3, LOW);
  delay (1000);
  digitalWrite(2, HIGH);
  delay (2000);
  servoMain.write(180); // Turn Servo Right to 180 degrees
  delay(2000);          // Wait 2 seconds
  digitalWrite (10, LOW);
  digitalWrite (9, HIGH);

You need to read the buttonPin in the loop() function.

With your current code, you need a pull-down resistor on the buttonPin.


I currently have a 330 ohm resistor attached to the button pin. I tried doing it with just a normal button and not a microswitch and it still didn't work

Switch review:

ok so i just tried swapping my button out for my microswitch and that didn't work either, however, I went back to basics and did the button example with both the button and the microswitch it worked for the button but not the microswitch

after countless trial and error i have come to the conclusion that my else statement is wrong is there any possibility that someone could have a look at that and see if I have made an error please and thank you

As stated, you need a digitalRead(buttonPin) inside the loop() function.

ok thank you soo much