E_H
July 22, 2019, 10:26pm
1
With the attached code I am using at HC-SR04 ultrasonic sensor, uppon reading a value from the sensor and printing to the serial monitor which seems to be working. The problem I'm having and can't find a solution through my own experimentation is that the IF statement seems to not function correctly, it outputs the initial condition and then does not reset through the else statement.
Arduino_HC-SR04_Test.ino (1.02 KB)
system
July 22, 2019, 11:53pm
2
OP's code properly placed in code tags.
const int trigPinRight = 4;
const int echoPinRight = 5;
long durationRight;
int distanceRight;
const int LEDRight = 10;
const int VibrationRight = 8;
void setup() {
// put your setup code here, to run once:
pinMode(trigPinRight, OUTPUT);
pinMode(echoPinRight, INPUT);
pinMode(LEDRight, OUTPUT);
pinMode(VibrationRight, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigPinRight, LOW);
digitalWrite(LEDRight, LOW);
digitalWrite(VibrationRight, LOW);
delayMicroseconds(2);
digitalWrite(trigPinRight, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinRight, LOW);
delayMicroseconds(100);
durationRight = pulseIn(echoPinRight, HIGH);
distanceRight = durationRight * 0.034 / 2;
if (digitalRead(distanceRight) <= 2) {
digitalWrite(LEDRight, HIGH);
digitalWrite(VibrationRight, HIGH);
}
else {
digitalWrite(LEDRight, LOW);
digitalWrite(VibrationRight, LOW);
}
Serial.print("DistanceRight: ");
Serial.println(distanceRight);
delay(1000);
}
blh64
July 22, 2019, 11:55pm
3
the variable 'distanceRight' is not a pin on which to read the digital value
if (digitalRead(distanceRight) <= 2){
...
just use the variable directly
if (distanceRight <= 2){
...