700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 增量编码器与Arduino连接(读取编码器脉冲数)

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

时间:2019-01-11 11:09:40

相关推荐

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

https://mp./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 encoderint encoderPinA = 2; //interrupt pin 2 int encoderPinB = 3; //interrrupt pin 3void 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 counterif ( encoderCounter!= temp){Serial.println (encoderCounter);temp = encoderCounter;}}void doEncoderA(){// look for a low-to-high on channel Aif (digitalRead(encoderPinA) == HIGH) {// check channel B to see which way encoder is turningif (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 Bif (digitalRead(encoderPinB) == HIGH) {// check channel A to see which way encoder is turningif (digitalRead(encoderPinA) == HIGH) {encoderCounter = encoderCounter + 1; // CW} else {encoderCounter = encoderCounter - 1; // CCW}}// Look for a high-to-low on channel Belse {// 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

可以获取电机转动角度

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。