Week 10 – Arduino: analog input & output

Concept 
I built a cool project using an ultrasonic sensor and an Arduino! It measures the distance to objects and tells me how far away they are using LEDs. If something is close, a red light blinks faster the closer it gets – like a warning. A green light turns on if it’s further away, so I know it’s safe. I can even start and stop the sensor with a button, which is pretty neat.

Video 

Components Required:
Arduino Uno (or any compatible board)
Ultrasonic Sensor (HC-SR04 or similar)
Red LED
Green LED
220-ohm resistors (2 pieces) & 10k-ohm resistor
Push button
Jumper wires
Breadboard

Schematic

Code

const int trigPin = 3;    //Trig
const int echoPin = 2;    //Echo
const int redLedPin = 13;  //RedLED
const int greenLedPin = 12; //GreenLED
const int buttonPin = 4;  //PushButton

int blinkInterval = 500; //BlinkInterval
bool projectRunning = false; //FlagToStart

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);  //SetUltrasonicSensor 
  pinMode(echoPin, INPUT);
  pinMode(redLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); //SetButton 
}

void loop() {
  if (digitalRead(buttonPin) == LOW) { 
    projectRunning = !projectRunning; //Toggle project state
  }

  if (projectRunning) {
    //Measure distance with ultrasonic sensor
    long duration = 0;
    long distance = 0;
    int retryCount = 0;
    const int maxRetries = 5; //Set a max number of retries
    while (duration == 0 && retryCount < maxRetries) {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      retryCount++;
    }
  
    if (duration != 0) {
      distance = duration * 0.034 / 2; //Convert to cm
    }
  
    //Print distance to Serial Monitor
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");
  
    //Control LED based on distance
    if (distance <= 50) { 
      digitalWrite(greenLedPin, LOW);  
      blinkInterval = map(distance, 0, 50, 100, 1000); 
      digitalWrite(redLedPin, HIGH);   
      delay(blinkInterval);
      digitalWrite(redLedPin, LOW);    
      delay(blinkInterval);             
    } else {
      digitalWrite(redLedPin, LOW);     
      digitalWrite(greenLedPin, HIGH);   
    } 
  } else {
    //Turn off both LEDs when the project is not running
    digitalWrite(redLedPin, LOW);
    digitalWrite(greenLedPin, LOW);
  }
}

Building this project was a real learning curve! Seeing the LEDs react to the distance measurements was super cool, but getting there wasn’t always smooth sailing. The sensor readings were a bit wonky at first, picking up on random noise and stuff. I had to get creative with the code to filter that out and make sure it was actually measuring the right things.

Leave a Reply