Advertisement
Guest User

(HC-SR04) Ultrasonic Arduino? Easy!

a guest
Nov 6th, 2015
1,009
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int vcc     = 10;
  2. int trigger = 11;
  3. int echo    = 12;
  4. int gnd     = 13;
  5.  
  6. void setup() {
  7.  
  8.   Serial.begin(9600);
  9.  
  10.   pinMode(echo, INPUT);
  11.  
  12.   pinMode(trigger, OUTPUT);
  13.   digitalWrite(trigger, LOW);
  14.  
  15.   pinMode(vcc, OUTPUT);
  16.   digitalWrite(vcc, HIGH);
  17.  
  18.   pinMode(gnd, OUTPUT);
  19.   digitalWrite(gnd, LOW);  
  20.  
  21. }
  22.  
  23. void loop() {
  24.  
  25.   long duration, inches, cm;
  26.  
  27.   digitalWrite(trigger, LOW); // Make sure trigger is LOW by default
  28.   delayMicroseconds(10);
  29.  
  30.   digitalWrite(trigger, HIGH); // 12ms pulse on trigger
  31.   delayMicroseconds(12);
  32.   digitalWrite(trigger, LOW); // Back to LOW
  33.  
  34.   duration = pulseIn(echo, HIGH); // Measuring the length of the ECHO pulse
  35.                            
  36.   cm=duration/58;
  37.   inches=duration/148;
  38.  
  39.  
  40.   // Print Data Serial (9600)
  41.  
  42.   if (cm > 100 || cm<3){     // Range: 3-100 cm
  43.     Serial.println("N/A");  
  44.     }
  45.   else{
  46.     Serial.print(cm);
  47.     Serial.print("   ");
  48.     Serial.println(inches);
  49.   }
  50.  
  51.   delay(100);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement