Advertisement
Guest User

Nano_ultrasonic_sensor

a guest
Jan 18th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. /*
  2. HC-SR04 Ping distance sensor]
  3. VCC to arduino 5v GND to arduino GND
  4. Echo to Arduino pin 13 Trig to Arduino pin 12
  5. Red POS to Arduino pin 11
  6. Green POS to Arduino pin 10
  7. 560 ohm resistor to both LED NEG and GRD power rail
  8. More info at: http://goo.gl/kJ8Gl
  9. Original code improvements to the Ping sketch sourced from Trollmaker.com
  10. Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
  11. */
  12.  
  13. #define trigPin 3
  14. #define echoPin 2
  15. #define led 11
  16. #define led2 10
  17.  
  18. void setup() {
  19.   Serial.begin (9600);
  20.   pinMode(trigPin, OUTPUT);
  21.   pinMode(echoPin, INPUT);
  22.   pinMode(led, OUTPUT);
  23.   pinMode(led2, OUTPUT);
  24. }
  25.  
  26. void loop() {
  27.   long duration, distance;
  28.   digitalWrite(trigPin, LOW);  // Added this line
  29.   delayMicroseconds(2); // Added this line
  30.   digitalWrite(trigPin, HIGH);
  31. //  delayMicroseconds(1000); - Removed this line
  32.   delayMicroseconds(10); // Added this line
  33.   digitalWrite(trigPin, LOW);
  34.   duration = pulseIn(echoPin, HIGH);
  35.   distance = (duration/2) / 50;
  36.   if (distance < 4) {  // This is where the LED On/Off happens
  37.     digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
  38.     digitalWrite(led2,LOW);
  39.   }
  40.   else {
  41.     digitalWrite(led,LOW);
  42.     digitalWrite(led2,HIGH);
  43.   }
  44.   if (distance >= 200 || distance <= 0){
  45.     Serial.println("Out of range");
  46.   }
  47.   else {
  48.     Serial.print(distance);
  49.     Serial.println(" cm");
  50.   }
  51.   delay(500);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement