我用STM32F103CB跟Mega8做I2C通信,看了资料,STM32的I2C管脚可以支持5V,所以将STM32的SCL和SDA上拉到5V,跟MEGA8通信。MEGA8的程序测试过,应该是没有问题的。
以下是STM32的程序:
#define I2C1_HOST_ADDRESS7 0x01
#define I2C1_SLAVE_ADDRESS7 0x02
#define ClockSpeed 200000
I2C_InitTypeDef I2C_InitStructure;
void I2C_Configuration(void)
{
/* Enable I2C1 ----------------------------------------------------*/
I2C_Cmd(I2C1, ENABLE);
/* I2C1 configuration ------------------------------------------------------*/
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = I2C1_HOST_ADDRESS7;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = ClockSpeed;
I2C_Init(I2C1, &I2C_InitStructure);
/* Send I2C1 START condition */
I2C_GenerateSTART(I2C1, ENABLE);
/* Test on I2C1 EV5 and clear it */
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
/* Send I2C2 slave Address for write */
I2C_Send7bitAddress(I2C1, I2C1_SLAVE_ADDRESS7, I2C_Direction_Transmitter);
/* Test on I2C1 EV6 and clear it */
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
/* Send I2C1 data */
I2C_SendData(I2C1, 0xaa);
/* Test on I2C1 EV8 and clear it */
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
/* Send I2C1 STOP Condition */
I2C_GenerateSTOP(I2C1, ENABLE);
}
RCC_APB1PeriphClockCmd( RCC_APB1Periph_I2C1, ENABLE );
/* Configure I2C1 pins: SCL and 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);
主机发送完START信号后,读取SR1和SR2寄存器的值,始终是0,而MEGA8接收不到ACK信号。郁闷了好几天了,高手帮忙解答一下吧~ |