概要
ラズパイでプログラムを組んでいて、ラジコンを作りました。
ラジコンをゲームのコントローラーでできないか、試している途中で、
「Aボタンはどんな信号なんだ?」と思い、
今回、調べました。
コード
早速、コードです。言語はpythonで書いています。
まずは、各ボタンを調べます。
import pygame
# Pygameの初期化
pygame.init()
# コントローラーの初期化
pygame.joystick.init()
# 最初のジョイスティックを選択
joystick_count = pygame.joystick.get_count()
if joystick_count > 0:
joystick = pygame.joystick.Joystick(0)
joystick.init()
print(f"Detected joystick: {joystick.get_name()}")
else:
print("No joystick detected")
pygame.quit()
exit()
print("Press any button on the controller...")
# イベントループ
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.JOYBUTTONDOWN:
print(f"Button {event.button} pressed")
elif event.type == pygame.JOYBUTTONUP:
print(f"Button {event.button} released")
elif event.type == pygame.QUIT:
running = False
pygame.quit()
上のコードだと、十字キーや左右のジョイスティックが調べなれなかったので、
以下コードで再度調べます。
import pygame
# Pygameの初期化
pygame.init()
# コントローラーの初期化
pygame.joystick.init()
# 最初のジョイスティックを選択
joystick_count = pygame.joystick.get_count()
if joystick_count > 0:
joystick = pygame.joystick.Joystick(0)
joystick.init()
print(f"Detected joystick: {joystick.get_name()}")
else:
print("No joystick detected")
pygame.quit()
exit()
print("Press any button on the controller...")
# イベントループ
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.JOYBUTTONDOWN:
print(f"Button {event.button} pressed")
elif event.type == pygame.JOYBUTTONUP:
print(f"Button {event.button} released")
elif event.type == pygame.QUIT:
running = False
# ハットスイッチの状態を取得
hat = joystick.get_hat(0)
print(f"Hat status: {hat}")
# 左のジョイスティックの軸の状態を取得
left_axis_x = joystick.get_axis(0)
left_axis_y = joystick.get_axis(1)
print(f"Left Stick Axis X: {left_axis_x}, Axis Y: {left_axis_y}")
# 右のジョイスティックの軸の状態を取得
right_axis_x = joystick.get_axis(3) # 右スティックの左右
right_axis_y = joystick.get_axis(4) # 右スティックの上下
print(f"Right Stick Axis X: {right_axis_x}, Axis Y: {right_axis_y}")
pygame.quit()
少し解説します。
ボタンの認識にはイベントがあります。
JOYBUTTONDOWN,JOYBUTTONUP,というのが、各ボタンのイベントです。
JOYHATMOTIONというのが、十字キーのイベントです。
JOYAXISMOTIONというのが、ジョイスティックのイベントになります。
マッピング結果
以下がマッピングした結果となります。
| コントローラーのボタン | 信号 |
| A | 0 |
| B | 1 |
| X | 3 |
| Y | 4 |
| LB | 6 |
| RB | 7 |
| LT | 8 |
| RT | 9 |
| – | 10 |
| + | 11 |
| home | 12 |
| L3(左のジョイスティック) | 13 |
| R3(右のジョイスティック) | 14 |
| P1 | 19 |
| P2 | 23 |
| star | なし |
| profile | なし |
| ↑ | 0,1 |
| ↓ | 0,-1 |
| ← | -1,0 |
| → | 1,0 |
| 左ジョイスティック左右 | get_axis(0) |
| 左ジョイスティック上下 | get_axis(1) |
| 右ジョイスティック左右 | get_axis(3) |
| 右ジョイスティック上下 | get_axis(4) |
まとめ
今まで書いたコードはpygameのライブラリです。他のライブラリだと違うみたいです。注意してください。
何かの参考になれば幸いです。
技術書の購入コストを抑えてスキルアップするなら

ここまで読んでいただきありがとうございます。最後に宣伝をさせてください。
プログラミングの技術書や参考書は、1冊3,000円〜5,000円するものも多く、出費がかさみがちです。Kindle Unlimitedであれば、月額980円で500万冊以上の書籍が読み放題となります。
気になる言語の入門書から、アルゴリズム、基本設計の専門書まで、手元のスマホやPCですぐに参照可能です。現在は「30日間の無料体験」や、対象者限定の「3か月499円プラン」なども実施されています。まずはご自身のアカウントでどのようなオファーが表示されるか確認してみてください。
