久々のブログ更新。
ラズパイ上でゲームパッドの情報を取得してみたくなったので、その記録です。
環境
ハード: Raspberry Pi 3 model B、F710ワイヤレス ゲームパッド
OS: Raspberry Pi OS (32bit)
動作確認
まず必要なパッケージをインストール(初回のみ)
$ sudo apt install joystick jstest-gtk
次にゲームパッドの接続確認。
とりあえずデバイスが表示されれば接続OK。
$ ls -l /dev/input/js0 crw-rw----+ 1 root input 13, 0 Dec 14 20:28 /dev/input/js0
CUIでテスト
$ jstest /dev/input/js0
GUIでテスト。画面表示が必要になるけど、わかりやすい。
$ jstest-gtk
pythonで情報取得
ゲームパッドを扱う好みのサンプルプログラムがなかったので、こちらのページを参考に作成。 画面表示をしていないラズパイだと、ダミーのディスプレイドライバを設定してあげないと動作しなかった。
import pygame
import os
import sys
from pygame.locals import *
os.environ["SDL_VIDEODRIVER"] = "dummy"
pygame.init()
pygame.joystick.init()
joy = pygame.joystick.Joystick(0)
joy.init()
print('NAME:', joy.get_name())
print('NUM AXES:', joy.get_numaxes())
print('NUM BUTTONS:', joy.get_numbuttons())
print('NUM HATS:', joy.get_numhats())
print('NUM BALLS:', joy.get_numballs())
while True:
pygame.time.wait(30)
for e in pygame.event.get():
if e.type == pygame.locals.JOYAXISMOTION or e.type == pygame.locals.JOYHATMOTION:
axes_data = {
"L": (round(joy.get_axis(0), 3), round(joy.get_axis(1), 3)),
"R": (round(joy.get_axis(3), 3), round(joy.get_axis(4), 3)),
"LT": round(joy.get_axis(2), 3),
"RT": round(joy.get_axis(5), 3),
"HAT": (joy.get_hat(0)[0], joy.get_hat(0)[1]),
}
print(axes_data)
elif e.type == pygame.locals.JOYBUTTONDOWN or e.type == pygame.locals.JOYBUTTONUP:
if e.type == pygame.locals.JOYBUTTONDOWN:
print('BUTTON %d DOWN' % e.button)
elif e.type == pygame.locals.JOYBUTTONUP:
print('BUTTON %d UP ' % e.button)
buttons_data = {
"A": joy.get_button(0),
"B": joy.get_button(1),
"X": joy.get_button(2),
"Y": joy.get_button(3),
"LB": joy.get_button(4),
"RB": joy.get_button(5),
"BACK": joy.get_button(6),
"START": joy.get_button(7),
"AXIS_L": joy.get_button(8),
"AXIS_R": joy.get_button(9),
}
print(buttons_data)
