UltraSonicFun

2017-08-15 02:50:03 +0000 - Written by Carl Burks

I've been playing with my Arduinos more now that I have a more than decent soldering iron. I was reading online and someone built a device for the garage which would help them park. I picked up some ultrasonic sensors from Amazon HC-SR04. The LEGO NXT has a similar sensor.

Want to learn about Ultrasonic Distance Sensors?

After plugging that up to a breadboard I checked to make sure things were working.

First I needed to find the right library:

I looked in Library Manager for "Ultrasonic" and someone had a coded one:

Erick Simões

#include </code></pre>

and you are off to the races.

Next I played around with a 4 pin RGB LED the pin out didn't really match and the examples I found online didn't work. I tried several combinations of things and time boxed myself. I exceeded the amount of time I wanted to spend, so I went with plan B. Plan B involved more soldering, so it probably was better for me anyway. I took another board and soldered three LEDs, one red, one yellow, and one green. With three resistors and header pins, I had finished my indicators. I wired everything together and here is the code I ended up with:



#include 

// UltraSonic
#define TRIGGER_PIN 5
#define ECHO_PIN 6

// Indicator Lights
#define YELLOW_LED 3
#define RED_LED 2
#define GREEN_LED 4

#define WINDSHIELD_TO_BUMPER_OFFSET_IN_CM 101 

#define RED_ZONE_IN_CM  8 
#define YELLOW_ZONE_IN_CM 50

#define BLINK_RATE_IN_MS  500

int _active_led = GREEN_LED;
int _distance_in_cm = 0;
Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(YELLOW_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);
}


void blink(int pin){
  digitalWrite(pin, HIGH);
  delay(BLINK_RATE_IN_MS);
  digitalWrite(pin, LOW);
  delay(BLINK_RATE_IN_MS);  

}
void loop() {
  _distance_in_cm = ultrasonic.distanceRead();
  Serial.println(_distance_in_cm);
  _distance_in_cm -= WINDSHIELD_TO_BUMPER_OFFSET_IN_CM;
  
  _active_led = GREEN_LED;
  if(_distance_in_cm < YELLOW_ZONE_IN_CM){
    if(_distance_in_cm < RED_ZONE_IN_CM){
      _active_led = RED_LED;
    } else {
      _active_led = YELLOW_LED;
    }
  }
  blink(_active_led);
}
</code></pre>

After that I needed an enclosure. The local hobby place had had a sail recently and I picked up a Paper case for a quite a deal. Then I cut a bit of foam to cover the LEDs.

Here is what I ended up with:

Ultrasonic Garage Sensor with LEDs in case illuminated - Pareidolia

Ultrasonic Garage Sensor with LEDs in case illuminated - Pareidolia

Ultrasonic Garage Sensor with LEDs in case in the light - Pareidolia

Ultrasonic Garage Sensor with LEDs in case in the light - Pareidolia