本文為大家?guī)砦宸N51單片機(jī)流水燈的實(shí)現(xiàn)方法。
51單片機(jī)流水燈原理
下圖為主控芯片和流水燈模塊的原理圖。流水燈模塊接在單片機(jī)的P1口,由原理圖可以知道,在P1口給一個(gè)低電平即可點(diǎn)亮LED燈。相反,如果要LED燈熄滅,就要把P1口的電平變?yōu)楦唠娖郊纯?。要?shí)現(xiàn)流水燈功能,我們只要將LED1~LED8依次點(diǎn)亮、熄滅,依始類推,8只LED變會一亮一暗的做流水燈了。
實(shí)現(xiàn)8個(gè)LED流水燈程序用中文表示為:P1.0低、延時(shí)、P1.0高、P1.1低、延時(shí)、P1.1高、P1.2低、延時(shí)、P1.2高、P1.3低、延時(shí)、P1.3高、P1.4低、延時(shí)、P1.4高、P1.5低、延時(shí)、P1.5高、P1.6低、延時(shí)、P1.6高、P1.7低、延時(shí)、P1.7高、返回到開始、程序結(jié)束。
1、通過改變賦值實(shí)現(xiàn)流水燈
void main()
{ while(1) {
P2=0xfe;
delay1ms(500); P2=0xfd; delay1ms(500); P2=0xfb;
delay1ms(500); P2=0xf7; delay1ms(500); P2=0xef; delay1ms(500); P2=0xdf;
delay1ms(500); P2=0xbf; delay1ms(500); P2=0x7f;
delay1ms(500); } }
2、通過公式運(yùn)算實(shí)現(xiàn)流水燈
void main() {
while(1) {
uinta,b=1; P2=0xfe; delayms(500); for(a=0;a<7;a++)
P2-=b; // P2=P2-b delayms(500); b=b*2; //都化為同一類型進(jìn)制運(yùn)算 } } }
3、通過操作符<<與“|”實(shí)現(xiàn)流水燈 (通過移位實(shí)現(xiàn)流水燈)
void main() {
uchara,i;
while(1) {
a=0xfe; //點(diǎn)亮第一位LED燈 for(i=0;i<8;i++)
{ P2=a;
a=a<<1; //左移一位
a=a|0x01; //左移一位后與0x01相或,保證左移后最低位為1 delay_ms(500); } } }
4、通過庫函數(shù)_crol_(字符左移)實(shí)現(xiàn)流水燈
void main()
{
uint a; a=0xfe; while(1) {
P2=a;a=_crol_(a,1); delay_ms(500); } }
5、采用數(shù)組實(shí)現(xiàn)流水燈
uchar code table[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
void main(void) {
uchari;
while (1) {
for(i=0;i<8;i++) //循環(huán)點(diǎn)亮8只LED燈 {
P2=table[i];
delay_ms(500); //延時(shí)500毫秒 } } }
評論