I am a rookie and i dont have much experience on arduino. please help me. I intend to build a robot that will drive on a straight path even on nonuniform surfaces like the ones we see in agricultural fields(It is just a prototype, so i want to run it on normal offroad surfaces).The robot has 4 motors, one for each wheel. I plan to use encoder feedback method to drive straight. Right now, I have coupled a slotted disc to the shaft of a dc motor and i am trying to get the counts from the encoder and display the count after a certain interval(5 seconds) on serial monitor. The count that i get is way off the mark. The disc is having 30 slots. With just 2 to 3 rotations I am getting a count of around 180.
I am using arduino R3. Encoder output:- Pin2 (external interrupt) motor Pins :- 8,9 I am attaching the code below.
const int motorPin1 = 8; // Pin 14 of L293
const int motorPin2 = 9; // Pin 10 of L293
const int encoder_pin = 2;
volatile unsigned int count = 0;
int time1 = 0;
int time2 = 0;
void setup() {
// put your setup code here, to run once:
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(encoder_pin,INPUT);
digitalWrite(encoder_pin,HIGH);
attachInterrupt(0,encoder,RISING);
Serial.begin(9600);
digitalWrite(motorPin1,HIGH);
digitalWrite(motorPin2,LOW);
time1 = millis();
}
void loop() {
// put your main code here, to run repeatedly:
time2 = millis();
if(abs((time2 - time1) > 5000))
{
digitalWrite(motorPin1,LOW);
digitalWrite(motorPin2,LOW);
Serial.println(count);
}
}
void encoder()
{
count++;
}
the end of code
The disc that i have mounted on the shaft doesn't rotate in vertical plane exactly. But i do get the blinks on the encoder when i rotate the shaft with my hand.Can that misalignment be the reason.