read()

描述

读取编码器计数器数值或脉波宽度。此函式回传值在不同工作模式下有不同意义,请见下面说明。

语法


Enc0.read()
Enc1.read()
Enc2.read()
Enc3.read()

参数

Enc0、Enc1、Enc2、Enc3:分别对应 ENC0、ENC1、ENC2、ENC3 编码器介面。

回传

Pulse/DIR、CW/CCW、A/B Pulse 模式:回传编码器所计数的值。

PWM 脉波捕捉模式:回传脉波 LOW 或 HIGH 的宽度(单位:us),最长可量测宽度约 71 分钟。注意:在此模式下,read() 只能在 ISR 函式内被呼叫,如果在其它地方被呼叫,将总是回传 0。

SSI 模式:回传由 SSI 绝对编码器读到的数值。

范例

设定 ENC0 为 A/B Pulse 模式,并读取编码器计数器数值:

#include <Encoder.h>

void setup() {
  Serial.begin(9600);
  Enc0.begin(MODE_AB_PHASE);
}

void loop() {
  Serial.println(Enc0.read()); // 读取编码器计数器数值
  delay(100);
}

设定 ENC1 为 PWM 脉波捕捉模式,并读取脉波的 HIGH、LOW 宽度:

#include <Encoder.h>

volatile unsigned long num1 = 0L;
volatile unsigned long num2 = 0L;
void encoder_isr(int flag) { // ISR 函式
    if (flag == INTR_A_PULSE_LOW) // 读取脉波 LOW 宽度
      num1 = Enc1.read();
    else if (flag == INTR_A_PULSE_HIGH) // 读取脉波 HIGH 宽度
      num2 = Enc1.read();
}

void setup() {
   Serial.begin(9600);
   Enc1.begin(MODE_CAPTURE);
   Enc1.attachInterrupt(encoder_isr); // 挂载 ISR 函式并启动中断功能
}

void loop() {
   Serial.print("LOW:");
   Serial.print(num1); // 印出脉波 LOW 的宽度,单位:us
   Serial.print("    ");
   Serial.print("HIGH:");
   Serial.println(num2); // 印出脉波 HIGH 的宽度,单位:us
   delay(100);
}

See also

attachInterrupt()


函式库参考主页面

The text of the 86Duino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.