General

path remembering car

userHead Account cancelled 2012-11-01 10:07:06 4590 Views0 Replies
I am trying to build a robot that remembers the path that it just passed, to do that I am using two wheel encoders. I bought the wheel encoders form DFrobots and used the sample code they have to test the encoders here is the code:
Code: Select all
#include <AFMotor.h> 
AF_DCMotor motor1(1, MOTOR12_64KHZ); 
AF_DCMotor motor2(2, MOTOR12_64KHZ); 
AF_DCMotor motor3(3, MOTOR12_1KHZ); 
AF_DCMotor motor4(4, MOTOR12_1KHZ); 
const int pingPin = 19; 
#define LEFT 0
#define RIGHT 1

long coder[2] = {
  0,0};
int lastSpeed[2] = {
  0,0}; 
void setup() { 
  Serial.begin(9600);           // set up Serial library at 9600 bps 
  motor1.setSpeed(200);         // Set the speed for the motors (255 is the maximum)  
  motor2.setSpeed(200); 
  motor3.setSpeed(200); 
  motor4.setSpeed(200); 
  attachInterrupt(LEFT, LwheelSpeed, CHANGE);    //init the interrupt mode for the digital pin 2
  attachInterrupt(RIGHT, RwheelSpeed, CHANGE);   //init the interrupt mode for the digital pin 3
} 
void forward(){      // This function moves the wheels forward 
    motor1.run(FORWARD); 
  motor2.run(FORWARD); 
  motor3.run(FORWARD); 
  motor4.run(FORWARD); 
} 
void backward() {      // This function moves the wheels backward 
    motor1.run(BACKWARD); 
  motor2.run(BACKWARD); 
  motor3.run(BACKWARD); 
  motor4.run(BACKWARD); 
} 
void haltMotors()   // This function stops each motor (It is better to stop the motors before changing direction.) 
{ 
  motor1.run(RELEASE); 
  motor2.run(RELEASE); 
  motor3.run(RELEASE); 
  motor4.run(RELEASE); 
} 
void turnRight(){    // This function turns the robot right.   
  motor1.run(FORWARD); 
  motor2.run(BACKWARD); 
  motor3.run(BACKWARD); 
  motor4.run(FORWARD); 
} 
void turnLeft(){
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(BACKWARD);
}
void loop() { 
  forward();
  delay(500);
  haltMotors();
  delay (1000);
  
 static unsigned long timer = 0;                //print manager timer
   
  if(millis() - timer > 100){                   
    Serial.print("Coder value: ");
    Serial.print(coder[LEFT]);
    Serial.print("[Left Wheel] ");
    Serial.print(coder[RIGHT]);
    Serial.println("[Right Wheel]");
     
    lastSpeed[LEFT] =  coder[LEFT];   //record the latest speed value
    lastSpeed[RIGHT] = coder[RIGHT];
    coder[LEFT] = 0;                 //clear the data buffer
    coder[RIGHT] = 0;
    timer = millis();
  }
}
void LwheelSpeed()
{
  coder[LEFT] ++;  //count the left wheel encoder interrupts
}
 
 
void RwheelSpeed()
{
  coder[RIGHT] ++; //count the right wheel encoder interrupts
}
(this is just a test it is not the code for the entire project.)
But the sensors are giving me wrong readings, even when I disconnect the pins it still give me weird readings. Does that mean that is something is wrong with the code or are the encoders bad?