void I2C1_ER_IRQHandler(void){
if (I2C_GetFlagStatus(I2C1, I2C_FLAG_AF)) {
I2C_ITConfig(I2C1, I2C_IT_EVT | I2C_IT_BUF, DISABLE);
I2C_ClearFlag(I2C1, I2C_FLAG_AF);
Message.status = I2C_STATUS_ERR;
}
if (I2C_GetFlagStatus(I2C1, I2C_FLAG_BERR)) {
I2C_ClearFlag(I2C1, I2C_FLAG_BERR);
}
if (I2C_GetFlagStatus(I2C1, I2C_FLAG_OVR)) {
I2C_ClearFlag(I2C1, I2C_FLAG_OVR);
}
if (I2C_GetFlagStatus(I2C1, I2C_FLAG_ARLO))
{
I2C_ClearFlag(I2C1, I2C_FLAG_ARLO);
}
}
void I2C1_EV_IRQHandler(){
uint16_t SR1;
uint16_t SR2;
SR1 = I2C1->SR1;
// Start bit event
if (SR1 & I2C_SR1_SB) {
if (Message.status == I2C_STATUS_START) {
I2C_Send7bitAddress(I2C1, Message.slaveAddress << 1, I2C_Direction_Transmitter);//2
Message.status = I2C_STATUS_ADDRESS;
}
else if (Message.status == I2C_STATUS_START_R) {
I2C_AcknowledgeConfig(I2C1, ENABLE);//5 转为读数据
I2C_Send7bitAddress(I2C1, Message.slaveAddress << 1, I2C_Direction_Receiver);
Message.status = I2C_STATUS_REDATA;
}
}
else if (SR1 & I2C_SR1_ADDR)//地址传输完成 {
SR2 = I2C1->SR2;
if (Message.status == I2C_STATUS_ADDRESS)//发送寄存器地址
{
I2C_SendData(I2C1, Message.regAddress);//4 发送地址
}
if (Message.Length == 1)//只接受一个字节
{
if (Message.status == I2C_STATUS_REDATA)
{
I2C_AcknowledgeConfig(I2C1, DISABLE);
}
}
I2C_ITConfig(I2C1, I2C_IT_BUF, ENABLE);
}
else if (SR1 & I2C_SR1_BTF) { //4 上次传输完成
if (SR1&I2C_SR1_TXE)//发送完成
{
if (Message.direction == i2cRead)//读数据
{
if (Message.status == I2C_STATUS_ADDRESS)//寄存器发送完
{
I2C1->CR1 = (I2C_CR1_START | I2C_CR1_PE);//
Message.status = I2C_STATUS_START_R;//启动读数据
}
}
else//写数据
{
I2C_SendData(I2C1, Message.buffer[Message.Index++]);
if (Message.Index == Message.Length)
{
I2C_ITConfig(I2C1, I2C_IT_EVT | I2C_IT_BUF, DISABLE);//关闭中断
I2C1->CR1 = (I2C_CR1_STOP | I2C_CR1_PE);//后续测试是否添加
Message.status = I2C_STATUS_FINSIH;
}
}
}
}
if (SR1 & I2C_SR1_RXNE)
{
Message.buffer[Message.Index++] = I2C_ReceiveData(I2C1);
if (Message.Index == Message.Length - 1)
{
I2C_AcknowledgeConfig(I2C1, DISABLE);//末尾数据禁止应答
}
if (Message.Index == Message.Length)
{
I2C1->CR1 = (I2C_CR1_STOP | I2C_CR1_PE);//后续测试是否添加
I2C_ITConfig(I2C1, I2C_IT_EVT | I2C_IT_BUF, DISABLE);//接受结束
Message.status = I2C_STATUS_FINSIH
; }
}
else if (SR1 & I2C_SR1_TXE)
{
}
}
仅供参考,网上有很多
|