Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Ultrasonic Sensor HC-SR04 and Arduino Tutorial
- *
- * Builded by Teodor Hristov
- * www.dev-hn.com
- *
- */
- // defines pins numbers
- int trig = 2;
- int echo = 3;
- int go = 4;
- // defines variables
- long duration;
- int distance;
- void setup() {
- pinMode(go, OUTPUT);
- pinMode(trig, OUTPUT); // Sets the trig as an Output
- pinMode(echo, INPUT); // Sets the echo as an Input
- Serial.begin(9600); // Starts the serial communication
- }
- void loop() {
- // Clears the trig
- digitalWrite(trig, LOW);
- delayMicroseconds(2);
- // Sets the trig on HIGH state for 10 micro seconds
- digitalWrite(trig, HIGH);
- delayMicroseconds(10);
- digitalWrite(trig, LOW);
- // Reads the echo, returns the sound wave travel time in microseconds
- duration = pulseIn(echo, HIGH);
- // Calculating the distance
- distance= duration*0.034/2;
- if (distance > 50){
- digitalWrite(go, HIGH);// High voltage on go or pin 4
- }
- else {
- digitalWrite(go, LOW);
- }
- // Prints the distance on the Serial Monitor
- Serial.print("Distance: ");
- Serial.println(distance);
- delay(250); //1/4 from 1 sec
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement