Arduino基礎 02-Button-
今回はボタンを使ったプログラムです。
”スケッチ例/02.Digital/Button”を開いてみましょう
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// constants won't change. They're used here to // set pin numbers: const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin // variables will change: int buttonState = 0; // variable for reading the pushbutton status void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } void loop(){ // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, HIGH); } else { // turn LED off: digitalWrite(ledPin, LOW); } } |
こちらのスケッチはArduinoのdigitalピンの2番に接続したボタンを押す事によって、13番ピンのLEDが点灯するというプログラムです。
ボタンを押している間はLEDは光り続け、ボタンを話すとLEDは消灯します。それでは中のプログラムを確認してみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
const int buttonPin = 2; // ”buttonPin”という文字列に”2”を設定 const int ledPin = 13; // ”ledPin”という文字列に”13”を設定 int buttonState = 0; // ”buttonState”という文字列に”0”を設定。今のボタンの状態を記録するための定義です。 void setup() { // ”ledPin”を”OUTPUT”に設定します pinMode(ledPin, OUTPUT); // ”buttonPin”を”INPUT”に設定します。 pinMode(buttonPin, INPUT); } void loop(){ // ”buttonState”に”buttonPin”の値を格納します。 buttonState = digitalRead(buttonPin); // 「if(◎◎==○○){〜」 は、「もし◎◎が○○と等しかったら〜する」という意味の制御文です。今回は”buttonState”が”HIGH”だったら”ledPin”の値を”HIGH”にするというものです if (buttonState == HIGH) { digitalWrite(ledPin, HIGH); } // 「else」は前述のifの内容以外の場合を定義します。今回はボダンが押されていない状態のときに”ledPin”を”LOW”にするというものですね else { digitalWrite(ledPin, LOW); } } |
いかがでしょうか?なんとなくわかりましたか?
このプログラムを使うことで、いろんなものをインタラクティブに光らせることが出来るようになります。
例えば、靴の底に仕込めば、歩くたびにピカピカ光る靴が作れるかもしれません。
手袋の甲に仕込めば、パンチするたびに光る閃光グローブが完成するかも!