前几次做了数码管实验和按键控制LED的实验,通过实验大家已经学会了两种器件的基本用法。这次使用数码管与按键进行组合,做一个简易数字骰子。
数字筛子的基本原理是数码管快速在1-8之间循环跳动,当按下按键时,数码管定格在当前的数字上,不再跳动。
先看一下接线图
ARDUINO 代码复制打印
- //设置控制各段的数字IO脚
- int a=7;
- int b=6;
- int c=5;
- int d=11;
- int e=10;
- int f=8;
- int g=9;
- int dp=4;
- //显示数字1
- void digital_1(void)
- {
- unsigned char j;
- digitalWrite(c,LOW);//给数字5引脚低电平,点亮c段
- digitalWrite(b,LOW);//点亮b段
- for(j=7;j<=11;j++)//熄灭其余段
- digitalWrite(j,HIGH);
- digitalWrite(dp,HIGH);//熄灭小数点DP段
- }
- //显示数字2
- void digital_2(void)
- {
- unsigned char j;
- digitalWrite(b,LOW);
- digitalWrite(a,LOW);
- for(j=9;j<=11;j++)
- digitalWrite(j,LOW);
- digitalWrite(dp,HIGH);
- digitalWrite(c,HIGH);
- digitalWrite(f,HIGH);
- }
- //显示数字3
- void digital_3(void)
- {
- unsigned char j;
- digitalWrite(g,LOW);
- digitalWrite(d,LOW);
- for(j=5;j<=7;j++)
- digitalWrite(j,LOW);
- digitalWrite(dp,HIGH);
- digitalWrite(f,HIGH);
- digitalWrite(e,HIGH);
- }
- //显示数字4
- void digital_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);
- }
- //显示数字5
- void digital_5(void)
- {
- unsigned char j;
- for(j=7;j<=9;j++)
- digitalWrite(j,LOW);
- digitalWrite(c,LOW);
- digitalWrite(d,LOW);
- digitalWrite(dp,HIGH);
- digitalWrite(b,HIGH);
- digitalWrite(e,HIGH);
- }
- //显示数字6
- void digital_6(void)
- {
- unsigned char j;
- for(j=7;j<=11;j++)
- digitalWrite(j,LOW);
- digitalWrite(c,LOW);
- digitalWrite(dp,HIGH);
- digitalWrite(b,HIGH);
- }
- //显示数字7
- void digital_7(void)
- {
- unsigned char j;
- for(j=5;j<=7;j++)
- digitalWrite(j,LOW);
- digitalWrite(dp,HIGH);
- for(j=8;j<=11;j++)
- digitalWrite(j,HIGH);
- }
- //显示数字8
- void digital_8(void)
- {
- unsigned char j;
- for(j=5;j<=11;j++)
- digitalWrite(j,LOW);
- digitalWrite(dp,HIGH);
- }
- void setup()
- {
- int i;
- for(i=4;i<=11;i++)
- {
- pinMode(i,OUTPUT);//设置4~11口为输出模式
- }
- }
- void loop()
- {
- while(1)
- {
- digital_1();//显示数字1
- while(analogRead(0)>1000);//如果读到模拟0口的值1000则说明有按键按下
- delay(100);//延时100ms
- digital_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);
- }
- }
0
|
|
|
|
感觉定义一个数组, 然后写个循环去写high和LOW 简单多了。
|
|
|
|
|