Wheel Encoders
Wheels Encoders Code
#define rightMotorFor 5
#define rightMotorRev 4
#define leftMotorFor 6
#define leftMotorRev 7
#define encoderPin 2
volatile long encoderValue = 0;
void setup()
{
Serial.begin(9600);
pinMode (rightMotorFor, OUTPUT);
pinMode (rightMotorRev, OUTPUT);
pinMode (leftMotorFor, OUTPUT);
pinMode (leftMotorRev, OUTPUT);
pinMode (encoderPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderPin), AdvanceEncoderValue, RISING);
}
void loop()
{
//make sure car is pointing forward
//right hand side of figure 8
for(int i =0; i< 4; i++){
rightTurn();
goForward();
}
//left hand side of the figure 8
for(int i =0; i< 4; i++){
leftTurn();
goForward();
}
//all done with the code
allStop();
}
void goForward()
{
encoderValue = 0;
digitalWrite(rightMotorRev, LOW);
digitalWrite(leftMotorRev, LOW);
digitalWrite(rightMotorFor, HIGH);
digitalWrite(leftMotorFor, HIGH);
Serial.println("starting forward");
while(encoderValue<8560){
}
Serial.println(encoderValue);
Serial.println("Finished 30.48 cm");
}
void rightTurn(){
encoderValue = 0;
digitalWrite(rightMotorFor, LOW);
digitalWrite(leftMotorRev, LOW);
digitalWrite(leftMotorFor, HIGH);
digitalWrite(rightMotorRev, HIGH);
Serial.println("starting rightTurn");
while(encoderValue<3310){
}
Serial.println(encoderValue);
Serial.println("Finished righTurn");
}
void leftTurn(){
encoderValue = 0;
digitalWrite(leftMotorFor, LOW);
digitalWrite(rightMotorRev, LOW);
digitalWrite(leftMotorRev, HIGH);
digitalWrite(rightMotorFor, HIGH);
Serial.println("starting lefTurn");
while(encoderValue<3310){
}
Serial.println(encoderValue);
Serial.println("Finished leftTurn");
}
void allStop(){
encoderValue = 10;
digitalWrite(leftMotorFor, LOW);
digitalWrite(rightMotorRev, LOW);
digitalWrite(leftMotorRev, LOW);
digitalWrite(rightMotorFor, LOW);
Serial.println("all stop");
while(encoderValue>1){
}
}
void AdvanceEncoderValue(){
encoderValue++;
}
Comments
Post a Comment