Now I have a simple chassis with two wheels which are powered by encoder motors. I connected Arduino Uno with the chassis and made a simple program to just count the numbers of signals (in simple terms) from each of the encoder motors.
Now theoretically when the chassis moves straight both readings should be exactly the same (I've checked - They are!). And when one motor is faster that certain reading should be more.
So I made a simple program that keeps a check on these encoder readings and when the difference exceeds a certain value it shuts off one motor until the values don't become equal and then turn on that motor.
Now theoretically the chassis should go in a straight line but it doesn't and performs weird stuff. (Code is attached below).
Now sometimes the code gets stuck in one of the while loops. I've also tinkered with my code a lot. For example instead of while(left_counter != right_counter)
I've even done while ((left_counter - right_counter) > Certain_Range
The only problem I can think of is that it takes time for the motors to turn off and in that time the interrupts are wreaking havoc. (I'm new to micro controller programming and stuff although I have quite a lot of experience in C++ etc.)
Please can any one explain why isn't this approach working in keeping the motor straight?
Code (Arduino UNO):
int motor_vcc_left = 12; //LEFT TIRE - BLUE
int pull_up_left = 3; //LEFT TIRE - GREEN
int motor_vcc_right = 11; //RIGHT TIRE - ORANGE
int pull_up_right = 2; //RIGHT TIRE - BLUE
int encoder_vcc_pin = 7;
volatile int left_counter = 0;
volatile int right_counter = 0;
void setup() {
pinMode(motor_vcc_left, OUTPUT);
pinMode(motor_vcc_right, OUTPUT);
pinMode(encoder_vcc_pin, OUTPUT);
digitalWrite(encoder_vcc_pin, HIGH);
pinMode(3, INPUT_PULLUP); //LEFT TIRE
attachInterrupt(1, blinkleft, CHANGE); //LEFT TIRE
pinMode(2, INPUT_PULLUP); //RIGHT TIRE
attachInterrupt(0, blinkright, CHANGE); //RIGHT TIRE
digitalWrite(motor_vcc_left, HIGH);
digitalWrite(motor_vcc_right, HIGH);
}
void loop() {
if ((left_counter - right_counter) > 10) {
while (left_counter != right_counter) {
digitalWrite(motor_vcc_left, LOW);
}
digitalWrite(motor_vcc_left, HIGH);
} else if ((right_counter - left_counter) > 10) {
while (right_counter != left_counter) {
digitalWrite(motor_vcc_right, LOW);
}
digitalWrite(motor_vcc_right, HIGH);
}
}
void blinkleft() {
left_counter++;
}
void blinkright() {
right_counter++;
}