单片机s52简易红绿灯c语言编程,【原创】两片S52单片机使用2个IO口进行通信

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

//晶振:11.0592MHz

//收数据

#include

sbit TSCLK=P3^3;

sbit TSDAT=P1^6;

sbit LED1=P2^0;

sbit LED2=P2^1;

sbit LED3=P2^2;

sbit LED4=P2^3;

sbit LED5=P2^4;

sbit LED6=P2^5;

sbit LED7=P2^6;

sbit LED8=P2^7;

sbit fmq=P3^6; //这是蜂鸣器

unsigned char num[4]={0,0,0,0};

unsigned char code DIS_SEG7[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};

unsigned int lowtime,hightime;

//延迟n毫秒

void delay(unsigned int n)

{

while (n--)

{

TH0=0xfc;

TL0=0x66; //11.0592MHz

TF0=0;

TR0=1;

while (TF0==0);

TF0=0;

}

}

void superdelay(unsigned char h, unsigned char l)

{

TH0=h;

TL0=l;

TF0=0;

TR0=1;

while (TF0==0);

TR0=0;

}

//延迟半毫秒

void delay500us()

{

superdelay(0xfe,0x33);

}

//蜂鸣器

void beep()

{

unsigned char i;

for (i=0;i<150;i++)

{

fmq=0;

delay500us();

fmq=1;

delay500us();

}

}

void receivebyte(unsigned char* Data)

{

unsigned char i;

unsigned int time;

for (i=0;i<8;i++)

{

*Data<<=1; //不应该在for循环的最后执行此操作,否则第一位会丢失

TH0=TL0=0;

while (TSDAT==0); //跳过低电平

TR0=1;

while (TSDAT==1 && TF0==0); //根据高电平长度判断是0还是1

TR0=0;

time=TH0*256+TL0;

if (time>950)

*Data|=0x01; //读1

else

*Data&=0xfe; //读0

}

}

void Display()

{

P0=0xff;

LED1=0;

P0=DIS_SEG7[num[0]/10];

delay(1);

LED1=1;

P0=0xff;

LED2=0;

P0=DIS_SEG7[num[0]%10];

delay(1);

LED2=1;

P0=0xff;

LED3=0;

P0=DIS_SEG7[num[1]/10];

delay(1);

LED3=1;

P0=0xff;

LED4=0;

P0=DIS_SEG7[num[1]%10];

delay(1);

LED4=1;

P0=0xff;

LED5=0;

P0=DIS_SEG7[num[2]/10];

delay(1);

LED5=1;

P0=0xff;

LED6=0;

P0=DIS_SEG7[num[2]%10];

delay(1);

LED6=1;

P0=0xff;

LED7=0;

P0=DIS_SEG7[num[3]/10];

delay(1);

LED7=1;

P0=0xff;

LED8=0;

P0=DIS_SEG7[num[3]%10];

delay(1);

LED8=1;

}

void main()

{

TMOD=0x01; //定时器2工作于16位查询工作方式

TR0=0;

EA=1;

EX1=1;

IT1=1;

while (1)

{

P1_7=0;

Display();

P1_7=1;

}

}

void int1() interrupt 2

{

EX1=0;

//检测引导码

//数据线1ms低电平和2.5ms高电平

TH0=TL0=0;

TR0=1;

while (TSDAT==0);

TR0=0;

lowtime=TH0*256+TL0;

TH0=TL0=0;

TR0=1;

while (TSDAT==1);

TR0=0;

hightime=TH0*256+TL0;

//对于低电平:1000us/1.085=921,实际值通常为934

//对于高电平:2500/1.085=2304,实际值通常为2365或2367

if (lowtime>880 && lowtime<980 && hightime>2300 && hightime<2400)

{

receivebyte(&num[0]);

receivebyte(&num[1]);

receivebyte(&num[2]);

receivebyte(&num[3]);

delay500us(); //全部数据接收完毕后,等待时钟线拉高,防止再次进入本中断

}

else

beep(); //引导码不合法

EX1=1;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值