Hello, I am a beginner to C++ and I have only done a few projects. Currently, I am trying to make a distance measurer with an ultrasonic sensor (Data sheet). What I want it to do is, when there is something close to the sensor the LED will turn on, however, the LED is always on and there is no error message.
here is the code
const int trigPin = 13;
const int echoPin = 12;
long duration;
int distance;
int led6 = 6;
int led5 = 5;
int led4 = 4;
int led3 = 3;
int led2 = 2;
int led1 = 1;
void setup() {
pinMode(led6,OUTPUT);
pinMode(led5,OUTPUT);
pinMode(led4,OUTPUT);
pinMode(led3,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led1,OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delay(500);
digitalWrite(trigPin, HIGH);
delay(500);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;
Serial.print("DISTANCE: ");
Serial.println(distance);
if (distance < 10){
digitalWrite(led6,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led1,HIGH);
}
else( digitalWrite(led1, LOW));
}
If anyone is able to help it would be greatly appreciated.