程序流程图
#include <reg51.h> #include <stdio.h> #define uchar unsigned char sbit LED = P0^0; uchar receive; uchar sdata[11]={13,10,76,69,68,58,111,'0','0',13,10}; uchar slevel[11]={13,10,108,101,118,101,108,32,'0',13,10}; uchar delayH[9]={0xFC,0xF8,0xF4,0xF0,0xEC,0xE8,0xE4,0xE0,0xDC}; uchar delayL[9]={0x18,0x30,0x48,0x60,0x78,0x90,0xA8,0xC0,0xD8}; uchar j=9; //初始亮度等级,共9级 void main(void) //程序初始化 { TMOD=0x21; //定时器T0工作在方式1,定时器T1工作在方式2 SCON=0x50; //串行口工作在方式1,允许接收 PCON=0x80; //波特率加倍 IT0=1; IT1=1; TH1=0xF3; TL1=TH1; PS=1; //串行口中断优先级为1 ES=1; EX0=1; EX1=1; EA=1; TR0=1; TR1=1; LED=1; while (1) {;} } void smessage(uchar *p1) //串行口发送程序 { uchar i; ES=0; for(i=0;i<=10;i++) { SBUF=*p1; p1++; while(!TI) {;} TI=0; } ES=1; } void adjust(uchar r1) //根据接收到的信息调整led亮灭 { if(r1==0x31) //接收到‘1’时,开启led小灯 { ET0=1; sdata[8]=0x00; sdata[7]='n'; smessage(sdata); //发送字符串LED:on } else if(r1==0x30) //接收到‘0’时,关闭led小灯 { ET0=0; LED=1; sdata[8]='f'; sdata[7]='f'; smessage(sdata); //发送字符串LED:off } if(ET0) //判断led是否开启 { if(r1==0x2B) //开启状态接收到‘+’时,亮度增加 { j++; if(j==10) //限制最高亮度 j=9; slevel[8]=j+48; //计算j数值的ASCII值 smessage(slevel); //发送字符串level j } else if(r1==0x2D) //开启状态接收到‘-’时,亮度降低 { j--; if(j==0) //限制最低亮度 j=1; slevel[8]=j+48; //计算j数值的ASCII值 smessage(slevel); //发送字符串level j } } } void int1() interrupt 2 //开关按钮中断 { if(ET0==1) receive=0x30; else receive=0x31; adjust(receive); } void int0() interrupt 0 //亮度调节按钮中断 { uchar k; k=P2; //获取P2口状态 if(k==0x7F) //亮度增加按钮被按下 { receive=0x2D; adjust(receive); } else if(k=0xBF) //亮度降低按钮被按下 { receive=0x2B; adjust(receive); } } void terminal() interrupt 4 //串行口接收中断 { RI=0; receive=SBUF; adjust(receive); } void pwm(void) interrupt 1 //pwm定频调宽,频率100Hz { if(LED) //高电平时,载入下次低电平T0初值 { TH0=delayH[j-1]; TL0=delayL[j-1]; } Else //低电平时,载入下次高电平T0初值 { TH0=delayH[9-j]; TL0=delayL[9-j]; } LED=!LED; //灯光电平取反 }
|