實現(xiàn)LED分級亮度的簡便算法
#include"reg52.h"
unsigned char code table[]={0xfe,0xfc,0xf0,0xe0,0xc0,0x80,0x00};
void main()
{
unsigned char i;
while(1)
{
i++;
i=0x07;
P1=table;
}
}
低電平點亮LED,i=0到7;
while循環(huán)周期*8=PWM的周期
當(dāng)i=0時,D0亮
當(dāng)i=1時,D0,D1亮
當(dāng)i=2時,D0,D1,D2亮
。。。。。。
當(dāng)i=7時,D0,D1,D2,D3,D4,D5,D6,D7全亮
也就是說,在while的8個循環(huán)中,D0一直亮,D1則只有7次亮。。。。。。D7則只有1次亮
按照這個算法,只要定義一個一維表格,就可以靜態(tài)現(xiàn)實LED的8個不同亮度,且亮度次序任意
如果定義一個二維表格,則可以動態(tài)現(xiàn)實LED亮度,幾乎可以任意定義次序花樣
下面來看一個完整的二維數(shù)組漸變程序
完整代碼下載地址:http://www.51hei.com/f/jianb.rar
#include "reg52.h" unsigned char code table[37][8]= //定義一個2維數(shù)組 {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,//off 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,//D0亮度等級1/8 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfc,//D1亮度等級1/8 0xff,0xff,0xff,0xff,0xff,0xff,0xfd,0xfc,//D1亮度等級2/8 0xff,0xff,0xff,0xff,0xff,0xff,0xfd,0xf8,//D2亮度等級1/8 0xff,0xff,0xff,0xff,0xff,0xff,0xf9,0xf8,//D2亮度等級2/8 0xff,0xff,0xff,0xff,0xff,0xfb,0xf9,0xf8,//D2亮度等級3/8 0xff,0xff,0xff,0xff,0xff,0xfb,0xf9,0xf0,//D3 0xff,0xff,0xff,0xff,0xff,0xfb,0xf1,0xf0, 0xff,0xff,0xff,0xff,0xff,0xf3,0xf1,0xf0, 0xff,0xff,0xff,0xff,0xf7,0xf3,0xf1,0xf0, 0xff,0xff,0xff,0xff,0xf7,0xf3,0xf1,0xe0,//D4 0xff,0xff,0xff,0xff,0xf7,0xf3,0xe1,0xe0, 0xff,0xff,0xff,0xff,0xf7,0xe3,0xe1,0xe0, 0xff,0xff,0xff,0xff,0xe7,0xe3,0xe1,0xe0, 0xff,0xff,0xff,0xef,0xe7,0xe3,0xe1,0xe0, 0xff,0xff,0xff,0xef,0xe7,0xe3,0xe1,0xc0,//D5 0xff,0xff,0xff,0xef,0xe7,0xe3,0xc1,0xc0, 0xff,0xff,0xff,0xef,0xe7,0xc3,0xc1,0xc0, 0xff,0xff,0xff,0xef,0xc7,0xc3,0xc1,0xc0, 0xff,0xff,0xff,0xcf,0xc7,0xc3,0xc1,0xc0, 0xff,0xff,0xdf,0xcf,0xc7,0xc3,0xc1,0xc0, 0xff,0xff,0xdf,0xcf,0xe7,0xe3,0xc1,0x80,//D6 0xff,0xff,0xdf,0xcf,0xe7,0xe3,0x81,0x80, 0xff,0xff,0xdf,0xcf,0xe7,0x83,0x81,0x80, 0xff,0xff,0xdf,0xcf,0x87,0x83,0x81,0x80, 0xff,0xff,0xdf,0x8f,0x87,0x83,0x81,0x80, 0xff,0xff,0x9f,0x8f,0x87,0x83,0x81,0x80, 0xff,0xbf,0x9f,0x8f,0x87,0x83,0x81,0x80, 0xff,0xbf,0x9f,0x8f,0x87,0x83,0x81,0x00,//D7 0xff,0xbf,0x9f,0x8f,0x87,0x83,0x01,0x00, 0xff,0xbf,0x9f,0x8f,0x87,0x03,0x01,0x00, 0xff,0xbf,0x9f,0x8f,0x07,0x03,0x01,0x00, 0xff,0xbf,0x9f,0x0f,0x07,0x03,0x01,0x00, 0xff,0xbf,0x1f,0x0f,0x07,0x03,0x01,0x00, 0xff,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x00, 0x7f,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x00, }; void main() { unsigned char i; unsigned int j; unsigned int counter; bit flag=0; while(1) { i++; i=0x07; //i=0到7 counter++; if(counter==12000) //延時對j++ { if(flag==0) j++; else j--; counter=0; if(j==36 || j==0) { flag=!flag; //決定正向掃描還是逆向掃描 i=0; } } P1=table[j]; //掃描第i列,掃描第j行 } }
注意:用2003時,是高電平點亮LED。要對它取反。
51單片機相關(guān)文章:51單片機教程
評論