Description of Arduino code and include or link to full Arduino sketch
/*
* created by Rui Santos, https://randomnerdtutorials.com
*
* Complete Guide for Ultrasonic Sensor HC-SR04
*
Ultrasonic sensor Pins:
VCC: +5VDC
Trig : Trigger (INPUT) - Pin11
Echo: Echo (OUTPUT) - Pin 12
GND: GND
*/
int potPinA = A1;
int potPinB = A2;
int trigPinA = 8; // Trigger
int echoPinA = 9; // Echo
int trigPinB = 10; // Trigger
int echoPinB = 11; // Echo
int potValA;
int potValB;
int prevSenValA;
int prevSenValB;
long durationA;
long durationB;
long cma, cmb, inches;
void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(potPinA,INPUT);
pinMode(potPinB,INPUT);
pinMode(trigPinA, OUTPUT);
pinMode(echoPinA, INPUT);
pinMode(trigPinB, OUTPUT);
pinMode(echoPinB, INPUT);
}
void loop() {
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPinA, LOW);
delayMicroseconds(5);
digitalWrite(trigPinA, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinA, LOW);
potValA = analogRead(potPinA);
potValB = analogRead(potPinB);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPinA, INPUT);
durationA = pulseInLong(echoPinA, HIGH);
digitalWrite(trigPinB, LOW);
delayMicroseconds(5);
digitalWrite(trigPinB, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinB, LOW);
pinMode(echoPinB, INPUT);
durationB = pulseInLong(echoPinB, HIGH);
// Convert the time into a distance
cma = (durationA/2) / 29.1;
cmb = (durationB/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
if(cma < 500) {
prevSenValA = cma;
} else {
cma = prevSenValA;
}
if(cmb < 500) {
prevSenValB = cmb;
} else {
cmb = prevSenValB;
}
Serial.print(cmb);
Serial.print(", ");
Serial.print(cma);
Serial.print(", ");
Serial.print(potValB);
Serial.print(", ");
Serial.print(potValA);
Serial.println();
delay(50);
}