I have several Arduino-branded Uno R3 and I'm having a weird, intermittent problem where they sometimes completely lock up while stepping a stepper. While debugging, I noticed that I sometimes get this problem even when I've disconnected all the hardware from the Arduino, including the stepper, so I'm almost certain it's not a power problem or anything like that.
The weird thing is that the problem is intermittent, and uploading the same exact sketch will sometimes lead to a freeze, and then the next day it won't even though nothing else has changed.
Here's my example sketch. You can see I use dynamic memory allocation for the stepper object. That's because this is a stripped-down version of my real sketch (which is really big and complicated), and in the real sketch I'd prefer to use dynamic memory allocation for reasons I can get into if necessary. I've also had basically the same problem when I don't use dynamic memory allocation anyway.
/* Very simple protocol to test freezing problem.
Just creates a stepper object. Often freezes when trying to step it.
*/
#include "Stepper.h"
// hardware constants
#define ENABLE_STEPPER 12
#define PIN_STEPPER1 8
#define PIN_STEPPER2 9
#define PIN_STEPPER3 10
#define PIN_STEPPER4 11
#define __HWCONSTANTS_H_NUMSTEPS 200
#define __HWCONSTANTS_H_STP_POST_ENABLE_DELAY 100
Stepper *stimStepper = 0;
void setup() {
Serial.begin(115200);
stimStepper = new Stepper(__HWCONSTANTS_H_NUMSTEPS,
PIN_STEPPER1, PIN_STEPPER2, PIN_STEPPER3, PIN_STEPPER4);
}
void loop() {
Serial.println("DBG stepping");
delay(500);
rotate(1);
}
int rotate(long n_steps)
{
digitalWrite(ENABLE_STEPPER, HIGH);
Serial.println("DBG stepping0");
delay(__HWCONSTANTS_H_STP_POST_ENABLE_DELAY);
Serial.println("DBG stepping1");
// This is where the freeze usually happens
stimStepper->step(n_steps);
// never get here
Serial.println("DBG stepping2");
Serial.println("DBG stepping3");
digitalWrite(ENABLE_STEPPER, LOW);
return 0;
}
As I said, the weird thing is that the problem doesn't occur reliably. But occasionally, when I upload this sketch and open the Serial Monitor from within the Arduino IDE, it does this:
DBG stepping
DBG stepping0
DBG stepping1
and then freezes forever. On other occasions, it does what it's supposed to: loops forever, printing all debug statements every time. I get the same result on several different Unos so I don't think it's a problem with the board.
Any ideas?? I am having trouble tracking this intermittent problem down! Are there tools that can check for memory leaks?