共阳极数码管显示数字程序的进化
arduino引脚的2~8号接数码管刚开始写的时候,很土,没有定义数码管函数,直接在loop里写了一堆
void setup() {
Serial.begin (9600) ;
for (int i = 2 ; i < 9 ; i++)
{ pinMode (i,OUTPUT);
digitalWrite ( i , 1);//通过一个for循环把2到8脚定义成数字输出,并且电平与阳极电平一致
}
}
void loop() {
digitalWrite(2 , 0 );
digitalWrite(3 , 0 );
digitalWrite(4 , 0 );
digitalWrite(5 , 1 );
digitalWrite(6 , 0 );
digitalWrite(7 , 0 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 1 );
digitalWrite(4 , 1 );
digitalWrite(5 , 1 );
digitalWrite(6 , 1 );
digitalWrite(7 , 1 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 1 );
digitalWrite(3 , 0 );
digitalWrite(4 , 0 );
digitalWrite(5 , 0 );
digitalWrite(6 , 1 );
digitalWrite(7 , 0 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 0 );
digitalWrite(4 , 1 );
digitalWrite(5 , 0 );
digitalWrite(6 , 1 );
digitalWrite(7 , 0 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 1 );
digitalWrite(4 , 1 );
digitalWrite(5 , 0 );
digitalWrite(6 , 0 );
digitalWrite(7 , 1 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 0 );
digitalWrite(4 , 1 );
digitalWrite(5 , 0 );
digitalWrite(6 , 0 );
digitalWrite(7 , 0 );
digitalWrite(8 , 1 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 0 );
digitalWrite(4 , 0 );
digitalWrite(5 , 0 );
digitalWrite(6 , 0 );
digitalWrite(7 , 0 );
digitalWrite(8 , 1 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 1 );
digitalWrite(4 , 1 );
digitalWrite(5 , 1 );
digitalWrite(6 , 1 );
digitalWrite(7 , 0 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 0 );
digitalWrite(4 , 0 );
digitalWrite(5 , 0 );
digitalWrite(6 , 0 );
digitalWrite(7 , 0 );
digitalWrite(8 , 0 );
delay (101);
digitalWrite(2 , 0 );
digitalWrite(3 , 0 );
digitalWrite(4 , 1 );
digitalWrite(5 , 0 );
digitalWrite(6 , 0 );
digitalWrite(7 , 0 );
digitalWrite(8 , 0 );
delay (101);
}
这么屎的程序肯定不能忍。
恁不觉得010101很像二进制数吗。
0:0001000 对应十进制数字8
1:0111110 对应十进制数字62
2:0010001 对应十进制数字17
3:0010100 对应十进制数字20
4:0100110 对应十进制数字38
5:0010001 对应十进制数字68
6:1000000 对应十进制数字6*4
7:0011110 对应十进制数字30
8:0000000 对应十进制数字0
9:0000100 对应十进制数字4
这样呢,我们先定义一个数组,数组也可以写到 定义数码管的函数里,这里我们的数组是个全局变量:
int Ten = {8 , 62 , 17 , 20 , 38 , 68 , 64 , 30 , 0 , 4}; //定义从0到9的数码管编码
写一个函数,翻译10进制数和数码管引脚的对应关系:
void NumChange(byte num){//将数码管的数字编码输出到2至8口
int s = 1 ;
for ( int i = 2 ; i < 10 ; i ++)
{
/* int ol = num&s;
if (ol>0)
ol = 1;
else
ol = 0 ; //这一段可有可无,与运算之后,除非当前位是0,否则输出的是正整数,正整数对应digitalWrite是1
Serial.println(ol); */
Serial.print ( num&s ,) ; //在串口调试器打印与运算结果
digitalWrite (i , num&s );
s <<= 1; //左移位操作,准备对下一“位”进行与操作
}
}
上边这段程序的核心思想是调取一个10进制数,把他二进制化,然后让这个二进制数的每一位跟一个二进制数1进行与操作,与出来的0或1就是对应引脚的电平。
这时,loop就可以写的比较简洁了
viod loop()
{
for (i = 0 ; i < 10 ; i ++ )
{
NumChange(Ten);
delay (1000);
}
}
简单明了 最后一段loop里调用的函数写错了应该是 NumChange(Ten [ i ] );
页:
[1]