ジョイスティックを使ってみます。中央の金属棒にゴムキャップを付けて使います。これでサーボモータを制御します。
5本のピンは左から GND、5V電源、X軸信号、Y軸信号、スイッチ です。Y軸とX軸の信号はアナログ入力のA0、A1ピンに、スイッチは7番ピンに接続しました。プログラムはネットからサンプルを探してきて、とりあえず動かしてみます。
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 |
#define SW 7 //ジョイスティックのスイッチは7番ピン #define Y A0 //ジョイスティックのY軸 #define X A1 //ジョイスティックのX軸 int switch_state = 0; int x_pos = 500; int y_pos = 500; void setup() { Serial.begin(9600); pinMode(X, INPUT); pinMode(Y, INPUT); pinMode(SW, INPUT_PULLUP); } void loop() { switch_state = digitalRead(SW); x_pos = analogRead(X); y_pos = analogRead(Y); Serial.print("Switch: "); Serial.print(switch_state); Serial.print(" X: "); Serial.print(x_pos); Serial.print(" Y: "); Serial.println(y_pos); delay(300); } |
シリアルモニタでどのような値が読めているか確認します。
どうやらX軸の信号は0~1000の範囲で読めているようです。これをサーボモータの角度に変換すれば良さそうです。接続はこのようになりました。ブレッドボードを使っています。
最終的にプログラムはこうなりました。
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 31 32 33 34 35 36 37 38 39 40 41 |
#include <Servo.h> #define SERVO 8 //サーボモータの制御信号は8番ピン #define SW 7 //ジョイスティックのスイッチは7番ピン #define Y A0 //ジョイスティックのY軸 #define X A1 //ジョイスティックのX軸 Servo myservo; int switch_state = 0; int x_pos = 500; int y_pos = 500; void setup() { Serial.begin(9600); pinMode(X, INPUT); pinMode(Y, INPUT); pinMode(SW, INPUT_PULLUP); myservo.attach(SERVO); } void loop() { switch_state = digitalRead(SW); x_pos = analogRead(X); y_pos = analogRead(Y); //ジョイスティックの変化範囲(0~1000)を角度に変換 int rot = ((long)x_pos*180)/1000; Serial.print("Switch: "); Serial.print(switch_state); Serial.print(" X: "); Serial.print(x_pos); Serial.print(" Y: "); Serial.print(y_pos); Serial.print(" Rotation: "); Serial.println(rot); myservo.write(rot); delay(50); } |
動きました。
コメント