Arduino-mouse-button-control

提供:Dev Guides
移動先:案内検索

Arduino-マウスボタンコントロール

マウスライブラリを使用すると、Arduino Leonardo、Micro、またはDueを使用してコンピューターの画面上のカーソルを制御できます。

この特定の例では、5つのプッシュボタンを使用して画面上のカーソルを移動します。 4つのボタンは方向(上、下、左、右)で、1つはマウスの左クリック用です。 Arduinoからのカーソルの動きは常に相対的です。 入力が読み取られるたびに、カーソルの位置は現在の位置に対して相対的に更新されます。

方向ボタンの1つが押されるたびに、Arduinoはマウスを動かし、HIGH入力を適切な方向の5の範囲にマッピングします。

5番目のボタンは、マウスの左クリックを制御するためのものです。 ボタンを離すと、コンピューターはイベントを認識します。

必要なコンポーネント

次のコンポーネントが必要になります-

  • 1×ブレッドボード
  • 1×Arduino Leonardo、MicroまたはDueボード
  • 5×10kオーム抵抗
  • 5×瞬間押しボタン

手順

以下の画像に示すように、回路図に従って、ブレッドボード上のコンポーネントを接続します。

マウスボタンブレッドボード

スケッチ

コンピューターでArduino IDEソフトウェアを開きます。 Arduino言語でコーディングすると、回路が制御されます。 [新規]をクリックして、新しいスケッチファイルを開きます。

この例では、Arduino IDE 1.6.7を使用する必要があります

スケッチ

Arduinoコード

/*
   Button Mouse Control
   For Leonardo and Due boards only .Controls the mouse from
   five pushbuttons on an Arduino Leonardo, Micro or Due.
   Hardware:
   * 5 pushbuttons attached to D2, D3, D4, D5, D6
   The mouse movement is always relative. This sketch reads
   four pushbuttons, and uses them to set the movement of the mouse.
   WARNING: When you use the Mouse.move() command, the Arduino takes
   over your mouse! Make sure you have control before you use the mouse commands.
*/

#include "Mouse.h"
//set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;
int range = 5;//output range of X or Y movement; affects movement speed
int responseDelay = 10;//response delay of the mouse, in ms

void setup() {
  //initialize the buttons' inputs:
   pinMode(upButton, INPUT);
   pinMode(downButton, INPUT);
   pinMode(leftButton, INPUT);
   pinMode(rightButton, INPUT);
   pinMode(mouseButton, INPUT);
  //initialize mouse control:
   Mouse.begin();
}

void loop() {
  //read the buttons:
   int upState = digitalRead(upButton);
   int downState = digitalRead(downButton);
   int rightState = digitalRead(rightButton);
   int leftState = digitalRead(leftButton);
   int clickState = digitalRead(mouseButton);
  //calculate the movement distance based on the button states:
   int xDistance = (leftState - rightState) *range;
   int yDistance = (upState - downState)* range;
  //if X or Y is non-zero, move:
   if ((xDistance != 0) || (yDistance != 0)) {
      Mouse.move(xDistance, yDistance, 0);
   }

  //if the mouse button is pressed:
   if (clickState == HIGH) {
     //if the mouse is not pressed, press it:
      if (!Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.press(MOUSE_LEFT);
      }
   } else {                          //else the mouse button is not pressed:
     //if the mouse is pressed, release it:
      if (Mouse.isPressed(MOUSE_LEFT)) {
         Mouse.release(MOUSE_LEFT);
      }
   }
  //a delay so the mouse does not move too fast:
   delay(responseDelay);
}

注意すべきコード

マイクロUSBケーブルでボードをコンピューターに接続します。 ボタンは、ピン2〜6のデジタル入力に接続されます。 必ず10kプルダウン抵抗を使用してください。