STM32F103 IIC代码
时间: 2023-11-12 11:07:54 浏览: 71
以下是一个示例STM32F103的I2C代码,用于从一个I2C设备读取数据:
```
#include "stm32f10x.h"
#define I2C_SPEED 100000 // I2C速度为100kHz
#define I2C_SLAVE_ADDRESS 0xA0 // I2C从设备地址
void I2C_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
// 使能I2C时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
// 使能GPIO时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 配置GPIO为开漏输出
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 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = I2C_SPEED;
I2C_Init(I2C1, &I2C_InitStructure);
// 使能I2C
I2C_Cmd(I2C1, ENABLE);
}
void I2C_ReadData(uint8_t *buffer, uint8_t length)
{
uint8_t i;
// 发送启动信号
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
// 发送从设备地址
I2C_Send7bitAddress(I2C1, I2C_SLAVE_ADDRESS, I2C_Direction_Receiver);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
// 读取数据
for(i = 0; i < length; i++)
{
if(i == length - 1)
{
// 最后一个字节不应答
I2C_AcknowledgeConfig(I2C1, DISABLE);
I2C_GenerateSTOP(I2C1, ENABLE);
}
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
buffer[i] = I2C_ReceiveData(I2C1);
}
// 恢复应答位
I2C_AcknowledgeConfig(I2C1, ENABLE);
}
int main(void)
{
uint8_t buffer[10];
I2C_Configuration();
// 从设备读取数据
I2C_ReadData(buffer, 10);
while(1);
}
```
阅读全文