例:按一下加1
byte seg7Pin[]={2,3,4,5,6,7,8};
byte seg7Table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
byte btnPin = 9 ;
int i,j;
int k=-1;
//boolean state = 0;//一開始沒有人按
boolean buttonUp = 1;//按鈕放開過了
void setup()
{
for(i=0;i<7;i++)
{
pinMode(seg7Pin[i],OUTPUT);
digitalWrite(seg7Pin[i],LOW);
}
pinMode(btnPin, INPUT);
digitalWrite(btnPin, HIGH);
Serial.begin(9600);
}
void outPort(byte data)
{
for(j=0;j<7;j++)
{
if(data % 2 == 1)digitalWrite(seg7Pin[j],HIGH);
else
{
digitalWrite(seg7Pin[j],LOW);
}
data=data/2;
}
}
void loop()
{
//有人按了這顆按鈕 且 按鈕曾經被放開過即切換LED狀態
if(digitalRead(btnPin) == 0 && buttonUp == 1)
{
buttonUp = 0;
k=k+1;
if(k==10)k=0;
Serial.println(k);
outPort(~seg7Table[k]);
}
//有人按了這顆按鈕 且 按鈕被放開過
else if(digitalRead(btnPin) == HIGH && buttonUp == 0)
{
buttonUp = 1;
}
delay(10); // Delay 時間可視情況調整(開關抖動)
}
例:兩個開關加減1
byte seg7Pin[]={2,3,4,5,6,7,8};
byte seg7Table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
byte btnPin1 = 9 ;
byte btnPin2 = 10 ;
int i,j;
int k=-1;
//boolean state = 0;//一開始沒有人按
boolean buttonUp1 = 1;//按鈕放開過了
boolean buttonUp2 = 1;//按鈕放開過了
void setup()
{
for(i=0;i<7;i++)
{
pinMode(seg7Pin[i],OUTPUT);
digitalWrite(seg7Pin[i],LOW);
}
pinMode(btnPin1, INPUT);
pinMode(btnPin2, INPUT);
digitalWrite(btnPin1, HIGH);
digitalWrite(btnPin2, HIGH);
Serial.begin(9600);
}
void outPort(byte data)
{
for(j=0;j<7;j++)
{
if(data % 2 == 1)digitalWrite(seg7Pin[j],HIGH);
else
{
digitalWrite(seg7Pin[j],LOW);
}
data=data/2;
}
}
void loop()
{
//有人按了這顆按鈕 且 按鈕曾經被放開過即切換LED狀態
if(digitalRead(btnPin1) == 0 && buttonUp1 == 1)
{
buttonUp1 = 0;
k=k+1;
if(k==10)k=0;
Serial.println(k);
outPort(~seg7Table[k]);
}
//有人按了這顆按鈕 且 按鈕被放開過
else if(digitalRead(btnPin1) == HIGH && buttonUp1 == 0)
{
buttonUp1 = 1;
}
if(digitalRead(btnPin2) == 0 && buttonUp2 == 1)
{
buttonUp2 = 0;
k=k-1;
if(k<0)k=9;
Serial.println(k);
outPort(~seg7Table[k]);
}
//有人按了這顆按鈕 且 按鈕被放開過
else if(digitalRead(btnPin2) == HIGH && buttonUp2 == 0)
{
buttonUp2 = 1;
}
delay(10); // Delay 時間可視情況調整(開關抖動)
}
沒有留言:
張貼留言