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.