Sketch
/*
pushbuttonをおした回数をカウントする
counter
The circuit:
* +5Vと2番ピンの間にpushbuttonを接続する
* 抵抗10Kを2番ピンとグランドの間に接続する
*
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ButtonStateChange
4回ごとにLEDが点灯する
*/
int buttonPin = 2; // 押しボタン
int ledPin = 13; // 内蔵LED
int buttonPushCounter = 0; // カウンター
int buttonState = 0; // 押しボタンの状態
int lastButtonState = 0; // 前回の押しボタンの状態
void setup() {
// 入力に設定
pinMode(buttonPin, INPUT);
// LEDを出力に設定
pinMode(ledPin, OUTPUT);
// シリアルを設定
Serial.begin(9600);
}
void loop() {
// 押しボタンを読取
buttonState = digitalRead(buttonPin);
// 前回の状態と比較
if (buttonState != lastButtonState) {
//状態が変化していたらカウンター数を加数
if (buttonState == HIGH) {
// 現在の状態がHIGHならif the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
else {
// 現在の状態がLOWならif the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
}
// 次回のために現在の状態を最後の状態と差し替えるsave the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
// 4回ごとにLEDを点灯させるtturns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
0 件のコメント:
コメントを投稿