kile环境,f103芯片,使用HAL库编写iic通信程序,并写出.c与 .h文件
时间: 2024-05-01 13:20:44 浏览: 208
基于HAL库的stm32f103单片机实现DMA+串口的接收、发送数据功能代码
以下是基于HAL库编写的STM32F103芯片I2C通信程序的.c和.h文件示例:
.i2c.h文件
```
#ifndef __I2C_H
#define __I2C_H
#ifdef __cplusplus
extern "C" {
#endif
#include "stm32f1xx_hal.h"
#define I2C_TIMEOUT 0xFFFF
void I2C_Init(I2C_HandleTypeDef *hi2c);
HAL_StatusTypeDef I2C_Write(I2C_HandleTypeDef *hi2c, uint8_t dev_addr, uint8_t *data, uint16_t size);
HAL_StatusTypeDef I2C_Read(I2C_HandleTypeDef *hi2c, uint8_t dev_addr, uint8_t *data, uint16_t size);
#ifdef __cplusplus
}
#endif
#endif /* __I2C_H */
```
.i2c.c文件
```
#include "i2c.h"
/* I2C initialization function */
void I2C_Init(I2C_HandleTypeDef *hi2c) {
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* Enable I2C GPIO clocks */
__HAL_RCC_GPIOB_CLK_ENABLE();
/* Configure I2C GPIO pins */
GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* Enable I2C clock */
__HAL_RCC_I2C1_CLK_ENABLE();
/* Configure I2C */
hi2c->Instance = I2C1;
hi2c->Init.ClockSpeed = 100000; /* I2C clock frequency */
hi2c->Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c->Init.OwnAddress1 = 0;
hi2c->Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c->Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c->Init.OwnAddress2 = 0;
hi2c->Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c->Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
HAL_I2C_Init(hi2c);
}
/* I2C write function */
HAL_StatusTypeDef I2C_Write(I2C_HandleTypeDef *hi2c, uint8_t dev_addr, uint8_t *data, uint16_t size) {
HAL_StatusTypeDef status;
/* Wait until the bus is ready */
while (HAL_I2C_GetState(hi2c) != HAL_I2C_STATE_READY);
/* Send device address with write command */
status = HAL_I2C_Master_Transmit(hi2c, dev_addr << 1, data, size, I2C_TIMEOUT);
/* Return status */
return status;
}
/* I2C read function */
HAL_StatusTypeDef I2C_Read(I2C_HandleTypeDef *hi2c, uint8_t dev_addr, uint8_t *data, uint16_t size) {
HAL_StatusTypeDef status;
/* Wait until the bus is ready */
while (HAL_I2C_GetState(hi2c) != HAL_I2C_STATE_READY);
/* Send device address with read command */
status = HAL_I2C_Master_Receive(hi2c, (dev_addr << 1) | 1, data, size, I2C_TIMEOUT);
/* Return status */
return status;
}
```
在主函数中,首先需要初始化I2C:
```
I2C_HandleTypeDef hi2c1;
int main(void) {
/* Initialize HAL Library */
HAL_Init();
/* Initialize I2C */
I2C_Init(&hi2c1);
/* ... */
}
```
之后,可以使用I2C_Write和I2C_Read函数向I2C设备写入和读取数据:
```
#define I2C_DEVICE_ADDR 0x50
uint8_t data[2] = {0xAA, 0x55};
/* Write data */
if (I2C_Write(&hi2c1, I2C_DEVICE_ADDR, data, 2) == HAL_OK) {
/* ... */
}
/* Read data */
if (I2C_Read(&hi2c1, I2C_DEVICE_ADDR, data, 2) == HAL_OK) {
/* ... */
}
```
阅读全文