Skip to content

Instantly share code, notes, and snippets.

@teomaragakis
Last active November 25, 2015 12:54
Show Gist options
  • Save teomaragakis/612000438f1c1927f91f to your computer and use it in GitHub Desktop.
Save teomaragakis/612000438f1c1927f91f to your computer and use it in GitHub Desktop.
HC-SR04 ultrasonic range finder test code. Read the full blog post on www.teomaragakis.com/hardware/electronics/testing-the-hc-sr04-ultrasonic-range-sensor/
/*
+-----+
+----[PWR]-------------------| USB |--+
| +-----+ |
| GND/RST2 [ ][ ] |
| MOSI2/SCK2 [ ][ ] A5/SCL[ ] | C5
| 5V/MISO2 [ ][ ] A4/SDA[ ] | C4
| AREF[ ] |
| GND[ ] |
| [ ]N/C SCK/13[ ] | B5
| [ ]v.ref MISO/12[ ] | .
| [ ]RST MOSI/11[ ]~| .
| [ ]3V3 +---+ 10[ ]~| .
| [X]5v | A | 9[ ]~| .
| [X]GND -| R |- 8[ ] | B0
| [ ]GND -| D |- |
| [ ]Vin -| U |- 7[ ] | D7
| -| I |- 6[ ]~| .
| [ ]A0 -| N |- 5[ ]~| .
| [ ]A1 -| O |- 4[ ] | .
| [ ]A2 +---+ INT1/3[X]~| .
| [ ]A3 INT0/2[X] | .
| [ ]A4/SDA RST SCK MISO TX>1[ ] | .
| [ ]A5/SCL [ ] [ ] [ ] RX<0[ ] | D0
| [ ] [ ] [ ] |
| UNO_R3 GND MOSI 5V ____________/
\_______________________/
http://busyducks.com/ascii-art-arduinos
*/
#define trig 2
#define echo 3
void setup() {
Serial.begin (9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop() {
float duration, distance;
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = duration / 58;
Serial.print(distance);
Serial.println(" cm");
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment