Hi all,
First of all, sorry for my english.
I’ve been working with Arduino for a year more or less. Now I’ve started with servos because I’m making a new proyect. My problem is my servo goes crazy, even with the most simple example.
My program is very simple, it moves the servo to the right and when it reaches 180 degrees, it turns to the left, with 10 degrees every step every second. I put the code at the bottom.
Well, when the program run for a while, the servo stops and it restart the running with a jump or maybe it stops forever and I have to reboot the Arduino. Because of these, I’ve put a counter that counts how many times the loop was called. My results, when the servo stopped, the loop’s times reduce (120000/second → OK, 20000/second → bad). I’ve tried with Servo library but I get the same results.
Thank you in advance. Any answer will be wellcome.
int angle;
int widthPulse;
int maxPulse;
int minPulse;
int rTime;
int increment;
unsigned long lastPulse;
unsigned long lastChange;
unsigned long nTimes;int angle2widthPulse(int angle){
return map(angle, 0, 180, 700, 2200);
}void setup(){
Serial.begin(9600);
nTimes = 0;
increment = 10;
angle = 91;
widthPulse = angle2widthPulse(angle);
maxPulse = 2200;
minPulse = 700;
rTime = 18;
pinMode(2,OUTPUT);
lastPulse = millis();
lastChange = millis();
}void loop(){
nTimes++;
if(millis() - lastPulse >= rTime){
digitalWrite(2, HIGH);
delayMicroseconds(widthPulse);
digitalWrite(2, LOW);
lastPulse = millis();
}
if(millis() - lastChange >= 1000){
angle = angle + increment;
if(angle > 180){
increment = -10;
angle = 170;
}else if(angle < 0){
increment = 10;
angle = 10;
}
widthPulse = angle2widthPulse(angle);
lastChange = millis();
Serial.println(nTimes/1000, DEC);
nTimes = 0;
}
}