I2C 事件中断是指 I2C 硬件在发生特定事件时触发的中断。不同的 I2C 事件会影响通信过程,这些事件可以在 I2C 状态寄存器中监测。通常,这些事件与 I2C 总线的状态变化有关,例如生成 START
、接收 ACK
、完成数据传输等。以下是常见的 I2C 事件中断:
1. START
生成事件 (SB - Start Bit)
- 触发时机: 当主机生成
START
信号时(即调用I2C_GenerateSTART(ENABLE)
)。 - 状态寄存器标志:
SB
(SR1
状态寄存器中)。 - 作用: 进入中断后,主机可以开始发送从设备地址。
2. ADDR
事件 (Address Sent/Matched)
- 触发时机:
- 主机发送从设备地址后,收到从机的应答信号(ACK)时。
- 从机检测到主机发送了它的地址。
- 状态寄存器标志:
ADDR
(SR1
状态寄存器中)。 - 作用: 主机或从机确定通信对象,接下来准备发送或接收数据。
3. STOP
生成事件 (STOPF - Stop Detection)
- 触发时机: 主机在通信完成后发送
STOP
信号,或者从机检测到主机发送了STOP
信号。 - 状态寄存器标志:
STOPF
(SR1
状态寄存器中)。 - 作用: 通信结束,主机或从机处理停止信号,并清除标志位。
4. 传输缓冲区空 (TxE - Data Register Empty)
- 触发时机: 当数据寄存器中的数据已经成功发送,并且硬件准备好接受新数据时。
- 状态寄存器标志:
TxE
(SR1
状态寄存器中)。 - 作用: 主机或从机可以继续发送下一个字节的数据。
5. 接收缓冲区非空 (RxNE - Data Register Not Empty)
- 触发时机: 当一个字节的数据接收完成并存储在数据寄存器中时。
- 状态寄存器标志:
RxNE
(SR1
状态寄存器中)。 - 作用: 从寄存器中读取接收到的数据,继续通信。
6. 字节传输完成事件 (BTF - Byte Transfer Finished)
- 触发时机:
- 当主机发送或接收了一个字节的数据,并且该字节传输完成时。
- 如果发送的是最后一个字节,主机会根据
BTF
标志来决定是否发送STOP
信号。
- 状态寄存器标志:
BTF
(SR1
状态寄存器中)。 - 作用: 表示当前字节传输已经完成,可以开始处理下一个字节。
7. 应答失败事件 (AF - Acknowledge Failure)
- 触发时机: 主机在发送数据或地址后,未收到从机的应答(NACK)时。
- 状态寄存器标志:
AF
(SR1
状态寄存器中)。 - 作用: 主机未收到应答信号,通信可能失败,主机需要处理错误。
8. 总线错误事件 (Bus Error - BER)
- 触发时机: 当 I2C 总线在非预期的时间内检测到开始或停止条件时,会出现总线错误。
- 状态寄存器标志:
BER
(SR1
状态寄存器中)。 - 作用: 通信出现严重错误,主机或从机需要停止通信并重新初始化总线。
9. 仲裁丢失事件 (ARLO - Arbitration Lost)
- 触发时机: 在多主机的 I2C 通信中,如果一个主机在发送数据时发现其仲裁失败,意味着它失去了控制总线的权利。
- 状态寄存器标志:
ARLO
(SR1
状态寄存器中)。 - 作用: 通信中断,主机需要重新尝试获取总线控制权。
10. 超时事件 (Timeout - TIMEOUT)
- 触发时机: 当通信超时或出现长时间未响应的情况时。
- 状态寄存器标志:
TIMEOUT
(SR1
状态寄存器中)。 - 作用: 通信超时,可能需要重新初始化或停止通信。
11. PEC 错误事件 (Packet Error Checking Error - PECERR)
- 触发时机: 当启用 PEC(数据包错误检查)模式时,如果校验的 PEC 值不匹配,则会触发该事件。
- 状态寄存器标志:
PECERR
(SR1
状态寄存器中)。 - 作用: 表示数据包错误,主机或从机需要重新传输数据。
if (event & (RB_I2C_BTF | RB_I2C_TxE)) 判断是否进入中断
小结:
以上这些事件中断通常是在 I2C 中断服务例程(ISR)中检测到的,开发者通过查询状态寄存器中的相应标志位来判断当前的总线状态,并采取相应的操作。不同的中断事件对应着 I2C 通信的不同阶段,帮助确保通信的正确性和完整性。