setRange()

描述

设定内部计数器的上限值(下限值总是为 0)。当计数器值递增到上限值后回到 0,会触发一次计数溢出的中断事件;相反的,计数器值递减到 0 后回到上限值,也会触发一次计数回卷的中断事件。

注意:从 86Duino Coding 105 版本以后才能使用这个函式,并且只可在 Pulse/DIR、CW/CCW、A/B Pulse 工作模式下使用。

语法


Enc0.setRange(val)
Enc0.setRange(val, condition)

Enc1.setRange(val)
Enc1.setRange(val, condition)

Enc2.setRange(val)
Enc2.setRange(val, condition)

Enc3.setRange(val)
Enc3.setRange(val, condition)

参数

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

val:计数器的上限值,范围是 1 ~ 4,294,967,295 (2^32 – 1)。假如设定此值为 199,那么计数器值会在递增到 199 后回到 0,或者递减到 0 后回到 199 。

condition:true 或 false。如果要启动计数溢出和计数回卷的中断事件,则设定 true,反之则设定 false。(预设值是 true)

回传

无回传值

范例

#include "Encoder.h"

volatile int ovnumber = 0;
volatile int uvnumber = 0;
void encoder_callback(int flag) {
  if(flag == INTR_OVERFLOW) // 假如是计数溢出的中断事件
    ovnumber++;
  else if(flag == INTR_UNDERFLOW) // 假如是计数回卷的中断事件
    uvnumber++;
}

void setup() {
  Serial.begin(9600);
  Enc0.begin(MODE_AB_PHASE);
  Enc0.setRange(199); // 设定上限值为 199
  Enc0.attachInterrupt(encoder_callback); // 挂载 callback 函式并启动中断功能
}

void loop() {
  Serial.print("count = ");
  Serial.print(Enc0.read()); // 读取编码器的计数值
  Serial.print(" ");
  Serial.print("overflow = ");
  Serial.print(ovnumber); // 印出计数溢出的次数
  Serial.print(" ");
  Serial.print("underflow = ");
  Serial.println(uvnumber); // 印出计数回卷的次数
  
  delay(100);
}

See also

setComparator()
setIndexReset()


函式库参考主页面

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.