如何将光学旋转编码器与Arduino连接

什么是光学旋转编码器

光学旋转编码器是一种机械设备,在圆柱形外壳的内部有一个旋转轴,其结构与电机相同。

圆形平盘,上面有两组插槽。

光学传感器安装在此光盘的两侧,发送器设置在一侧,接收器设置在一侧。

因此,当开槽光盘在传感器之间旋转时,它会切断光学传感器,并在接收器末端生成信号。

接收器还与微控制器连接以处理生成的信号,

这样我们就可以知道旋转了多少轴。

我们还可以通过比较两个输出的信号极性来确定轴的旋转方向。因为两组插槽之间有一定的偏移

光学旋转编码器一般有两个输出“ A”和“ B”。

编码器类型

通常有两种编码器

增量编码器

绝对编码器

增量编码器

这种类型的编码器提供脉冲作为输出,可以将其视为增量信号。

因为它没有任何唯一位置的唯一值,这意味着当该编码器断电时,它失去了位置参考并从零开始。

绝对编码器

这种类型的编码器比增量编码器更为先进。

同时它们具有磁盘来代替插槽磁盘,因此它在每个位置都有独特的价值,因此即使在断电后也能记住它的药水。

在这篇文章中,我们将学习增量编码器。

带有Arduino的连接光学编码器

在这里,我使用的是https://www.pepperl-fuchs.com/china/zh/classid_197.htm?view=productdetails&prodid=76458,每转有1040个脉冲

在下面,您可以看到编码器的电线详细信息:

白色:输出–

绿色:输出–

黑色 – 黑色:GND

红色:+ 5V DC

屏蔽:GND

如下将光学旋转编码器与arduino连接

白色(OUT A):PIN 3( arduino的中断器引脚

绿色(OUT B):PIN 2( arduino的中断器引脚

红色:5V

黑色:GND

在这里,我们必须注意,来自编码器的绿色和白色的输出必须仅连接到orduino的中断引脚。

否则,arduino无法记录来自编码器的每个脉冲。


编码器ARDUINO接线

CODE

volatile long temp, counter = 0; //This variable will increase or decrease depending on the rotation of encoder


void setup() {

  Serial.begin (9600);

  pinMode(2, INPUT_PULLUP); // internal pullup input pin 2


  pinMode(3, INPUT_PULLUP); // internalเป็น pullup input pin 3

  //Setting up interrupt

  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.

  attachInterrupt(0, ai0, RISING);


  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.

  attachInterrupt(1, ai1, RISING);

  }


  void loop() {

  // Send the value of counter

  if( counter != temp ){

  Serial.println (counter);

  temp = counter;

  }

  }


  void ai0() {

  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH

  // Check pin 3 to determine the direction

  if(digitalRead(3)==LOW) {

  counter++;

  }else{

  counter--;

  }

  }


  void ai1() {

  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH

  // Check with pin 2 to determine the direction

  if(digitalRead(2)==LOW) {

  counter--;

  }else{

  counter++;

  }

  }

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

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

如果值显示反向,则表示顺时针运动为-ve值。

您可以颠倒“ GREEN”和“ WHITE”线。

你可能感兴趣的:(如何将光学旋转编码器与Arduino连接)