Files
foc_ccs/3rd/soft_i2c.c

104 lines
2.1 KiB
C

#include "soft_i2c.h"
#include "delay.h"
#include "ti_msp_dl_config.h"
#define DELAY 1
#define SDA_PIN_SHIFT 9 // if pa.8 shift8 , if pa.9 shift 9
void I2C_ENABLE_OUTPUT_SDA(void) {
DL_GPIO_initDigitalOutput(SOFT_I2C_SDA_IOMUX);
DL_GPIO_enableOutput(SOFT_I2C_PORT, SOFT_I2C_SDA_PIN);
}
void I2C_ENABLE_INPUT_SDA(void) {
DL_GPIO_disableOutput(SOFT_I2C_PORT, SOFT_I2C_SDA_PIN);
DL_GPIO_initDigitalInputFeatures(
SOFT_I2C_SDA_IOMUX, DL_GPIO_INVERSION_DISABLE, DL_GPIO_RESISTOR_PULL_UP,
DL_GPIO_HYSTERESIS_DISABLE, DL_GPIO_WAKEUP_DISABLE);
}
void I2C_W_SCL(uint8_t BitValue) {
if (BitValue) {
DL_GPIO_setPins(SOFT_I2C_PORT, SOFT_I2C_CLK_PIN);
} else {
DL_GPIO_clearPins(SOFT_I2C_PORT, SOFT_I2C_CLK_PIN);
}
delay_us(DELAY);
}
void I2C_W_SDA(uint8_t BitValue) {
if (BitValue) {
DL_GPIO_setPins(SOFT_I2C_PORT, SOFT_I2C_SDA_PIN);
} else {
DL_GPIO_clearPins(SOFT_I2C_PORT, SOFT_I2C_SDA_PIN);
}
delay_us(DELAY);
}
// 读取时钟线数据
uint8_t I2C_R_SDA(void) {
uint32_t BitValue;
BitValue = DL_GPIO_readPins(SOFT_I2C_PORT, SOFT_I2C_SDA_PIN);
return (uint8_t)(BitValue >> 9);
}
void I2C_Start(void) {
I2C_W_SCL(1);
I2C_W_SDA(1);
I2C_W_SDA(0);
I2C_W_SCL(0);
}
void I2C_Stop(void) {
I2C_W_SDA(0);
I2C_W_SCL(1);
I2C_W_SDA(1);
}
void I2C_SendByte(uint8_t Byte) {
uint8_t i;
for (i = 0; i < 8; i++) {
I2C_W_SDA(Byte & (0x80 >> i));
I2C_W_SCL(1);
I2C_W_SCL(0);
}
}
uint8_t I2C_RecviveData(void) {
uint8_t i, Byte = 0x00;
I2C_W_SDA(1);
for (i = 0; i < 8; i++) {
I2C_ENABLE_INPUT_SDA();
I2C_W_SCL(1);
if (I2C_R_SDA() == 1) {
Byte |= (0x80 >> i);
}
I2C_W_SCL(0);
I2C_ENABLE_OUTPUT_SDA();
}
return Byte;
}
void I2C_SendAck(uint8_t AckBit) {
I2C_W_SDA(AckBit);
I2C_W_SCL(1);
I2C_W_SCL(0);
}
uint8_t I2C_RecviveAck(void) {
uint8_t AckBit;
I2C_W_SDA(1);
I2C_ENABLE_INPUT_SDA();
I2C_W_SCL(1);
AckBit = I2C_R_SDA();
I2C_W_SCL(0);
I2C_ENABLE_OUTPUT_SDA();
return AckBit;
}