がちもとさんのブログ

co-founder #KumaMCN / @KnowComInc R&D戦略チーム / #Azure #HoloLens #MRPP / #AWS #ML / #CV #SLAM #Python / #WHILL #自動運転 / #メタバース #XR / #Databricks / お仕事のご依頼はDMで✉️

WHILLをJoyConで操作する(Python、Windows)

アドベントカレンダー2019の2日目の記事です。

WHILLをJoyConで動かしてみました。 https://www.instagram.com/p/Bwr5mk3ninW/?igshid=167dycnuhsrv1

システム環境

  • WHILL Model CR
  • RS232C-USBケーブル
  • Windows10
  • Python 3.6

ライブラリのインストール

  • pip install pyserial
  • pip install pygame

ソースコード

from whill import ComWHILL
import pygame
from pygame.locals import *
import time

def main() :
    whill = ComWHILL(port='COM21')
    pygame.joystick.init()
    joystick0 = pygame.joystick.Joystick(0)
    joystick0.init()

    print ('joystick start')

    pygame.init()

    x, y = 0, 0
    while True:
         # コントローラーの操作を取得
        eventlist = pygame.event.get()

        # イベント処理
        for e in eventlist:
            if e.type == QUIT:
                return

            if e.type == pygame.locals.JOYAXISMOTION:
                x, y = joystick0.get_axis(0), joystick0.get_axis(1)
                print ('axis x:' + str(x) + ' axis y:' + str(y))
            elif e.type == pygame.locals.JOYHATMOTION:
                x, y = joystick0.get_hat(0)
                print ('hat x:' + str(x) + ' hat y:' + str(y))
            elif e.type == pygame.locals.JOYBUTTONDOWN:
                print ('button:' + str(e.button))

        whill.send_joystick(int(x*50), int(-y*50))
        time.sleep(0.01)

if __name__ == '__main__':
    try:
        main()
    except pygame.error:
        print ('joystickが見つかりませんでした。')
  1. ライブラリをインポート (WHILL用、JoyCon用、Sleep用)

  2. WhillとJoyConの初期設定

  3. JoyConの値を取得 x,y

  4. WHILLに指令 whill.send_joystick(int(x50), int(-y50))の50という値を変更して速度を調整、屋内では50だと速いので小スペースだと20くらいでOK

まとめ

JoyConがあるだけで、子どもたちが寄ってきます。ゲーム感覚でWHILLを操作できるの楽しい!

参考

Mac版はこちら。ライブラリに公式のpywhillではなく、whillpyを用います。 qiita.com