arduino 按键控制数码管显示
按键控制数码管显示 0-9;
代码
int pin_a = 8;//定义数码管每段引脚
int pin_b = 7;
int pin_c = 6;
int pin_d = 5;
int pin_e = 4;
int pin_f = 3;
int pin_g = 2;
int key = 13; //定义按键
int num=0;
int numTable[10][8] = { //共阳极
{0,0,0,0,0,0,1,1},// 0
{1,0,0,1,1,1,1,1},// 1
{0,0,1,0,0,1,0,1},// 2
{0,0,0,0,1,1,0,1},// 3
{1,0,0,1,1,0,0,1},// 4
{0,1,0,0,1,0,0,1},// 5
{0,1,0,0,0,0,0,1},// 6
{0,0,0,1,1,1,1,1},// 7
{0,0,0,0,0,0,0,1},// 8
{0,0,0,0,1,0,0,1},// 9
};
int Key_Number(void)
{
if(digitalRead(key)==0)//判断按键是否按下
{
delay(20); //消抖
if(digitalRead(key)==0)// 再次判断按键是否按下
{
num++; // num+1
if(num>=10) num=0; //
while(digitalRead(key)==0); //当按键按下没有松手时
}
}
return num; // 返回要显示的数字
}
void display(int n)//数码管显示,n表示显示的数字
{
digitalWrite(pin_a,numTable[n][0]);
digitalWrite(pin_b,numTable[n][1]);
digitalWrite(pin_c,numTable[n][2]);
digitalWrite(pin_d,numTable[n][3]);
digitalWrite(pin_e,numTable[n][4]);
digitalWrite(pin_f,numTable[n][5]);
digitalWrite(pin_g,numTable[n][6]);
}
void setup() {
pinMode(pin_a,OUTPUT); //引脚设置为输出模式
pinMode(pin_b,OUTPUT);
pinMode(pin_c,OUTPUT);
pinMode(pin_d,OUTPUT);
pinMode(pin_e,OUTPUT);
pinMode(pin_f,OUTPUT);
pinMode(pin_g,OUTPUT);
pinMode(key,INPUT); //引脚设置为输入模式
}
void loop() {
display(num); // 显示数字
Key_Number(); //显示下一个数值的函数
}