51單片機(jī)利用LED宏,控制LED等的亮度
經(jīng)常用led燈來(lái)觀察現(xiàn)象,甚至調(diào)試代碼,修改代碼時(shí)用0和1很不方便,而且閱讀性也不好,利用個(gè)宏,用起來(lái)方便些。
今天嘗試控制燈的亮度. 先試試for循環(huán)控制,占空比調(diào)節(jié)...
c代碼
//#include my51.h
#include
typedef unsigned char u8;
typedef unsigned short int u16;
#ifndef _51LED_
#define _51LED_
#define led P1 //P1總線連8個(gè)led燈,燈連573鎖存器,P1置低電平點(diǎn)亮
#define LED led
#define ON(x) P1(~(1(x))) //打開(kāi)某個(gè)燈,開(kāi)多個(gè)燈用 ON(m) ON(n)
#define OFF(x) P1|(1(x)) //關(guān)閉某個(gè)燈,關(guān)多個(gè)燈用 OFF(m)| OFF(n)
#define on(x) ON(x) //包含大小寫(xiě)
#define off(x) OFF(x)
#define ledon 0 //某個(gè)燈,打開(kāi)
#define ledoff 1 //某個(gè)燈,關(guān)閉
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; //鎖定當(dāng)前8個(gè)led的狀態(tài),0鎖定 ,1不鎖定
#endif
void ledCtr(u8 ledX,u8 per) //參數(shù)1是某個(gè)燈,參數(shù)2是亮度
{
u8 i=1;
for(i=1;i=100;i++)
{
if(i
{
led=on(ledX) ; //打開(kāi)燈
}
else
{
led=off(ledX); //關(guān)閉燈
}
}
}
void delayms(u16 ms) //毫秒級(jí)軟延時(shí)函數(shù)
{
u16 i,j;
for(i=ms;i>0;i--)
{
for(j=113;j>0;j--)
{}
}
}
void main() //測(cè)試
{
led6=ledon; //打開(kāi)6號(hào)燈,亮度100%
led=on(0); //打開(kāi)0號(hào)燈,亮度100%
led=on(1) on(5); //打開(kāi)1號(hào)和5號(hào)燈,亮度100%
delayms(2000);
led0=ledoff; //關(guān)閉0號(hào)燈
led=off(6)|off(1)|off(5);//關(guān)閉1,5,6號(hào)燈
while(1)
{
ledCtr(2,5); //僅打開(kāi)2號(hào)燈,亮度5%, 省電...
}
}
評(píng)論