📄 i2c.c
字号:
// ---------------------- Software I2C bus implementation ----------------------
/* FileName: i2c.c
Version : 0.1
Last Updated: 2007-5-18
Description:
This library contains the necessary functions for Simulating SPI bus.
Program Coder: Seeseawe
*/
// Start an I2C communication
void I2C_Start(void)
{
sbi(I2C_DataPort, I2C_SDA);
sbi(I2C_DataPort, I2C_SCL);
DelayUs(I2C_DELAY);
cbi(I2C_DataPort, I2C_SDA);
DelayUs(I2C_DELAY);
cbi(I2C_DataPort, I2C_SCL);
}
// Stop an I2C Communication
void I2C_Stop(void)
{
cbi(I2C_DataPort, I2C_SDA);
sbi(I2C_DataPort, I2C_SCL);
DelayUs(I2C_DELAY);
sbi(I2C_DataPort, I2C_SDA);
DelayUs(I2C_DELAY);
}
// Send a byte to I2C Bus
void I2C_SendByte(uint8 dByte)
{
uint8 i;
for (i = 0; i < 8; i++)
{
if (((dByte<<i) & 0x80) == 0x80)
sbi(I2C_DataPort, I2C_SDA);
else
cbi(I2C_DataPort, I2C_SDA);
sbi(I2C_DataPort, I2C_SCL);
DelayUs(I2C_DELAY);
cbi(I2C_DataPort, I2C_SCL);
}
// Release the bus and clock out ACK signal from Slave
sbi(I2C_DataPort, I2C_SDA);
sbi(I2C_DataPort, I2C_SCL);
DelayUs(I2C_DELAY);
cbi(I2C_DataPort, I2C_SCL);
}
// Read a byte from the slave
uint8 I2C_ReadByte(void)
{
uint8 dByte = 0;
uint8 i;
for ( i = 0; i < 8; i++ )
{
sbi(I2C_DataPort, I2C_SDA); // Release I2C_SDA
sbi(I2C_DataPort, I2C_SCL); // Release I2C_SCL
while((I2C_DataPins & (1<<I2C_SCL)) == 0); // Synchronize clock
DelayUs(I2C_DELAY);
dByte <<= 1; // Shift left the result
if (I2C_DataPins & (1<<I2C_SDA))
dByte |= 0x01; // Set actual I2C_SDA state to LSB
cbi(I2C_DataPort, I2C_SCL); // Force a clock cycle
DelayUs(I2C_DELAY);
}
return dByte;
}
// Send an ACK or NACK signal to the slave
void I2C_SendAck(uint8 ACK)
{
if (ACK != 0)
sbi(I2C_DataPort, I2C_SDA);
else
cbi(I2C_DataPort, I2C_SDA);
sbi(I2C_DataPort, I2C_SCL);
while((I2C_DataPins & (1<<I2C_SCL)) == 0); // Synchronize clock
DelayUs(I2C_DELAY);
cbi(I2C_DataPort, I2C_SCL);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -