Hi, I'm starting to learn how to code and overall create circuits. I'm trying to make something but it doesn't work as I'm imagining it. It's an Ultrasonic Distance Sensor connected to an Arduino UNO, and I'm trying to add some lights so that the closer it gets to the sensor the more lights light up. There's also a buzzer that should turn on at a certain threshold.
What happens when I run the code is that every light as well as the buzzer turn on, regardless of the distance where the object is at.
I can't figure out why it won't work. Here's the code I have:
/*
*/
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int LEDred = 4;
const int LEDblue = 3;
const int LEDyellow = 2;
const int Buzzer = 7;
// defines variables
long duration;
int distance;
void setup()
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(LEDred, OUTPUT);
pinMode(LEDblue, OUTPUT);
pinMode(LEDyellow, OUTPUT);
pinMode(Buzzer, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop()
{
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
if(distance > 400);
{
digitalWrite (LEDred, LOW);
digitalWrite (LEDblue, LOW);
digitalWrite (LEDyellow, LOW);
digitalWrite (Buzzer, LOW);
}
if((distance > 200) && (distance < 400));
{
digitalWrite (LEDred, HIGH); //red
digitalWrite (LEDblue, LOW); //blue
digitalWrite (LEDyellow, LOW); //yellow
digitalWrite (Buzzer, LOW); //Buzzer
delay(1000);
}
if((distance > 50) && (distance < 200));
{
digitalWrite (LEDred, HIGH); //red
digitalWrite (LEDblue, HIGH); //blue
digitalWrite (LEDyellow, LOW); //yellow
digitalWrite (Buzzer, LOW); //Buzzer
delay(1000);
}
if((distance > 0) && (distance < 50));
{
digitalWrite (LEDred, HIGH); //red
digitalWrite (LEDblue, HIGH); //blue
digitalWrite (LEDyellow, HIGH); //yellow
digitalWrite (Buzzer, HIGH); //Buzzer
delay(1000);
}
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
Serial.println(" cm ");
delay(100);
}
And also an image of how the circuit looks if it helps, since maybe I connected something wrong there.
