編集履歴一覧に戻る
LEGOTAROのアイコン画像

LEGOTARO が 2021年02月21日15時38分27秒 に編集

初版

タイトルの変更

+

arduinoとジョイスティックを使ったマウス作り(windows)

タグの変更

+

joystick

+

Arduino_Uno

本文の変更

+

syouwa_taroさんの作品を見てGoogle earthでフライトシミュレーターができると知ったのでやってみました。 #### 実際の動き @[youtube](https://youtu.be/88PWPiDuSsE) このようなことができるようになります。 #### 経緯 Google earth のフライトシミュレーターをジョイスティックでやりたかったからです。 #### 開発環境づくり ちなみに今回はarduinoとpythonを使います。 python環境がない場合はこちらからダウンロ-ドしてください。 こちらhttps://www.python.org/ python3をダウンロードしてください。 僕は、python3.10をダウンロードしました。 コマンドプロンプトにコマンドを打ちます。 まず、自分のpythonのある場所のファイルのパスをコピーします。 そしてこのように打っていきます。 1. cd パスのコピー ここはcdとパスの間に半角でスペースを入れます。 2. py –m pip install –-upgrade pip 3. py –m pip install mouse 4. py -m pip install pyserial この時にpython2をダウンロードしてある場合はうまくいかない場合があります。 コマンドプロンプトに書くのはここで終わりです。 #### 配線 このように配線します。 ![配線](https://cdn.discordapp.com/attachments/800481502923325451/812931004712484865/mouse.png) 配線はここで終わりです。 #### プログラム arduino ```arduino //////////////////////////////// // 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 } ``` python ```python 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を押すと動くはずです。 ###苦労したところ バージョンのせいで動かないことがあります。 ファイル名とモジュールが同じだと動かないのでjoystickなどの名前にしましょう。 ####材料 arduino uno USBケーブル joystick ジャンパーコード #### 参考にしたサイト https://create.arduino.cc/projecthub/shubhamsantosh99/joystick-controlled-mouse-af2939