So I've been trying to program an ultrasonic sensor to read the distance from an object, but for some reason it won't work and keeps reading zero. I thought it was a hardware issue at first, but I've realized that that might not be the case since I've tried using 3 different sensors.
Here is my code:
const int triggerPin = 12; //Trigger connected to PIN 12
const int echoPin = 10; //Echo connected to PIN 10
int buz = 5; //Buzzer to PIN 5
int vibmotor = 3; //vibration motor connected to PIN 3
int inches = 0;
int cm = 0;
long duration;
int distance;
//https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
void setup() {
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buz, OUTPUT); //makes the buzzer an output
pinMode(2, OUTPUT); //makes the LED an output
pinMode(3, OUTPUT); //makes the vibration motor an output
Serial.begin(9600);
}
void loop()
{
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration*0.01723;
distance = distance/2.54;
Serial.print("Distance:");
Serial.print(distance);
Serial.println(" inches");
if(distance <= 24)
{
//Makes the buzzer buzz
digitalWrite(buz, HIGH);
//Makes the LED flash
digitalWrite(2, HIGH);
//Makes the vibration motor vibrate
digitalWrite(vibmotor, HIGH);
}
else {
digitalWrite(buz, LOW);
digitalWrite(2, LOW);
digitalWrite(vibmotor, LOW);
}
}
Could it be a problem with the code?? If so, what?