前几次做了数码管实验和按键控制LED的实验,通过实验大家已经学会了两种器件的基本用法。这次使用数码管与按键进行组合,做一个简易数字骰子。数字筛子的基本原理是数码管快速在1-8之间循环跳动,当按下按键时,数码管定格在当前的数字上,不再跳动。先看一下接线图//设置控制各段的数字IO脚inta=7;intb=6;intc=5;intd=11;inte=10;intf=8;intg=9;intdp=4;//显示数字1voiddigital_1(void){unsignedcharj;digitalWrite(c,LOW);//给数字5引脚低电平,点亮c段digitalWrite(b,LOW);//点亮b段for(j=7;j=11;j++)//熄灭其余段digitalWrite(j,HIGH);digitalWrite(dp,HIGH);//熄灭小数点DP段}//显示数字2voiddigital_2(void){unsignedcharj;digitalWrite(b,LOW);digitalWrite(a,LOW);for(j=9;j=11;j++)digitalWrite(j,LOW);digitalWrite(dp,HIGH);digitalWrite(c,HIGH);digitalWrite(f,HIGH);}//显示数字3voiddigital_3(void){unsignedcharj;digitalWrite(g,LOW);digitalWrite(d,LOW);for(j=5;j=7;j++)digitalWrite(j,LOW);digitalWrite(dp,HIGH);digitalWrite(f,HIGH);digitalWrite(e,HIGH);}//显示数字4voiddigital_4(void){digitalWrite(c,LOW);digitalWrite(b,LOW);digitalWrite(f,LOW);digitalWrite(g,LOW);digitalWrite(dp,HIGH);digitalWrite(a,HIGH);digitalWrite(e,HIGH);digitalWrite(d,HIGH);}//显示数字5voiddigital_5(void){unsignedcharj;for(j=7;j=9;j++)digitalWrite(j,LOW);digitalWrite(c,LOW);digitalWrite(d,LOW);digitalWrite(dp,HIGH);digitalWrite(b,HIGH);digitalWrite(e,HIGH);}//显示数字6voiddigital_6(void){unsignedcharj;for(j=7;j=11;j++)digitalWrite(j,LOW);digitalWrite(c,LOW);digitalWrite(dp,HIGH);digitalWrite(b,HIGH);}//显示数字7voiddigital_7(void){unsignedcharj;for(j=5;j=7;j++)digitalWrite(j,LOW);digitalWrite(dp,HIGH);for(j=8;j=11;j++)digitalWrite(j,HIGH);}//显示数字8voiddigital_8(void){unsignedcharj;for(j=5;j=11;j++)digitalWrite(j,LOW);digitalWrite(dp,HIGH);}voidsetup(){inti;for(i=4;i=11;i++){pinMode(i,OUTPUT);//设置4~11口为输出模式}}voidloop(){while(1){digital_1();//显示数字1while(analogRead(0)1000);//如果读到模拟0口的值1000则说明有按键按下delay(100);//延时200msdigital_2();while(analogRead(0)1000);delay(100);digital_3();while(analogRead(0)1000);delay(100);digital_4();while(analogRead(0)1000);delay(100);digital_5();while(analogRead(0)1000);delay(100);digital_6();while(analogRead(0)1000);delay(100);digital_7();while(analogRead(0)1000);delay(100);digital_8();while(analogRead(0)1000);delay(100);}}复制代码