把i2c.c 和 i2c.h写出来
时间: 2024-02-17 09:05:16 浏览: 60
以下是一个简单的I2C库函数的示例,包括i2c.c和i2c.h文件:
i2c.h:
```c
#ifndef __I2C_H__
#define __I2C_H__
#include "stm32f10x.h"
void i2c_init(void);
void i2c_write(uint8_t addr, uint8_t *data, uint16_t len);
void i2c_read(uint8_t addr, uint8_t *data, uint16_t len);
#endif /* __I2C_H__ */
```
i2c.c:
```c
#include "i2c.h"
#define I2C_SPEED 100000 // I2C总线速度,单位为Hz
void i2c_init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
I2C_InitTypeDef I2C_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // 使能GPIOB时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE); // 使能I2C1时钟
// 配置GPIOB6和GPIOB7为复用推挽输出
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
// 配置I2C1为标准模式,时钟速度为100kHz
I2C_InitStruct.I2C_Mode = I2C_Mode_I2C;
I2C_InitStruct.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStruct.I2C_OwnAddress1 = 0x00;
I2C_InitStruct.I2C_Ack = I2C_Ack_Enable;
I2C_InitStruct.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStruct.I2C_ClockSpeed = I2C_SPEED;
I2C_Init(I2C1, &I2C_InitStruct);
I2C_Cmd(I2C1, ENABLE); // 使能I2C1
}
void i2c_write(uint8_t addr, uint8_t *data, uint16_t len)
{
uint32_t timeout = 0;
while (I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY))
{
if (++timeout > 0x10000)
return;
}
I2C_GenerateSTART(I2C1, ENABLE);
timeout = 0;
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))
{
if (++timeout > 0x10000)
return;
}
I2C_Send7bitAddress(I2C1, addr << 1, I2C_Direction_Transmitter);
timeout = 0;
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
{
if (++timeout > 0x10000)
return;
}
while (len--)
{
I2C_SendData(I2C1, *data++);
timeout = 0;
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
{
if (++timeout > 0x10000)
return;
}
}
I2C_GenerateSTOP(I2C1, ENABLE);
}
void i2c_read(uint8_t addr, uint8_t *data, uint16_t len)
{
uint32_t timeout = 0;
while (I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY))
{
if (++timeout > 0x10000)
return;
}
I2C_GenerateSTART(I2C1, ENABLE);
timeout = 0;
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))
{
if (++timeout > 0x10000)
return;
}
I2C_Send7bitAddress(I2C1, addr << 1, I2C_Direction_Receiver);
timeout = 0;
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))
{
if (++timeout > 0x10000)
return;
}
while (len--)
{
if (len == 0)
I2C_AcknowledgeConfig(I2C1, DISABLE);
timeout = 0;
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
if (++timeout > 0x10000)
return;
}
*data++ = I2C_ReceiveData(I2C1);
}
I2C_AcknowledgeConfig(I2C1, ENABLE);
I2C_GenerateSTOP(I2C1, ENABLE);
}
```
需要注意的是,上述代码中的RCC_APB2PeriphClockCmd()、RCC_APB1PeriphClockCmd()和GPIO_Init()等函数需要根据具体的STM32开发板和引脚进行修改。同时还需要根据具体的I2C总线速度和使用的I2C模式来修改i2c_init()函数中的配置参数。
阅读全文