And an Arduino Mega 2560 / ADAFruit motor shield, and I've been having a problem.
If I try to run the motors, they run fine. As soon as you introduce a delay however, they start to twitch and not move at all (while connected to 5AA batt pack), if I switch over to arduino power from USB, they work (but very weakly due to low current).
To get around this I made a function with a for loop to act instead of a delay. What now happens is that it will run the function perfectly - the FIRST time. After that it won't even budge until arduino is reset.
Here is my code:
#include <AFMotor.h>
AF_DCMotor motorBL(1, MOTOR12_64KHZ);
AF_DCMotor motorBR(2, MOTOR12_64KHZ);
AF_DCMotor motorFR(3, MOTOR12_64KHZ);
AF_DCMotor motorFL(4, MOTOR12_64KHZ);
void setup()
{
motorBL.setSpeed(255);
motorBR.setSpeed(255);
motorFR.setSpeed(255);
motorFL.setSpeed(255);
}
void loop()
{
turnLeft(500,255);
delay(500);
turnRight(500,255);
delay(500);
}
void turnLeft(unsigned long time, int motorSpeed)
{
motorBL.setSpeed(motorSpeed);
motorBR.setSpeed(motorSpeed);
motorFR.setSpeed(motorSpeed);
motorFL.setSpeed(motorSpeed);
unsigned long stTime = millis();
unsigned long endTime;
for(unsigned long timeElapsed; timeElapsed < time; timeElapsed = (endTime - stTime))
{
motorBL.run(BACKWARD);
motorBR.run(FORWARD);
motorFR.run(FORWARD);
motorFL.run(BACKWARD);
endTime = millis();
}
motorBL.run(RELEASE);
motorBR.run(RELEASE);
motorFR.run(RELEASE);
motorFL.run(RELEASE);
}
void turnRight(unsigned long time, int motorSpeed)
{
motorBL.setSpeed(motorSpeed);
motorBR.setSpeed(motorSpeed);
motorFR.setSpeed(motorSpeed);
motorFL.setSpeed(motorSpeed);
unsigned long stTime = millis();
unsigned long endTime;
for(unsigned long timeElapsed; timeElapsed < time; timeElapsed = (endTime - stTime))
{
motorBL.run(FORWARD);
motorBR.run(BACKWARD);
motorFR.run(BACKWARD);
motorFL.run(FORWARD);
endTime = millis();
}
motorBL.run(RELEASE);
motorBR.run(RELEASE);
motorFR.run(RELEASE);
motorFL.run(RELEASE);
}
I would initialize both, even as global. (add: If you use the variables as global) insure you remove the declarations of those variables in the functions. Local variables have precedence over global.