我正在尝试使用STM32F4发现板作为主设备,使用I2C与传感器进行通信。我正在使用std periph库来执行此操作但由于某种原因,我无法通过SCL和SDA行获取任何内容。从阅读stf periph头文件和我在网上看到的其他例子来看,我似乎没有做错任何事情或忘记了一步。下面我已经包含了我的所有I2C代码:
#define I2CTransmitter 0
#define I2CReciever 1
#define I2CAckEnable 1
#define I2CAckDisable 0
void I2CInit() {
I2C_InitTypeDef I2CInitStruct;
GPIO_InitTypeDef GPIO;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOB, ENABLE);
//Configure and initialize the GPIOs
GPIO.GPIO_Pin = GPIO_Pin_6;
GPIO.GPIO_Mode = GPIO_Mode_AF;
GPIO.GPIO_Speed = GPIO_Speed_100MHz;
GPIO.GPIO_OType = GPIO_OType_OD;
GPIO.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO);
GPIO.GPIO_Pin = GPIO_Pin_7;
GPIO_Init(GPIOB, &GPIO);
//Connect GPIO pins to peripheral
GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_I2C1);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_I2C1);
I2CInitStruct.I2C_ClockSpeed = 100000;
I2CInitStruct.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2CInitStruct.I2C_Mode = I2C_Mode_I2C;
I2CInitStruct.I2C_OwnAddress1 = 0x00;
I2CInitStruct.I2C_Ack = I2C_Ack_Enable;
I2CInitStruct.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_Init(I2C1, &I2CInitStruct);
I2C_Cmd(I2C1, ENABLE);
}
uint8_t I2CRead(uint8_t address, uint8_t reg) {
uint8_t data;
I2CStart(address, I2CTransmitter, I2CAckEnable);
I2CWriteData(reg);
I2CStart(address, I2CReciever, I2CAckDisable);
data = I2CReadNAck();
I2CStop();
return data;
}
void I2CWrite(uint8_t address, uint8_t reg, uint8_t data) {
I2CStart(address, I2CTransmitter, I2CAckEnable);
I2CWriteData(reg);
I2CWriteData(data);
I2CStop();
}
void I2CStart(uint8_t address, uint8_t direction, uint8_t ack) {
I2C_GenerateSTART(I2C1, ENABLE);
I2C_Send7bitAddress(I2C1, address, direction);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_SLAVE_BYTE_RECEIVED));
}
void I2CStop() {
I2C_GenerateSTOP(I2C1, ENABLE);
}
void I2CWriteData(uint8_t data) {
I2C_SendData(I2C1, data);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_SLAVE_BYTE_RECEIVED));
}
uint8_t I2CReadAck() {
uint8_t data;
I2C_AcknowledgeConfig(I2C1, ENABLE);
while( !I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED) );
data = I2C_ReceiveData(I2C1);
return data;
}
uint8_t I2CReadNAck() {
uint8_t data;
I2C_AcknowledgeConfig(I2C1, DISABLE);
I2C_GenerateSTOP(I2C1, ENABLE);
while( !I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED) );
data = I2C_ReceiveData(I2C1);
return data;
}
代码在main函数中使用,只需调用I2CInit()然后在while循环中调用I2CWrite()进行测试。预先感谢您的任何帮助!