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:

void loop() {
    // put your main code here, to run repeatedly:

    int randnum = rand()%(40000-1000 + 1) + 1000;
    int randnumreturn = rand()%(600-350 + 1) + 350;
  • What is your power source?
    – Majenko
    Aug 6, 2016 at 14:58
  • my laptop, i have the board plugged in through the usb cable used to download code onto the board
    – ryan
    Aug 6, 2016 at 14:59
  • 1
    How long do you normally have to wait for it to stop? Is your laptop going to sleep?
    – Majenko
    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 a long int literal, and the whole expression at the right of = is computed as a long int. The overflow happens when that expression is assigned to int randnum. 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 and randumreturn to unsigned int.
    – jfpoilpret
    Aug 7, 2016 at 8:29
  • 1
    @EdgarBonet I am clarifying so that it would be understood better. Aug 7, 2016 at 9:04
  • @jfpoilpret Or using a value less than 32767. I am updating for possible solutions. Aug 7, 2016 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.