kowalyshyn_o

Ultrasonic Sensor

Mar 1st, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. /*
  2.   Distance Measurement
  3.   Hookup instructions:
  4.   HC-SR04: VCC to arduino 5V,GND to arduino GND
  5.   Echo to Arduino pin 8 Trig to Arduino pin 7
  6.   Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
  7.   Measurement is continually displayed on LCD
  8.   To operate, press momentary switch to take a reading.
  9. */
  10.  
  11. #include <LiquidCrystal.h>
  12.  
  13. //Define pins for Ultrasonic Range Finder
  14. #define trigPin 7
  15. #define echoPin 8
  16.  
  17. //Define switch pin
  18. #define switchPin 9
  19.  
  20. //Define pins for LCD display
  21. #define RS 12     // Register Select Pin (RS)
  22. #define EN 11     // Enable Select Pin (EN)
  23. #define D4 5      // 4 Data pins
  24. #define D5 4
  25. #define D6 3
  26. #define D7 2
  27.  
  28. //Create objects
  29. int duration, distance, switchRead;
  30. LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);
  31.  
  32. void setup() {
  33.   Serial.begin (9600);
  34.   lcd.begin(16, 2);
  35.  
  36.   pinMode(trigPin, OUTPUT);             //Set Trigger pin to OUTPUT
  37.   pinMode(echoPin, INPUT);              //Set Echo pin to INPUT
  38.   pinMode(switchPin, INPUT);            //Set input for switch
  39.   digitalWrite(trigPin, LOW);           //Turn OFF Trigger
  40. }
  41.  
  42. void loop() {
  43.  
  44.   switchRead = digitalRead(switchPin);    //Switch pulled to ground with 1M ohm resistor (0 V)
  45.  
  46.   if (switchRead == HIGH) {               //Take measurement only when button is pressed (5V present)
  47.  
  48.     digitalWrite(trigPin, HIGH);          //send a burst PING for 10us (microseconds)
  49.     delayMicroseconds(10);
  50.     digitalWrite(trigPin, LOW);
  51.  
  52.     duration = pulseIn(echoPin, HIGH);        //return duration of PING
  53.     distance = (duration / 2) / 29.1;         //formula convert to cm
  54.  
  55.     if (distance < 550 && distance > 0) {
  56.  
  57.       Serial.println(String(distance) + " cm");
  58.  
  59.       lcd.setCursor(0, 0);
  60.       lcd.print("Distance");
  61.       lcd.setCursor(0, 1);
  62.       lcd.print(String(distance) + " cm     ");
  63.       delay(200);
  64.     }
  65.  
  66.     if (distance < 0) {
  67.       lcd.setCursor(0,1);
  68.       lcd.print("Out of Range   ");
  69.     }
  70.    
  71.   }
  72. } // end loop
Add Comment
Please, Sign In to add comment