Hi all,
I've been working on a small car for a project. I'm trying to make the car go a certain distance and stop when it has reached that, and have used the PID library to accomplish this. As part of the tuning process, I printed out the current PWM value (declared as variable power) and the current number of encoder Ticks. However, at random points, the Serial monitor stops printing and the Arduino Uno stops processing. There is still power though; for example, if the motors were currently at power of 255, they stay there even after the monitor freezes.
#include <PID_v1.h>
#include <RedBot.h>
#include <Adafruit_MotorShield.h>
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *rightWheel = AFMS.getMotor(4);
Adafruit_DCMotor *leftWheel = AFMS.getMotor(3);
RedBotEncoder encoder = RedBotEncoder(A4, 10);
double numCounts = 0;
double goal = 6.5*PI;//goal distance in cm
double goalRevs = 5;
double goalCounts = goalRevs*192;
double power = 100;
boolean go = false;
int buttonPin = 9;//replace w/actual button pin
PID encoderPID = PID(&numCounts, &power, &goalCounts, 0.6, 0.9, 0.9, DIRECT);
void setup() {
Serial.begin(9600);
AFMS.begin();
rightWheel->run(FORWARD);
leftWheel->run(FORWARD);
encoderPID.SetMode(AUTOMATIC);
// encoderPID.SetOutputLimits(0, 255);
//encoderPID.SetSampleTime(300);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
encoder.clearEnc(BOTH);
/*Serial.println(F("???"));
Serial.println(F("???"));
Serial.println(F("???"));
//pinMode(A2, INPUT);
Serial.println("Finished setup");*/
}
void loop() {
//Serial.println(encoder.getTicks(LEFT));
// Serial.println(digitalRead(buttonPin));
if (digitalRead(buttonPin) == LOW)
go = true;
if (!go){
//Serial.println(F("Waiting for Button"));
//Serial.println(encoder.getTicks(LEFT));
return;
}
else
{
driveDistance(goalCounts);
}
//numCounts = 0;
}
void driveDistance(double goalCounts)
{
//encoder.clearEnc(BOTH);
if(numCounts<goalCounts)
{
encoderPID.Compute();
//Serial.print(F("Traveling at: "));
Serial.println(power);
rightWheel->setSpeed(power);
leftWheel->setSpeed(power);
numCounts = (double) encoder.getTicks(LEFT);
delay(210);
Serial.println(numCounts);
delay(210);
}
else{
rightWheel->setSpeed(0);
leftWheel->setSpeed(0);
//Serial.println(F("Finished"));
exit(1);
}
}
I researched this problem online, but didn't find a solution.
Here is what I tried:
- wrapping my Serial.println literal string in F()
- changing the baud rate
- checking the free memory available using the MemoryFree Library (I deleted this from my code); it was always 13529 (I think)
- removing all of the Serial prints
- running on battery power
- adding in delays
I think there could be a problem with the board. I'm using the Adafruit Motorshield V2.
I also attached a picture of the serial monitor frozen.
Please lmk what you think the problem is and how I could solve it.
Thanks!