Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Distance Measurement
- Hookup instructions:
- HC-SR04: VCC to arduino 5V,GND to arduino GND
- Echo to Arduino pin 8 Trig to Arduino pin 7
- Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
- Measurement is continually displayed on LCD
- To operate, press momentary switch to take a reading.
- */
- #include <LiquidCrystal.h>
- //Define pins for Ultrasonic Range Finder
- #define trigPin 7
- #define echoPin 8
- //Define switch pin
- #define switchPin 9
- //Define pins for LCD display
- #define RS 12 // Register Select Pin (RS)
- #define EN 11 // Enable Select Pin (EN)
- #define D4 5 // 4 Data pins
- #define D5 4
- #define D6 3
- #define D7 2
- //Create objects
- int duration, distance, switchRead;
- LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);
- void setup() {
- Serial.begin (9600);
- lcd.begin(16, 2);
- pinMode(trigPin, OUTPUT); //Set Trigger pin to OUTPUT
- pinMode(echoPin, INPUT); //Set Echo pin to INPUT
- pinMode(switchPin, INPUT); //Set input for switch
- digitalWrite(trigPin, LOW); //Turn OFF Trigger
- }
- void loop() {
- switchRead = digitalRead(switchPin); //Switch pulled to ground with 1M ohm resistor (0 V)
- if (switchRead == HIGH) { //Take measurement only when button is pressed (5V present)
- digitalWrite(trigPin, HIGH); //send a burst PING for 10us (microseconds)
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH); //return duration of PING
- distance = (duration / 2) / 29.1; //formula convert to cm
- if (distance < 550 && distance > 0) {
- Serial.println(String(distance) + " cm");
- lcd.setCursor(0, 0);
- lcd.print("Distance");
- lcd.setCursor(0, 1);
- lcd.print(String(distance) + " cm ");
- delay(200);
- }
- if (distance < 0) {
- lcd.setCursor(0,1);
- lcd.print("Out of Range ");
- }
- }
- } // end loop
Add Comment
Please, Sign In to add comment