Skip to content

Instantly share code, notes, and snippets.

@pingud98
Created August 27, 2015 07:33
Show Gist options
  • Save pingud98/baf670f1cf1cb11b0f4a to your computer and use it in GitHub Desktop.
Save pingud98/baf670f1cf1cb11b0f4a to your computer and use it in GitHub Desktop.
HC-SR04 ultrasonic position sensor - without any wiring
/*
A (neat) cheat way of getting the HC-SR04 distance sensor working on an Arduino Uno
put it in the end, with the GND aligned with the GND pin next to pin 13 and AREF
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
//int led = 13;
int echopin = 13;
int trigpin = 12;
int vcc = 11;
// the setup routine runs once when you press reset:
void setup() {
pinMode(echopin, INPUT);
pinMode(trigpin, OUTPUT);
pinMode(vcc, OUTPUT);
digitalWrite(vcc, HIGH);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
long duration, distance;
digitalWrite(trigpin, LOW); // Added this line
delayMicroseconds(4); // Added this line
digitalWrite(trigpin, HIGH);
delayMicroseconds(20); // Added this line
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
@bcopy
Copy link

bcopy commented Aug 27, 2015

Thanks ! At least I know that sensor is working !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment