我需要一段单片机模拟IIC的程序
时间: 2024-01-07 16:06:08 浏览: 79
i2c 主机模式 通信程序 PIC单片机_IIC通信模拟_PIC_
5星 · 资源好评率100%
好的,以下是一段单片机模拟IIC的程序:
```c
#include <reg51.h>
#define SCL P2_0
#define SDA P2_1
void start()
{
SDA = 1;
SCL = 1;
SDA = 0;
SCL = 0;
}
void stop()
{
SDA = 0;
SCL = 1;
SDA = 1;
}
void write_byte(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
SDA = dat & 0x80;
SCL = 1;
SCL = 0;
dat <<= 1;
}
SDA = 1;
SCL = 1;
SCL = 0;
}
unsigned char read_byte()
{
unsigned char i, dat = 0;
SDA = 1;
for (i = 0; i < 8; i++)
{
SCL = 1;
dat <<= 1;
dat |= SDA;
SCL = 0;
}
return dat;
}
unsigned char i2c_write(unsigned char device_addr, unsigned char reg_addr, unsigned char *reg_data, unsigned char cnt)
{
unsigned char i;
start();
write_byte(device_addr << 1);
if (read_byte() != 0x18)
{
stop();
return 1;
}
write_byte(reg_addr);
if (read_byte() != 0x28)
{
stop();
return 1;
}
for (i = 0; i < cnt; i++)
{
write_byte(reg_data[i]);
if (read_byte() != 0x28)
{
stop();
return 1;
}
}
stop();
return 0;
}
unsigned char i2c_read(unsigned char device_addr, unsigned char reg_addr, unsigned char *reg_data, unsigned char cnt)
{
unsigned char i;
start();
write_byte(device_addr << 1);
if (read_byte() != 0x18)
{
stop();
return 1;
}
write_byte(reg_addr);
if (read_byte() != 0x28)
{
stop();
return 1;
}
start();
write_byte((device_addr << 1) | 1);
if (read_byte() != 0x40)
{
stop();
return 1;
}
for (i = 0; i < cnt; i++)
{
reg_data[i] = read_byte();
if (i == cnt - 1)
SDA = 1;
else
SDA = 0;
SCL = 1;
SCL = 0;
}
stop();
return 0;
}
```
希望这能帮到你!
阅读全文