增量编码器与Arduino连接(读取编码器脉冲数)

https://mp.weixin.qq.com/s/e_25NUo5C_IhVck6dl3Tfg

如下将编码器与Arduino连接:
A相:PIN 2( arduino的中断器引脚)
B相:PIN 4( arduino的中断器引脚)
电源:5V
地:GND
在这里,我们必须注意,编码器的A、B相输出必须仅连接到Aorduino的中断引脚。否则,arduino无法记录来自编码器的每个脉冲。
在这里插入图片描述

volatile long temp, encoderCounter =0; //This variable will increase or decreas depending on the rotation of encoder
int encoderPinA = 2; //interrupt pin 2 
int encoderPinB = 3; //interrrupt pin 3

void setup() {
Serial.begin (115200);
pinMode (encoderPinA, INPUT); 
pinMode (encoderPinB, INPUT); 

//Setting up interrupt
//attach an interrupt to pin encoderPinA & encoderPinA of the Arduino, and when the pulse is in the CHANGE edge called the function doEncoderA()/doEncoderB()
attachInterrupt (digitalPinToInterrupt(encoderPinA), doEncoderA, CHANGE);//B rising pulse from encodenren activated ai1(). AttachInterrupt 1 isDigitalPin nr 3 on moust Arduino.
attachInterrupt (digitalPinToInterrupt(encoderPinB), doEncoderB, CHANGE);
}

void loop() {
  // Send the value of counter
if ( encoderCounter!= temp){
  Serial.println (encoderCounter);
  temp = encoderCounter;
}
}

void doEncoderA(){

  // look for a low-to-high on channel A
  if (digitalRead(encoderPinA) == HIGH) { 
    // check channel B to see which way encoder is turning
    if (digitalRead(encoderPinB) == LOW) {  
      encoderCounter = encoderCounter + 1;         // CW
    } 
    else {
      encoderCounter = encoderCounter - 1;         // CCW
    }
  }
  else   // must be a high-to-low edge on channel A                                       
  { 
    // check channel B to see which way encoder is turning  
    if (digitalRead(encoderPinB) == HIGH) {   
      encoderCounter = encoderCounter + 1;          // CW
    } 
    else {
      encoderCounter = encoderCounter - 1;          // CCW
    }
  }
  //Serial.println (encoder0Pos, DEC);          
  // use for debugging - remember to comment out
}

void doEncoderB(){

  // look for a low-to-high on channel B
  if (digitalRead(encoderPinB) == HIGH) {   
   // check channel A to see which way encoder is turning
    if (digitalRead(encoderPinA) == HIGH) {  
      encoderCounter = encoderCounter + 1;         // CW
    } 
    else {
      encoderCounter = encoderCounter - 1;         // CCW
    }
  }
  // Look for a high-to-low on channel B
  else { 
    // check channel B to see which way encoder is turning  
    if (digitalRead(encoderPinA) == LOW) {   
      encoderCounter = encoderCounter + 1;          // CW
    } 
    else {
      encoderCounter = encoderCounter - 1;          // CCW
    }
  }
}

将代码上传到arduino后,打开串行监视器

并旋转编码器轴,如果沿顺时针方向旋转编码器,则值会增加;如果沿逆时针方向旋转,则值会减小。

进一步通过:

double angle = encoderCounter*360/172032.0;//ppr=172032

可以获取电机转动角度


版权声明:本文为lihe4151021原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。