TweetLast week two new components for my Arduino arrived in the mail:

16×2 LCD (Liquid Crystal Display) Module

SainSmart HC-SR04 Ranging Detector Mod Distance Sensor

So of course I had to combine the two into a project!

I started off by using the ranging sensor to read the distance of objects directly in front of it (based on this instructable). I then used this data to change the color of a RGB LED. So it lights up green if there is nothing within 30cm, then turns blue when something gets within 20cm and then red when closer than 10cm.

The idea behind this is I am hoping to integrate this into an upcoming robot/car project. I’m hoping to have the robot stop itself before crashing into a wall (or my kid or a cat!) One step at a time though!!

Once I had this working, I thought it would be cool to display the distance on the LCD. The first thing I had to do was solder the header pins into the LCD board (this was a kind of huge step for me, as I’d never used a soldering iron before, so it was pretty exciting stuff!)

I used the awesome adafruit tutorial to wire up the LCD and updated the code to output the distance.

Here’s how it looked running:

Distance Sensor running

Circuit

Schematic

Code

// include the library code: #include <LiquidCrystal.h> const int RED_PIN = 9; const int GREEN_PIN = 10; const int BLUE_PIN = 11; const int ECHO_PIN = 6; const int TRG_PIN = 7; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(0, 1, 5, 4, 3, 2); void setup() { // put your setup code here, to run once: pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(TRG_PIN, OUTPUT); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("Distance (cm):"); // Serial.begin(9600); } void loop() { long duration,distance; // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(TRG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRG_PIN, LOW); duration = pulseIn(ECHO_PIN, HIGH); distance = (duration/2) / 29.1; //Serial.print(distance); // Serial.println(); digitalWrite(RED_PIN, LOW); digitalWrite(GREEN_PIN, LOW); digitalWrite(BLUE_PIN, LOW); if (distance <= 10) { digitalWrite(RED_PIN, HIGH); } else if (distance <= 20) { digitalWrite(BLUE_PIN, HIGH); } else{ digitalWrite(GREEN_PIN, HIGH); } lcd.setCursor(0, 1); lcd.print(" "); lcd.setCursor(0, 1); lcd.print(distance); delay(300); }