Week 9: Traffic light controller

Concept

For this assignment, I decided to make a traffic light that can be controlled by the enemy and get broken. It gets broken by using the potentiometer, which turns it off or turns all the lights on at the same time which can create a huge traffic jam. However, policemen can make it work by clicking the button, which lets the lights turn on one by one.

Code

int potpin = 2;  // analog pin used to connect the potentiometer
int val; 
void setup() {
  pinMode(7, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(A2, INPUT);
}

void loop() {

  int switchPosition = digitalRead(A2);
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 360); 
  if (switchPosition == LOW) {
    digitalWrite(4, val);   
    digitalWrite(2, val);
    digitalWrite(7, val);
    


  } else  {

    digitalWrite(7, HIGH);    // turn the  red LED on
    digitalWrite(4, LOW);
    digitalWrite(2, LOW);
    delay(500);
    digitalWrite(7, LOW);    // turn the yellow LED on
    digitalWrite(4, HIGH);
    digitalWrite(2, LOW);
    delay(500);
    digitalWrite(7, LOW);    // turn the green LED on
    digitalWrite(4, LOW);
    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(4, HIGH);   // turn all the lights on
    digitalWrite(2, HIGH);
    digitalWrite(7, HIGH);
  }
}

Reflection

Connecting several lights and making them light one by one was a really fun exercise. However, adding a potentiometer broke down my switch at some point, which made it difficult for me to control the LED light using it. For future improvements, I would like to be able to have different outputs when changing the potentiometer values when the switch is on and off, so the game mode can get difficult, so I can learn more about the potentiometer’s advanced features.

Leave a Reply