SHARE
TWEET

HC-SR04

tuixte Mar 5th, 2013 212 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const int triggerPort = 7;
  2. const int echoPort = 8;
  3.  
  4. void setup(){
  5.   pinMode(triggerPort, OUTPUT);
  6.   pinMode(echoPort, INPUT);
  7.   Serial.begin(9600);
  8.   Serial.println("Ready.");
  9. }
  10.  
  11. void loop(){
  12.   digitalWrite(triggerPort, LOW);
  13.   digitalWrite(triggerPort, HIGH);
  14.   delayMicroseconds(10);
  15.   digitalWrite(triggerPort, LOW);
  16.  
  17.   long duration = pulseIn(echoPort, HIGH);
  18.   long distance = 0.017 * duration;
  19.  
  20.   Serial.print("Duration: ");
  21.   Serial.print(duration);
  22.   Serial.print(", ");
  23.   Serial.print("distance: ");
  24.   Serial.print(distance);
  25.   Serial.println(" cm");
  26.  
  27.   delay(100);
  28. }
RAW Paste Data
Want to get better at C++?
Learn to code C++ in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top