经常用led灯来观察现象,甚至调试代码,修改代码时用0和1很不方便,而且阅读性也不好,
故写了个宏,用起来方便些.
今天尝试控制灯的亮度. 先试试for循环控制,占空比调节...
//#include "my51.h"#include <reg52.h>typedef unsigned char u8;typedef unsigned short int u16;#ifndef _51LED_#define _51LED_#define led P1 //P1总线连8个led灯,灯连573锁存器,P1置低电平点亮#define LED led#define ON(x) P1&(~(1<<(x))) //打开某个灯,开多个灯用 ON(m) & ON(n)#define OFF(x) P1|(1<<(x)) //关闭某个灯,关多个灯用 OFF(m)| OFF(n)#define on(x) ON(x) //包含大小写#define off(x) OFF(x)#define ledon 0 //某个灯,打开#define ledoff 1 //某个灯,关闭sbit led0=P1^0; sbit led1=P1^1;sbit led2=P1^2;sbit led3=P1^3;sbit led4=P1^4;sbit led5=P1^5;sbit led6=P1^6;sbit led7=P1^7; sbit ledLock=P2^5; //锁定当前8个led的状态,0锁定 ,1不锁定#endifvoid ledCtr(u8 ledX,u8 per) //参数1是某个灯,参数2是亮度{ u8 i=1; for(i=1;i<=100;i++) { if(i<per) { led=on(ledX) ; //打开灯 } else { led=off(ledX); //关闭灯 } }}void delayms(u16 ms) //毫秒级软延时函数{ u16 i,j; for(i=ms;i>0;i--) { for(j=113;j>0;j--) {} }}void main() //测试{ led6=ledon; //打开6号灯,亮度100% led=on(0); //打开0号灯,亮度100% led=on(1) & on(5); //打开1号和5号灯,亮度100% delayms(2000); led0=ledoff; //关闭0号灯 led=off(6)|off(1)|off(5);//关闭1,5,6号灯 while(1) { ledCtr(2,5); //仅打开2号灯,亮度5%, 省电... }}
?