0
votes

I've been working on a project where I need to control servo motors based on data saved on an SD card. So far it is going well, however I'm having issues with controlling the timing and speed of the servo motors movements. I'll explain what I'm trying to accomplish and some example code.

I'm using an Arduino Mega with an SD module attached to it. On the SD card I have four different .txt files. Each file contains 30 integer values, each line contains a single integer and is terminated with a (,). This is merely test data so I can sweep through a range of angles to check I'm reading and converting the values just fine. But when I try to slow down the servos using timers, delays etc. it speeds through the code as if they were there. In my case the code looks like this:

string dataRead ="";                  // String object to read bytes from
unsigned long int motorTime = 250;    // Refresh time of the motor (250 ms)      
unsigned long int lastMotor = (long) micros();
while (entry.available()) {           // While there are bytes in the file to be read
   dataRead = entry.readStringUntil(',');
   while((long) micros() - lastMotor <= (motorTime * 1000));    // Do nothing until refresh time has elapsed

   myServo.write(dataRead.toInt());
   lastMotor = (long) micros();
}

The data is read fine and the motor moves according to the data, however the timing code just appears to be negated for some reason. I suspect it is because all sorts of hardware features are being enabled and disabled underneath all the layers of abstraction in the Arduino IDE and the delay is being negated for some reason.

Has anyone had experience of this? Any tips for driving a servo at a set speed? My alternative solution is to load the data into an array; but I don't want to run the risk of burning through all of the RAM and cause other problems.

Thanks in advance!

1

1 Answers

0
votes

I fixed it in the end. I disabled interrupts for when I was reading the data and that messed with the timer functions such as micros() and millis(); they rely on interrupts to keep track of the elapsed time. It probably makes more sense to detach the interrupt service routines rather than disabling them by default.