两个单片机iic通讯程序_怎样从零学单片机?
时间: 2023-08-07 19:04:16 浏览: 75
IIC(Inter-Integrated Circuit)总线是一种常用的通信协议,可用于单片机与各种外设之间的通讯,如传感器、存储器、显示器等。
下面是两个单片机之间使用IIC通讯的程序:
主机程序:
```c
#include<reg52.h>
#include<intrins.h>
#define SDA P2_0
#define SCL P2_1
sbit SDA=P2^0;
sbit SCL=P2^1;
void delay(int x)
{
int i,j;
for(i=0;i<x;i++)
for(j=0;j<110;j++);
}
void init_IIC()
{
SDA=1;
SCL=1;
}
void start()
{
SDA=1;
SCL=1;
delay(5);
SDA=0;
delay(5);
SCL=0;
delay(5);
}
void stop()
{
SDA=0;
SCL=1;
delay(5);
SDA=1;
delay(5);
}
void send_ack(bit ack)
{
SDA=ack;
SCL=1;
delay(5);
SCL=0;
delay(5);
}
bit receive_ack()
{
SCL=1;
delay(5);
if(SDA==1)
{
SCL=0;
return 0;
}
else
{
SCL=0;
return 1;
}
}
void send_byte(unsigned char data)
{
unsigned char i;
for(i=0;i<8;i++)
{
SDA=(data&0x80)>>7;
data<<=1;
SCL=1;
delay(5);
SCL=0;
delay(5);
}
}
unsigned char receive_byte()
{
unsigned char i,data=0;
for(i=0;i<8;i++)
{
SCL=1;
delay(5);
data<<=1;
data|=SDA;
SCL=0;
delay(5);
}
return data;
}
void main()
{
unsigned char data=0x55;
init_IIC();
start();
send_byte(0xA0);
receive_ack();
send_byte(0x00);
receive_ack();
send_byte(data);
receive_ack();
stop();
delay(500);
}
```
从机程序:
```c
#include<reg52.h>
#include<intrins.h>
#define SDA P2_0
#define SCL P2_1
sbit SDA=P2^0;
sbit SCL=P2^1;
void delay(int x)
{
int i,j;
for(i=0;i<x;i++)
for(j=0;j<110;j++);
}
void init_IIC()
{
SDA=1;
SCL=1;
}
void wait()
{
while(SDA==0);
}
void receive_byte()
{
unsigned char data;
SCL=1;
delay(5);
data=SDA;
SCL=0;
delay(5);
return data;
}
void send_ack(bit ack)
{
SDA=ack;
SCL=1;
delay(5);
SCL=0;
delay(5);
}
void main()
{
unsigned char data;
init_IIC();
while(1)
{
wait();
if(receive_byte()==0xA0)
{
send_ack(1);
wait();
if(receive_byte()==0x00)
{
send_ack(1);
data=receive_byte();
send_ack(0);
}
}
}
}
```
这是一个简单的例子,主机发送一个字节给从机,从机接收并发送回去。在实际应用中,可以根据需要修改程序。
阅读全文