# 轮编码器一次遮光触发多次中断

> 原文链接：https://robotics.hellobike.com/pitfalls/2016-01-20-robotics-se-8950
> 频道：pitfalls | 更新日期：2016-01-20 | 标签：auto, stackexchange, arduino, wheel, two-wheeled, interrupts
> 核心摘要：Arduino 轮编码器状态变化时多次触发中断，采用去抖逻辑后只在真实变化时计数。

# 轮编码器一次遮光触发多次中断

::: v-pre
> 本文由 AI 根据公开内容整理，可能有误，请以原文为准：[Wheel encoder triggers interrupt too many times](https://robotics.stackexchange.com/questions/8950/wheel-encoder-triggers-interrupt-too-many-times)（Robotics Stack Exchange #8950）

**状态**：已解决

## 问题

轮编码器光束被切断一次时，`attachInterrupt` 绑定的中断多次触发；即使用 `RISING`，从 `HIGH` 到 `LOW` 时也会计数，`count` 一次变化可增加 9、15、26 等。

## 环境

Arduino；两驱动轮简易机器人；轮编码器接数字引脚 `2`，后续方案使用 `2` 和 `3`。

## 解决办法

1. 将中断改为监听 `CHANGE`，分别为左右编码器绑定 `doEncoderRight` 和 `doEncoderLeft`。
2. 对编码器输入启用上拉：`pinMode(..., INPUT)` 后 `digitalWrite(..., HIGH)`。
3. 在中断函数中用 `firstChangeR`、`firstChangeL` 标记第一次变化；第一次检测到变化时 `delay(1)` 等待抖动结束。
4. 用 `digitalRead` 与保存的真实状态 `right_set`、`left_set` 比较；只有当前状态不同于保存状态时才翻转状态并递增 `countR` 或 `countL`。
5. 在 `loop` 中将 `firstChangeR`、`firstChangeL` 重置为 `true`，等待下一次触发。

原问题作者：ejalaa12；采纳答案作者：ejalaa12。原内容依 CC BY-SA 4.0 授权，本页摘要同样依 CC BY-SA 4.0 授权。
:::

## 原始参考来源 (Sources)

- [Robotics Stack Exchange #8950：Wheel encoder triggers interrupt too many times](https://robotics.stackexchange.com/questions/8950/wheel-encoder-triggers-interrupt-too-many-times)