I am trying to control a 9g servo in a project that i am still working on, but whenever I run the code the servo just flicks in between what i assume the 2 positions are or it moves a bit then freezes. I know that it freezes in this certain part of the code because i have leds that will turn off when it runs through the servos.
anyways here is the part of the code where it freezes...
servo.write(90);
delay(5000);
servo.write(180);
delay(5000);
this is the full code...
#include <Servo.h>
Servo servo;
//rgb leds r in d7 d11 and d12
int redPin= 5;
int greenPin =11;
int bluePin =3;
int pos = 0; // variable to store the servo position
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 3;//needs PWM pins
long duration;//the time diffrence in bettween the trigger and echo
int distance;//the distance of the object
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT);//letting the pin know it will be used to send signals
pinMode(echoPin, INPUT);//letting it know it will be used to receive signals
Serial.begin(9600);//lets the serial monitior know that we r watching
pinMode(buzzer, OUTPUT);
servo.attach(8);
servo.write(180);
delay(1000);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigPin,LOW);//turns off trig pin
delayMicroseconds(2);//short delay
digitalWrite(trigPin,HIGH);//turns on trig pin
delayMicroseconds(10);
digitalWrite(trigPin,LOW);//turns off trig pin
//sends the package of signal for a short time
duration = pulseIn(echoPin,HIGH);//read the echo pin and return the sound wave travel time in microsecond
distance = duration* 0.034/2;//converts the duration into the distance to the object
Serial.print("distance: "); Serial.println(distance);//printing the value of the distance from the sensor to the object
if (distance <20)
{
setColor(0,100,0);
delay(3000);
setColor(100,100,0);
delay(1000);
setColor(100,0,0);
delay(1000);
servo.write(90);
delay(5000);
servo.write(180);
delay(5000);
setColor(0,0,0);
delay(10);
}
}
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}