现有一个项目,因为其他串口应用很多,无奈打算采取I2C与51
单片机通讯,
想法是,51单片机做主,
STM32做从,通过硬件接收中断获取51单片机的数据,但现在无法接收到数据,却在中断循环判断。寻求大侠们帮助,STM32代码如下:
#define I2C1_OWN_ADDRESS7 0xA0
#define I2C_Speed 222222;
void I2C1_Configura
tion(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* 使能与 I2C1 有关的时钟 */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1,ENABLE);
/* PB6-I2C1_SCL、PB7-I2C1_SDA*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD; // 开漏输出
GPIO_Init(GPIOB, &GPIO_InitStructure);
/* I2C 配置 */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 =I2C1_OWN_ADDRESS7;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable ;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = I2C_Speed;
I2C_ITConfig(I2C1,I2C_IT_EVT | I2C_IT_BUF, ENABLE); //开启I2C1中断的事件、缓存中断
/* 使能 I2C1 */
I2C_Cmd(I2C1, ENABLE);
/* I2C1 初始化 */
I2C_Init(I2C1, &I2C_InitStructure);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = I2C1_EV_IRQn; //使能USART2的IRQ通道()
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
/*****************************************************************
函数功能 :I2C1接收中断
******************************************************************/
void I2C1_EV_IRQHandler(void)
{
switch(I2C_GetLastEvent(I2C1))
{
case I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED : //接收到匹配的地址数据
{
break;
}
case I2C_EVENT_SLAVE_BYTE_RECEIVED :
{
if(I2C1_Rx_Idx < I2C1_BufferSize)
{
I2C1_Buffer_Rx[I2C1_Rx_Idx] = I2C_ReceiveData(I2C1);
}
break;
}
case I2C_EVENT_SLAVE_STOP_DETECTED :
{
I2C_ClearFlag(I2C1 , I2C_FLAG_STOPF);
I2C1_Flag = 1;
printf("i2c
");
break;
}
default:
{
break;
}
}
}
一周热门 更多>