Control DC MOTOR + Encoder with DC Motor Shield for Arduino





Arduino Sketch



//Arduino PWM Speed Control:

int E1 = 5;  // MOTOR_1

int M1 = 4;  // MOTOR_1

int E2 = 6;  // MOTOR_2                   

int M2 = 7;  // MOTOR_2     



//The sample code for driving one way motor encoder

const byte encoder0pinA = 2;//A pin -> the interrupt pin 0

const byte encoder0pinB = 4;//B pin -> the digital pin 4

byte encoder0PinALast;

int duration;//the number of the pulses

boolean Direction;//the rotation direction



void setup() {

 

  Serial.begin(57600);//Initialize the serial port

  EncoderInit();//Initialize the module



  pinMode(M1, OUTPUT); 

  pinMode(M2, OUTPUT);



  digitalWrite(M1,LOW); 

  analogWrite(E1, 100);



  digitalWrite(M2,HIGH);

  analogWrite(E2,250);

}



void loop()

{

  Serial.print("Pulse:");

  Serial.println(duration);

  duration = 0;

  delay(100);

}



void EncoderInit()

{

  Direction = true;//default -> Forward 

  pinMode(encoder0pinB,INPUT); 

  attachInterrupt(0, wheelSpeed, CHANGE);

}



void wheelSpeed()

{

  int Lstate = digitalRead(encoder0pinA);

  if((encoder0PinALast == LOW) && Lstate==HIGH)

  {

    int val = digitalRead(encoder0pinB);

    if(val == LOW && Direction)

    {

      Direction = false; //Reverse

    }

    else if(val == HIGH && !Direction)

    {

      Direction = true;  //Forward

    }

  }

  encoder0PinALast = Lstate;



  if(!Direction)  duration++;

  else  duration--;

}

ความคิดเห็น