元高専生のロボット作り

元高専生のロボット作り

主にプログラミング, 電子系について書きます。たまに機械系もやります。メモ代わりの記事ばっか書きます

jetson nano pygameでジョイスティックの読み取りを行う

まず、jetson nanoにpygameをいれようとしたのですが、
いきなりpip3 install pygameではうまくいきませんでした。
sudo apt install python-pygameでもだめでした。

以下の記事の通り行うとちゃんとインストールできました。

qiita.com


また、今回はjetsonをssh接続して動かしているため、ターミナルを開くことができません。

ssh接続経由で実行すると以下のようなエラーがでる。

  File "joy_test.py", line 18, in joy_demo
    for e in pygame.event.get():
pygame.error: video system not initialized

この場合はDummyVideoDriverというのを使えばよくて、以下に書いてあります。
DummyVideoDriver - pygame wiki


以下が動作確認用のコードです。

import pygame
from pygame.locals import *
import os

# ssh接続だとディスプレイが開けないので
# DummyVideoDriverを使用する
os.environ["SDL_VIDEODRIVER"] = "dummy"

def joy_demo():
    pygame.init()
    pygame.joystick.init()
    joys = pygame.joystick.Joystick(0)
    joys.init()
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

    while True:
        for e in pygame.event.get():
            if e.type == pygame.locals.JOYAXISMOTION:
                print(joystick.get_axis(0), joystick.get_axis(1), joystick.get_axis(2), joystick.get_axis(3))
            elif e.type == pygame.locals.JOYBUTTONDOWN:
                print('buttin: ' + str(e.button) + ' pushed')
            elif e.type == pygame.locals.JOYBUTTONUP:
                print('button: ' + str(e.button) + ' released')

if __name__ == '__main__':
    try:
        joy_demo()
    except KeyboardInterrupt:
        print("終了")