Below is the Arduino code for use with the HC-SR04 Ultrasonic sensor:
/*
* HC-SR04 example
* by DIYrobots
* March 2019
*/
#define trigger 7// use your own pin definitions
#define echo 8//use your own pin definitions
long duration;
int distance;
void setup() {
pinMode(trigger, OUTPUT); // Sets the trigger pin as an Output
pinMode(echo, INPUT); // Sets the echo pin as an Input
Serial.begin(9600); // Starts the serial communication
Serial.println("HC-SR04 readings in centimeters \n By DIYrobots");
}
void loop() {
// Clears the trigger pin
digitalWrite(trigger, LOW);
delayMicroseconds(5);
// Sets the trigger pin high for 10 microseconds (1/100000 of a second)
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
// Reads the echo pin, returns the data from the ultrasonic sensor
duration = pulseIn(echo, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
delay(1000);
}
* HC-SR04 example
* by DIYrobots
* March 2019
*/
#define trigger 7// use your own pin definitions
#define echo 8//use your own pin definitions
long duration;
int distance;
void setup() {
pinMode(trigger, OUTPUT); // Sets the trigger pin as an Output
pinMode(echo, INPUT); // Sets the echo pin as an Input
Serial.begin(9600); // Starts the serial communication
Serial.println("HC-SR04 readings in centimeters \n By DIYrobots");
}
void loop() {
// Clears the trigger pin
digitalWrite(trigger, LOW);
delayMicroseconds(5);
// Sets the trigger pin high for 10 microseconds (1/100000 of a second)
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
// Reads the echo pin, returns the data from the ultrasonic sensor
duration = pulseIn(echo, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
delay(1000);
}
What the code does:
This code pulses the HC-SR04 sensor's output and turns the raw output into the value in centimeters.
It then displays the values in the Arduino IDE's Serial Monitor.
It then displays the values in the Arduino IDE's Serial Monitor.