I am running a simple servo program that swings the servo back and forth, it is essentially pressing a button continuously. However, after some time the servo stops moving and it seems like the code stops. I have no code in the program to tell it to stop and I am uploading from a sketch. Can anyone tell me why the servo will stop after some amount of time? is this some kind of safety or programmatic end that is used when you use the sketch compiler to run code?
Here is my code:
#include <Servo.h>
int servoPin = 9;
Servo servo;
int servoAngle = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
servo.attach(servoPin);
}
void loop() {
// put your main code here, to run repeatedly:
int randnum = rand()%(40000-1000 + 1) + 1000;
int randnumreturn = rand()%(600-350 + 1) + 350;
servo.write(45);
delay(randnum);
servo.write(22);
delay(randnumreturn);
}
-
What is your power source?Majenko– Majenko2016年08月06日 14:58:38 +00:00Commented Aug 6, 2016 at 14:58
-
my laptop, i have the board plugged in through the usb cable used to download code onto the boardryan– ryan2016年08月06日 14:59:49 +00:00Commented Aug 6, 2016 at 14:59
-
1How long do you normally have to wait for it to stop? Is your laptop going to sleep?Majenko– Majenko2016年08月06日 15:14:07 +00:00Commented Aug 6, 2016 at 15:14
1 Answer 1
int
in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is > 32767
, you would get a minus value, which may cause delay not to work properly.
In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.
Edit: I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.
-
Actually,
40000
is along int
literal, and the whole expression at the right of=
is computed as along int
. The overflow happens when that expression is assigned toint randnum
.Edgar Bonet– Edgar Bonet2016年08月07日 07:44:12 +00:00Commented Aug 7, 2016 at 7:44 -
I'd suggest you complete your answer by mentioning what to do to solve the problem rather than just explaining it. Here, this is a matter of changing declarations of
random
andrandumreturn
tounsigned int
.jfpoilpret– jfpoilpret2016年08月07日 08:29:20 +00:00Commented Aug 7, 2016 at 8:29 -
1@EdgarBonet I am clarifying so that it would be understood better.Cem Kalyoncu– Cem Kalyoncu2016年08月07日 09:04:25 +00:00Commented Aug 7, 2016 at 9:04
-
@jfpoilpret Or using a value less than 32767. I am updating for possible solutions.Cem Kalyoncu– Cem Kalyoncu2016年08月07日 09:04:28 +00:00Commented Aug 7, 2016 at 9:04