Created
July 25, 2017 15:31
-
-
Save iotguider/64f61a87a640b724dba2f23fc886698d to your computer and use it in GitHub Desktop.
Code for Ultrasonic Sensor HC-SR04 in Arduino
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
#define trigPin 13 | |
#define echoPin 12 | |
void setup() { | |
Serial.begin (9600); // Begin the Serial Monitor at 9600 Baud | |
pinMode(trigPin, OUTPUT); // Initialize Trigger Pin | |
pinMode(echoPin, INPUT); // Initialize Echo Pin | |
} | |
void loop() { | |
long duration, distance; // Duration varible stores time duration taken by ultrasonic and Distance variable stores distance | |
digitalWrite(trigPin, LOW); // Set Trigger Pin Low | |
delayMicroseconds(2); // Delay | |
digitalWrite(trigPin, HIGH); // Set Trigger Pin High | |
delayMicroseconds(10); // Delay | |
digitalWrite(trigPin, LOW); // Set Trigger Pin Low | |
duration = pulseIn(echoPin, HIGH); // Set Echo Pin High to set time to variable | |
distance = (duration/2) / 29.1; // Convert time into distance | |
Serial.print(distance); // Print distance to Serial Monitor | |
Serial.println(" cm"); | |
delay(500); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment