/* --------------------------------------------------------------- * Example code for HC-SR04 ultrasonic distance sensor with Arduino. * https://www.makerguides.com/hc-sr04-arduino-tutorial/ * No library is required to use this sensor. * Setup: * HC-SR04 has 4 connections: 5v, Gnd * echo -> pin2 * trig -> pin3 ----------------------------------------------------------------*/ // Define Trigger and Echo pin: #define trigPin 3 #define echoPin 2 long duration; int distance; void setup() { // Define inputs and outputs: pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); //Begin Serial communication at a baudrate of 9600: Serial.begin(9600); } void loop() { // "Clear" the trigPin by setting it LOW: digitalWrite(trigPin, LOW); delayMicroseconds(5); // Generate pulse by setting the trigPin high for 10 microseconds: digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds: duration = pulseIn(echoPin, HIGH); // Calculate the distance: distance = duration * 0.034 / 2; // Print the distance on the Serial Monitor (Ctrl+Shift+M): Serial.print("Distance = "); Serial.print(distance); Serial.println(" cm"); delay(50); } |