arduinoとジョイスティックを使ったマウス作り(windows)
Google earthでフライトシミュレーターが無料できると知ったのでやってみました。
実際の動き
youtube このようなことが、マウスの代わりにジョイスティックでできるようになります。
経緯
Google earth のフライトシミュレーターをジョイスティックでやりたかったからです。 少しでも、操縦している雰囲気を味わってみたかったのでwww。
開発環境づくり
Google earth pro のダウンロードページはこちら
今回はArduinoとPythonを使います。 Python環境がない場合はこちらからダウンロ-ドしてください。 こちらhttps://www.python.org/ Python3をダウンロードしてください。 僕は、Python3.10をダウンロードしました。
コマンドプロンプトにコマンドを打ちます。 まず、自分のPythonのある場所のファイルのパスをコピーします。 そしてこのように打っていきます。
cd パスのコピー ここはcdとパスの間に半角でスペースを入れます。
py –m pip install –-upgrade pip
py –m pip install mouse
py -m pip install pyserial この時にPython2をダウンロードしてある場合はうまくいかない場合があります。 コマンドプロンプトに書くのはここで終わりです。
配線
このように配線します。 配線はここで終わりです。
プログラム
//////////////////////////////// // Joystick controlled mouse/// /// by Shubham Santosh//////// ///////////////////////////// void setup() { Serial.begin(9600); pinMode(9,INPUT); // SW pin digitalWrite(9,HIGH); } int prev_state=0; // previous state of switch void loop() { int z=0,xpos=0,ypos=0; int x=analogRead(A0); int y=analogRead(A1); int sensitivity=10; // you can adjust the sensitivity based on your comfort if(x>=550) // when moved up xpos=map(x,550,1023,0,sensitivity); if(x<=450) // when moved down xpos=map(x,450,0,0,-sensitivity); if(y>=550) // when moved right ypos=map(y,550,1023,0,sensitivity); if(y<=450) // when moved left ypos=map(y,450,0,0,-sensitivity); int curr_state=digitalRead(9); if(curr_state==1 && prev_state==0) // when SW is pressed z=1; else z=0; if(xpos!=0 or ypos!=0 or z==1) // prints only when the joystick is moved { Serial.print(xpos); // print the data and separating by ":" Serial.print(":"); Serial.print(ypos); Serial.print(":"); Serial.println(z); } prev_state=curr_state; delay(10); // for normal operation }
import mouse, sys import time import serial mouse.FAILSAFE=False ArduinoSerial=serial.Serial('com7',9600) #Specify the correct COM port time.sleep(1) #delay of 1 second while 1: data=str(ArduinoSerial.readline().decode('ascii')) #read the data (x,y,z)=data.split(":") # assigns to x,y and z (X,Y)=mouse.get_position() #read the cursor's current position (x,y)=(int(x),int(y)) #convert to int mouse.move(X+x,Y-y) #move cursor to desired position if '1' in z: # read the Status of SW mouse.click(button="left") # clicks left button
PythonはIDLEというものを使用してください。 上から6段目にcom7とありますがarduinoが刺さっているポートなので 各自で変えて下さい。 これはデバイスマネージャーから確認できます。 そしてRUNを押すと動くはずです。
苦労したところ
最初、Arduino Unoだけあれば簡単にできると思って作り始めたのですが、 Arduino LeonardoやArduino MegaじゃないとPythonやJavaを使わないとできないことを知って、いろいろ方法を探しました。 初めてPythonを使ったし、日本語のサイトが余りなかったので、メモとして作り方をのせてみました。 バージョンのせいで動かないことがあるので、気をつけたいと思いました。 (これは、CoderDojoのメンターさんに相談して、問題点を見つけてもらいました。) ファイル名とモジュールが同じだと動かないので名前に気をつけたいです。
材料
Arduino uno
USBケーブル
Joystick
ジャンパーコード
参考にしたサイト
https://create.arduino.cc/projecthub/shubhamsantosh99/joystick-controlled-mouse-af2939
お試し
試し書き。
確認です
表示