Hi, I'm having some troubles with this. My intentions are for the motors are supposed to continuously until it detects something within the range of 100cm. I got a diagram with the code, which in theory should work (when I run the code it uploads without errors). Could someone tell me if it is supposed to work or not? Because then I could troubleshoot for loose wiring/faulty components etc. If any kind soul could help, it would be amazing! Thank you
image of my wiring & diagram: Imgur: The magic of the Internet
my code:
define echoPin 7 // Echo Pin
define trigPin 8 // Trigger Pin
define relayPin 13 // Relay Pin
int objectRange = 20; // Object range needed in cm
long duration; long distance;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW);
}
void loop() {
getDistance();
Serial.println("Distance = " + String(distance) + "cm"); //remove this serial print if not essential, it will speed up the response.
if (distance > objectRange) {
Serial.println("Relay On");
digitalWrite(relayPin, HIGH);
}
else { Serial.println("Relay Off");
digitalWrite(relayPin, LOW); }
delay(50);
}
void getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration/58.2;
}