byte ledPin1 = 2 ;
byte ledPin2 = 3;
byte btnPin = 4 ;
int k=-1;
//boolean state = 0;//一開始沒有人按
boolean buttonUp = 1;//按鈕放開過了
void setup()
{
pinMode(ledPin1, OUTPUT);
digitalWrite(ledPin1, 0);
pinMode(ledPin2, OUTPUT);
digitalWrite(ledPin2, 0);
pinMode(btnPin, INPUT);
digitalWrite(btnPin, HIGH);
Serial.begin(9600);
}
void loop()
{
//有人按了這顆按鈕 且 按鈕曾經被放開過即切換LED狀態
if(digitalRead(btnPin) == 0 && buttonUp == 1)
{
buttonUp = 0;
k=k+1;
if(k==2)k=0;
if(k==0)
{
digitalWrite(ledPin1, 1);
digitalWrite(ledPin2, 0);
}
if(k==1)
{
digitalWrite(ledPin1, 0);
digitalWrite(ledPin2, 1);
}
Serial.println(k);
}
//有人按了這顆按鈕 且 按鈕被放開過
else if(digitalRead(btnPin) == HIGH && buttonUp == 0)
{
buttonUp = 1;
}
delay(10); // Delay 時間可視情況調整(開關抖動)
}
byte ledPin[] = { 9, 8, 7, 6, 5, 4,3,2};
int ad1[] = {0x81,0x42,0x24,0x18,0x24,0x42,0x81,0x00 };
int ad2[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x00};
int ad3[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01,0x00};
byte btnPin = 10 ;
int k=-1;
int delaytime = 1000; // 延遲時間預設為 100 ms
int i,j; // for迴圈的計數變數
boolean buttonUp = 1;//按鈕放開過了
void setup()
{
for (i=0; i<8; i++)
{
pinMode(ledPin[i], OUTPUT);
digitalWrite(ledPin[i], LOW);
}
pinMode(btnPin, INPUT);
digitalWrite(btnPin, HIGH);
Serial.begin(9600);
}
void OutPort(byte dat)
{
for (j=7; j>=0; j--)
{
if (dat % 2==1) // 除 2 的餘數代表要取出 dat 的最低位元狀態
digitalWrite(ledPin[j], HIGH); // LED off
else
digitalWrite(ledPin[j], LOW); // LED on
dat=dat >> 1; // dat 右移一個位元, 繼續偵測其它位元狀態
}
}
void loop()
{
//有人按了這顆按鈕 且 按鈕曾經被放開過即切換LED狀態
if(digitalRead(btnPin) == 0 && buttonUp == 1)
{
buttonUp = 0;
k=k+1;
if(k>2)k=0;
Serial.println(k);
if(k==0)
{
for (i=0; i<8; i++)
{
OutPort(ad1[i]);
delay(delaytime); // wait for a second
}
}
if(k==1)
{
for (i=0; i<9; i++)
{
OutPort(ad2[i]);
delay(delaytime); // wait for a second
}
}
if(k==2)
{
for (i=0; i<9; i++)
{ OutPort(ad3[i]);
delay(delaytime); // wait for a second
}
}
}
//有人按了這顆按鈕 且 按鈕被放開過
else if(digitalRead(btnPin) == 1 && buttonUp == 0)
{
buttonUp = 1;
}
delay(10); // Delay 時間可視情況調整(開關抖動)
}
沒有留言:
張貼留言