Hello guys first of all i want to say that i'm new to the arduino world i've start learning arduino programming a month ago and today i've built my first project if a HC-SR04 mounted on a servo and if an object get cloder to the sensor the LED's turn on one by one so i've wired everything and i wrote the code
and when i tried to run it the servo start turning but all the LED's stays off sometime they turn all on and stay like that . i've removed the serovo and i tested only the LED's and the sensor and it works but when i add the servo it dosen"t i hope you guys can help me solve this problem thanks
#include <Servo.h>;
Servo myservo;
int servopin = 9;
int x = 10;
int distance;
long duration;
int trig;
int echo;
int distance1;
int distance2;
int distance3;
int distance4;
int LED1 = 3;
int LED2 = 5;
int LED3 = 6;
int LED4 = 11;
void setup() {
myservo.attach(servopin);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop() {
distance1 = realdistance(x += 15);
distance2 = realdistance(x += 15);
distance3 = realdistance(x += 15);
distance4 = realdistance(x += 15);
if (x > 179) {
x = 0;
}
analogWrite(LED1, distance1);
delay(300);
analogWrite(LED2, distance2);
delay(300);
analogWrite(LED3, distance3);
delay(300);
analogWrite(LED4, distance4);
delay(300);
}
int realdistance(int pos) {
myservo.write(pos);
delay(600);
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = duration * 0.034 / 2;
if (distance <= 80) {
distance1 = map(distance, 80, 60, 0, 255);
distance1 = constrain(distance1, 0, 255);
}
else if (distance <= 60 ) {
distance2 = map(distance, 60, 40, 0, 255);
distance2 = constrain(distance2, 0, 255);
}
else if (distance <= 40) {
distance3 = map(distance, 40, 20, 0, 255);
distance3 = constrain(distance3, 0, 255);
}
else if (distance <= 20) {
distance4 = map(distance, 20, 0, 0, 255);
distance4 = constrain(distance4, 0, 255);
}
return distance1;
return distance2;
return distance3;
return distance4;
}
