0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

パソコンにUSB接続したゲームパッドと、Arduino nanoの通信

0
Last updated at Posted at 2026-07-26

「ゲームパッドの特定のボタン(Aボタンなど)を押している間だけ、Arduino Nanoの内蔵LED(13番ピン)が点灯する」システムを作成します。

Arduino側のプログラム(C++)

gamepad_arduino.cpp
// PCからシリアル通信で指示を受け取り、LEDを制御するプログラム

const int ledPin = 13; // Arduino Nanoの内蔵LEDピン

void setup() {
  // PC側と通信速度(ボーレート)を合わせる
  Serial.begin(9600);
  
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW); // 初期状態は消灯
}

void loop() {
  // PCからデータが送られてきているか確認
  if (Serial.available() > 0) {
    // データを1バイト(1文字)読み取る
    char command = Serial.read(); 

    // 受け取った文字に応じた処理
    if (command == '1') {
      digitalWrite(ledPin, HIGH); // 1を受信したらLEDを点灯
    } else if (command == '0') {
      digitalWrite(ledPin, LOW);  // 0を受信したらLEDを消灯
    }
  }
}

PC側のプログラム(Python)

gamepad_arduino.py
import pygame
import serial
import time

# --- 環境に合わせて書き換える設定 ---
# Arduino IDEの「ツール」メニューで確認できるポート名を指定してください
# Windowsの例: 'COM3', 'COM4' など
# Mac/Linuxの例: '/dev/tty.usbserial-XXXX' など
COM_PORT = 'COM3' 
BAUD_RATE = 9600

# シリアル通信の初期化
try:
    ser = serial.Serial(COM_PORT, BAUD_RATE, timeout=0.1)
    time.sleep(2) # Arduinoの自動リセットからの復帰を待つ
    print("Arduinoと接続しました!")
except serial.SerialException:
    print(f"エラー: {COM_PORT} が開けません。Arduinoが接続されているか確認してください。")
    exit()

# Pygame(ゲームパッド読み取り用)の初期化
pygame.init()
pygame.joystick.init()

if pygame.joystick.get_count() == 0:
    print("エラー: ゲームパッドがPCに接続されていません。")
    ser.close()
    exit()

joystick = pygame.joystick.Joystick(0)
joystick.init()
print(f"{joystick.get_name()}」を検出しました。")
print("ボタン0(通常はAボタンや×ボタン)を押すとArduinoのLEDが光ります。")
print("終了するにはターミナルで Ctrl+C を押してください。")

# 状態の変化を監視するための変数
last_button_state = -1 

try:
    while True:
        pygame.event.pump() # ゲームパッドの状態を更新

        # ボタン0の状態を取得 (押していれば 1, 離していれば 0)
        current_button_state = joystick.get_button(0)

        # ボタンの状態が変化した時だけArduinoにデータを送る
        # (送りすぎによる通信パンクを防ぐため)
        if current_button_state != last_button_state:
            if current_button_state == 1:
                ser.write(b'1') # Arduinoへ '1' を送信
                print("ボタンON -> '1' を送信")
            else:
                ser.write(b'0') # Arduinoへ '0' を送信
                print("ボタンOFF -> '0' を送信")
            
            last_button_state = current_button_state

        time.sleep(0.05) # CPU負荷を下げるためのウェイト

except KeyboardInterrupt:
    print("\nプログラムを終了します。")
finally:
    ser.close()
    pygame.quit()

実行手順
このシステムを動かすには、以下の順番で作業を行います。

1
Arduinoにスケッチを書き込む:Arduino IDEに上記のC++コードを貼り付け、Arduino Nanoに書き込みます。
書き込みが終わったら、Arduino IDEのシリアルモニタは閉じてください
(開いたままだとPython側からポートにアクセスできずエラーになります)。

2
Python環境の準備をする:PCのコマンドプロンプト(またはターミナル)を開き、必要なライブラリをインストールします。
以下のコマンドを実行してください。

pip install pygame pyserial

3
Pythonプログラムを実行する:ポート名の書き換えを忘れずに。
Pythonのコードを gamepad_arduino.py などの名前で保存します。
コード内の COM_PORT = 'COM3' の部分をご自身の環境に合わせて書き換えてから、プログラムを実行します。
ゲームパッドのボタンを押した瞬間に、Arduino Nano基板上の「L」と書かれたLEDが光れば成功です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?