Newbie here. When I plug the USB into my Arduino to power the project, my servo wants to move around right away. Sometimes it goes to 90 degrees and stops until it is triggered by the ultrasonic sensor. In this case, it starts at 90, goes back to 0, to 180 back to 0...
The other case is that upon powering it up, sometimes the servo goes to 180 and then back to 0. Neither of these options are good because I am making a lock on a box and I can't have it unlock as soon as I power up the Arduino. I need the servo to remain at 0 until I trigger the sensor.
(More mods have to be made to the code so that the lock will remain open until I trigger it again but that is another discussion).
Your help is much appreciated!
#include<Servo.h>
int trig=8;
int echo=9;
int dt=10;
Servo servo;
//int distance,duration;
void setup() {
// put your setup code here, to run once:
pinMode(trig,OUTPUT);
pinMode(echo,INPUT);
Serial.begin(9600);
servo.attach(11);
}
void loop() {
// put your main code here, to run repeatedly:
if (calc_dis()<5)
{
for (int i=0;i<=540;i++)
{
servo.write(i);
delay(1);
}
delay(100);
for (int i=540;i>=0;i--)
{
servo.write(i);
delay(1);
}
delay(100);
}
}
//This code is written to calculate the DISTANCE using ULTRASONIC SENSOR
int calc_dis()
{
int duration,distance;
digitalWrite(trig,HIGH);
delay(dt);
digitalWrite(trig,LOW);
duration=pulseIn(echo,HIGH);
distance = (duration/2) / 29.1;
return distance;
}