LoginSignup
5
3

More than 1 year has passed since last update.

Raspberry Pi Pico (micropython) と PC の Python 間をUSB 1本で通信する

Posted at

 通信といっても Thonny の下の Shell みたいなモノがそのまま動けばいいんじゃい!という感覚で色々調べたものの、みんな UART 変換なりを使っていたり、USB 周りに手を出すと mbed OS と干渉して死ぬみたいな記事を見てなんとか使えないものかと試行錯誤した軌跡

概要

  • プログラム用のUSBだけで通信する
  • 書き込み読み取り量に比例するが大体1500Hz〜2300Hzくらい

こんな人に

  • ラズピコ本体と PC と繋ぐ USB ケーブルしかない
  • わざわざ UART-USB 変換を買いたくない
  • ファームウェアやOS等の深い部分を触って壊したくない
  • とりあえず動けばいい

非対象者

  • ちゃんと通信したい方
  • より適切な方法を知ってる方(教えてください)

環境

  • Thonny 4.0.1 (Windows 10 / macOS Ventura)
  • Python 3.9
    • pyserial 3.5

Raspberry Pi Pico 側のコード

main.py

while True:
    s = input()
    print(s)

PC側のコード

test.py

import serial
from tqdm import tqdm

PORT = 'COM*'  # Windows の場合
PORT = '/dev/cu.usbmodem*'  # Mac の場合
BAUD = 115200

ser = serial.Serial(
    port=PORT,
    baudrate=BAUD,
    timeout=1,
    write_timeout=1,
    exclusive=True,
)

N = 30000

for i in tqdm(range(N)):
    send_bytes = bytes('{:06d}\r\n'.format(i), 'utf-8')

    ser.write(send_bytes)
    ser.flush()

    receive_bytes = ser.read_all()
    receive = receive_bytes.decode('utf-8').splitlines()

    if not len(receive) > 1:
        continue

    # print('send: {:06d} recv: {}'.format(i, receive[1]))

実行結果

% python test.py
100%|███████████████| 30000/30000 [00:12<00:00, 2337.89it/s]

ハマったポイント

  • ser.readline() だと書き込みありで回した場合にゴミが溜まるのか write_timeout で落ちてしまった

    • Mac だと動くっぽい(環境による?)
  • ser.read_all() すると前後にいろいろ入る

  • Thonny を閉じてリセットする儀式

5
3
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
5
3