Beep Beep, Stuck in Traffic!

For this weeks assignment, I chose a very corny heading (sorry for that) but at the same time I combined some of the reading work we have previously done and implemented into the assignment.

My Inspiration came from the car industry, which is something I mentioned in one of my previous reading assignments. Since we are working with lights I thought that it would be a good idea to mimic some of the headlights that I’ve seen on never cars.

The way this lights work are:

  • When the driver turns to the left, the corresponding light turns on
  • When the driver turns to the right, the corresponding light turns on
  • The lights dim (in a way that if the turn is sharper, the light would be brighter)

To mimic this I used a potentiometer as well as two lights(logically :). For a fun element, I also added a buzzer and a button that activates that buzzer like a car horn would.

Here is the code I used:

int potentiometer = A0;
const int led0 = 5;
const int led1 = 6;
const int buttonPin = 7;
int buttonRead = 0;
const int buzzerPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(led0, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  buttonRead = digitalRead(buttonPin);
  Serial.println(buttonRead);
  int potentiometerValue = analogRead(potentiometer);
  int pwmValue1 = map(potentiometerValue, 0, 512, 255, 0); // Map potentiometer value for LED0
  int pwmValue2 = map(potentiometerValue, 513, 1023, 0, 255); // Map potentiometer value for LED1

  // Check if the button is pressed (buttonRead is HIGH)
  if (buttonRead == HIGH) {
    // Turn on the buzzer
    analogWrite(buzzerPin, HIGH);
  } else {
    // Turn off the buzzer
    analogWrite(buzzerPin, LOW);
  }

  if (potentiometerValue >= 0 && potentiometerValue <= 512) {
    analogWrite(led0, pwmValue1); // Dim LED0
    analogWrite(led1, 0); // Turn off LED1
  } else {
    analogWrite(led0, 0); // Turn off LED0
    analogWrite(led1, pwmValue2); // Dim LED1
  } 
}

Basically what the code does is it takes the potentiometer values, and maps them to the lights correspondigly. At the same time, the button turns the buzzer on and off.

Video demonstration:

 

Leave a Reply