Hello, so I'm making this project, a ultrasonic sensor that tracks the distance of the area nearby, and it's standing on top of a servo(1) which should always be rotating and when a object is closer than 20 cm, it turns on another servo(2), which makes an object fall(this servo just has to turn one time, amd then it can do whatever it wants :P). It's kind of an alarm. But I'm having problems with coding and I don't know if I'm doing things right with connecting servos and sensors to Arduino, so here's a scheme of the build and the code below, you're free to help me figuring the problem out, and btw, the problem is that none of the servos move or rotate, but the ultrasonic sensor calculates the distance, and even though an object is closer that 20 cm , it still doesn't turn on the servo(2).
Here's the code:
#define ECHOPIN 7
#define TRIGPIN 8
#include <Servo.h>
float distance;
Servo servo;
int pos = 0; //
void setup()
{
Serial.begin(9600);
servo1.attach(9);
servo2.attach(3);
pinMode(7, OUTPUT);
pinMode(8, INPUT);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
void Print (int R , int T)
{
Serial.print(R); Serial.print(", ");
Serial.print(T); Serial.println(".");
delay(100);
}
float Distance () {
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
float distance = pulseIn(ECHOPIN, HIGH);
distance = distance / 58;
return (distance);
}
void loop()
{
servo1.write(45);
servo1.attach(9);
delay(400);
for (pos = 45; pos <= 45; pos += 1)
{
servo1.write(pos);
Print(Distance() , pos);
delay(10);
for (pos = 45; pos >= 45; pos -= 1)
servo1.write(pos); Print(Distance() , pos);
delay(10);
}
if (distance < 20)
{
servo2.attach(3);
servo2.write(45);
delay(400);
for (pos = 45; pos <= 45; pos += 45)
{
servo2.write(pos);
Print(Distance() , pos);
delay(10);
for (pos = 45; pos >= 45; pos -= 45)
servo2.write(pos);
Print(Distance() , pos);
delay(10);
}
}
else
{
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
Here's a picture of my project!
Please help!!!