softwareI2C/i2c.c

157 lines
3.0 KiB
C
Raw Normal View History

#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;
}