softwareI2C/i2c.c
JRNitre 7bd40527b1 2025-04-02 v1.1
对之前遗留下来的乱码用 utf-8 重新编写
增加了标准的函数&文件注释
2025-04-02 09:10:11 +08:00

157 lines
3.0 KiB
C

#include "i2c.h"
/*
* @brief 初始化 I2C 对应的引脚和定时器
* @param void
*
* @return void
*/
void i2cInit(void){
GPIO_InitTypeDef GPIO_InitStruct;
I2C_RCC_CLOCK_CMD;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType = GPIO_OType_OD;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Pin = I2C_SCL_PIN | I2C_SDA_PIN;
GPIO_Init(I2C_GROUP,&GPIO_InitStruct);
GPIO_SetBits(I2C_GROUP, I2C_SCL_PIN);
GPIO_SetBits(I2C_GROUP, I2C_SDA_PIN);
// tim2 init
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 83;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_Cmd(TIM2, ENABLE);
}
/*
* @brief 延时函数
* @param uint32_t us 延时时长 us
*
* @return void
*/
void i2cDelay_us(uint32_t us){
TIM_SetCounter(TIM2, 0);
// wait counter to target
while(TIM_GetCounter(TIM2) < us);
}
/*
* @brief 软件 i2c 引脚操纵函数
* @param uint8_t BitValue 0->低电平/1->高电平
*
* @return void
*/
void i2cCon_SCL(uint8_t BitValue){
GPIO_WriteBit(I2C_GROUP, I2C_SCL_PIN, (BitAction)(BitValue));
i2cDelay_us(i2cSpeedDelay);
}
void i2cCon_SDA(uint8_t BitValue){
GPIO_WriteBit(I2C_GROUP, I2C_SDA_PIN, (BitAction)(BitValue));
i2cDelay_us(i2cSpeedDelay);
}
/*
* @brief 从 i2c SDA 引脚上读取一个 bit 电平
* @param void
*
* @return uint8_t 总线电平状态
*/
uint8_t i2cReceive_SDA(void){
uint8_t bitValue = GPIO_ReadInputDataBit(I2C_GROUP, I2C_SDA_PIN);
i2cDelay_us(i2cSpeedDelay);
return bitValue;
}
/*
* @brief 发送起始&终止信号
* @param void
*
* @return void
*/
void i2cSignal_Start(void){
i2cCon_SDA(1);
i2cCon_SCL(1);
i2cCon_SDA(0);
i2cCon_SCL(0);
}
void i2cSignal_Stop(void){
i2cCon_SDA(0);
i2cCon_SCL(1);
i2cCon_SDA(1);
}
/*
* @brief 发送一个 byte 数据
* @param uint8_t byte 需要发送的数据
*
* @return void
*/
void i2cSend_Byte(uint8_t byte){
for(int i = 0; i < 8; i++){
i2cCon_SDA(!!(byte & (0x80 >> i)));
i2cCon_SCL(1);
i2cCon_SCL(0);
}
}
/*
* @brief 接收一个 byte 数据
* @param void
*
* @return uint8_t 接收到的数据
*/
uint8_t i2cReceive_Byte(void){
uint8_t rByte = 0x00;
i2cCon_SDA(1);
for(int i = 0; i < 8; i++){
i2cCon_SCL(1);
if(i2cReceive_SDA() == 1){
rByte |= (0x80 >> i);
}
i2cCon_SCL(0);
}
return rByte;
}
/*
* @brief 发送应答信号
* @param uint8_t ackBit 0->无应答/1->应答
*
* @return void
*/
void i2cSend_ACK(uint8_t ackBit){
i2cCon_SDA(ackBit);
i2cCon_SCL(1);
i2cCon_SCL(0);
}
/*
* @brief 接收应答信号
* @param void
*
* @return uint8_t 是否有应答
*/
uint8_t i2cReceive_ACK(void){
i2cCon_SDA(1);
i2cCon_SCL(1);
uint8_t ackBit = i2cReceive_SDA();
i2cCon_SCL(0);
return ackBit;
}