Created
August 27, 2015 07:33
-
-
Save pingud98/baf670f1cf1cb11b0f4a to your computer and use it in GitHub Desktop.
HC-SR04 ultrasonic position sensor - without any wiring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks ! At least I know that sensor is working !