Week 9: Parking sensor

THE Parking sensor

For this project, we had only two sensor options: the LDR or the ultrasonic sensor. Since we’d already used the LDR before, I wanted to try out something new. So, I looked into the ultrasonic sensor and started working with it. While brainstorming, I came up with various game ideas that used the sensor, but they needed a screen, which wasn’t allowed for this assignment. After more research on ultrasonic sensors, I found they could work well as a car parking alarm to help drivers avoid hitting obstacles. I started writing the code and set up a variable called “time_delay” to control how fast the LED blinks. To make it more like a real parking sensor, I decided to add a buzzing sound and found out how to connect a buzzer to the setup. With these changes, I made a working parking sensor. To meet the assignment’s requirements for a switch and a second LED, I made a switch that, when pressed, turns on a bulb that matches its color.

THE CODE:

const int trigPin = 9;
const int echoPin = 10;

int led = 5;

long duration;
int distance;

const int buzzer = 13;

const int buttonPin = 2;  // the number of the pushbutton pin
const int ledPin = 8; // the second light

int buttonState = 0; // button bool

void setup() {
  // put your setup code here, to run once:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  pinMode(led, OUTPUT); //light
  pinMode(buzzer, OUTPUT); // buzzer

 
  pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
  pinMode(buttonPin, INPUT);  // initialize the pushbutton pin as an input
  

  Serial.begin(9600);


}

void loop() {
  //sending the audio pulses
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
//calculating distance
  duration = pulseIn(echoPin, HIGH);
  distance= duration*0.034/2;

//the warning rate
  float time_delay= (distance *3) +30;

  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }

  if(distance < 50)
  {
    //the warning / buzzing rate
    digitalWrite(buzzer, HIGH);
    analogWrite(led,0);
    delay(time_delay);
    digitalWrite(buzzer,LOW);
    analogWrite(led,255);

  }
  
  else{
    digitalWrite(led, LOW);
    noTone(buzzer);
  }

  //for feedback
  Serial.print("Distance: ");
  Serial.println(distance);


}

 

This is how it looked like

Video:

 

Leave a Reply