generated from hulk/gd32e23x_template
iic驱动重写
This commit is contained in:
78
src/i2c.c
Normal file
78
src/i2c.c
Normal file
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// Created by dell on 24-12-4.
|
||||
//
|
||||
|
||||
#include "i2c.h"
|
||||
|
||||
/**
|
||||
* @brief 向I2C设备寄存器写入数据
|
||||
* @param device_address: 设备地址
|
||||
* @param data: 要写入的数据
|
||||
* @retval int: 0表示成功,-1表示超时
|
||||
*/
|
||||
int i2c_write_reg(uint8_t device_address, uint8_t *data)
|
||||
{
|
||||
uint32_t timeout = 0;
|
||||
|
||||
// 生成起始条件
|
||||
while (i2c_flag_get(LDC_I2C, I2C_FLAG_I2CBSY) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
i2c_start_on_bus(LDC_I2C);
|
||||
timeout = 0;
|
||||
|
||||
// 等待起始条件发送完成
|
||||
while (!i2c_flag_get(LDC_I2C, I2C_FLAG_SBSEND) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
i2c_master_addressing(LDC_I2C, device_address, I2C_TRANSMITTER);
|
||||
timeout = 0;
|
||||
|
||||
// 等待地址发送完成
|
||||
while (!i2c_flag_get(LDC_I2C, I2C_FLAG_ADDSEND) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
i2c_flag_clear(LDC_I2C, I2C_FLAG_ADDSEND);
|
||||
timeout = 0;
|
||||
|
||||
// 发送寄存器地址
|
||||
while (!i2c_flag_get(LDC_I2C, I2C_FLAG_TBE) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
// 发送寄存器地址和数据
|
||||
for (int i = 0; i < 3; i++) {
|
||||
while (!i2c_flag_get(LDC_I2C, I2C_FLAG_TBE) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
i2c_data_transmit(LDC_I2C, data[i]);
|
||||
timeout = 0;
|
||||
}
|
||||
timeout = 0;
|
||||
|
||||
// 生成停止条件
|
||||
while (!i2c_flag_get(LDC_I2C, I2C_FLAG_BTC) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
i2c_stop_on_bus(LDC_I2C);
|
||||
timeout = 0;
|
||||
|
||||
while (i2c_flag_get(LDC_I2C, I2C_FLAG_STPDET) && (timeout < I2C_TIME_OUT))
|
||||
timeout++;
|
||||
if (timeout >= I2C_TIME_OUT) {
|
||||
return -1; // 超时返回错误
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user