单向数码管红绿灯
byte DIGITAL_DISPLAY= { //设置0-9数字所对应数组,共阳数码管“0”为点亮的原则
{ 0,0,0,0,1,0,0,1 },// = 9
{ 0,0,0,0,0,0,0,1 }, // = 8
{ 0,0,0,1,1,1,1,1 }, // = 7
{ 0,1,0,0,0,0,0,1 }, // = 6
{ 0,1,0,0,1,0,0,1 }, // = 5
{ 1,0,0,1,1,0,0,1 }, // = 4
{ 0,0,0,0,1,1,0,1 }, // = 3
{ 0,0,1,0,0,1,0,1 }, // = 2
{ 1,0,0,1,1,1,1,1 },// = 1
{ 0,0,0,0,0,0,1,1 }// = 0
};
int redpin=11;
int yellowpin=12;
int greenpin=13;
void setup() { //设定2~10号数字端口为输出
for(int i=2;i<=13;i++){
pinMode(i, OUTPUT);
}
digitalWrite(10,HIGH);
}
void loop() {
//9~0数码管倒计时的同时点亮红灯
for (int k = 0; k < 10; k++) {
int pin = 2;
for (int s = 0; s < 8; s++)
{
digitalWrite(pin, DIGITAL_DISPLAY);
digitalWrite(redpin,HIGH);
pin++;
}
delay(1000);
digitalWrite(redpin,LOW);
}
//9~0数码管倒计时的同时点亮绿灯
for (int k = 0; k < 10; k++) {
int pin = 2;
for (int s = 0; s < 8; s++)
{
digitalWrite(pin, DIGITAL_DISPLAY);
digitalWrite(greenpin,HIGH);
pin++;
}
delay(1000);
digitalWrite(greenpin,LOW);
}
//黄灯闪烁3秒
digitalWrite(yellowpin,HIGH);
delay(1000);
digitalWrite(yellowpin,LOW);
delay(1000);
digitalWrite(yellowpin,HIGH);
delay(1000);
digitalWrite(yellowpin,LOW);
}
用二进制数来驱动数码管直观且非常简洁,值得推广。不过复制代码没有通过编译,错误指向了两个地方:“digitalWrite(pin, DIGITAL_DISPLAY);”原因是初设的二维数组,但在此时显示的是一维数组,在后面添上即: digitalWrite(pin, DIGITAL_DISPLAY); 把一维数组再变回二维数组后就可通过编译了。
页:
[1]