Assignment 7 – Sensors and Push Buttons

Concept

My idea for this project was to come up with something similar to an alarm system. I chose to work with the ultrasonic distance sensor to create an alarm based on proximity. I implement the system using to LED’s where one is for indicating the distance and is the analog control and the other is the alarm indicator, digital control. The latter LED gives a visual feedback of the distance from an oncoming object and acts as an alert. When the object is outside the 40 cm radius of the sensor the LED is completely off indicating no threat but when an object moves into the 40cm radius the LED starts to light gradually depending on the distance from the sensor; when distance is big the LED is dim and when distance continues to be shorter and shorter the LED also gradually increases brightness to alert someone to turn on the alarm.

Sketch/Setup

Code Highlight

void loop() {
  // Distance from sensor
  int distance = getDistance();

  // State of the switch
  alarmEnabled = digitalRead(switchPin) == LOW; 

  // Analog LED brightness based on distance
  int brightness = map(distance, 5, 50, 255, 0); // distances between 5 cm and 50 cm
  brightness = constrain(brightness, 0, 255);     // Limit brightness to range
  analogWrite(analogLedPin, brightness);

  // If alarm is enabled and distance is below threshold, blink alarm LED
  if (alarmEnabled && distance < distanceThreshold) {
    digitalWrite(digitalLedPin, HIGH);
    delay(200);
    digitalWrite(digitalLedPin, LOW);
    delay(200);
  } else {
    digitalWrite(digitalLedPin, LOW); // Keep alarm LED off
  }

  //Debug
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.print(" cm | Alarm: ");
  Serial.println(alarmEnabled ? "ON" : "OFF");

  delay(100); 
}

The above is the part of my code which I am proud of how I implemented. In the code I use the distance value which is picked from the sensor to control both LEDs. I control the analog LED based on the distance and to do this I limit the LEDs readings to the distance by mapping then to have a gradual increase in brightness I use constrain so that the difference can be visually perceived.

 

Video demonstration

Reflection and Future improvements

Implementing the project was really fun as it gave me a space to actualise my idea of creating an alarm in an interesting way. I am proud of how I implemented the alarm system. However, there is still room for improvement as I would want  the system to have sound which goes off when the alarm is triggered. Overall, I enjoyed executing the project and further understanding Arduino.

Leave a Reply