LoginSignup
153
141

More than 5 years have passed since last update.

Pythonでシリアル通信

Last updated at Posted at 2014-10-06

pySerialを使ったシリアル通信

未だに組み込み系においては何かとお世話になるシリアル通信。最近ではRaspberry Piなどの組み込みようとに使えるLinuxボードが出てきているので、Pythonからシリアル通信が使えると何かと便利です。

Install

PyPiに登録されているのでpipまたはeasy_installを使ってインストール

$ pip install pyserial

or

$ easy_install -U pyserial

使い方

オープンと出力(write)

文字を出力するだけなら至って簡単

>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600)  # デバイス名とボーレートを設定しポートをオープン 
>>> ser.write("hello")      # 出力
>>> ser.close()             # ポートのクローズ

リード

timeoutを簡単に設定できるのでノンブロッキングの形にも簡単にできる

>>> import serial
>>> ser = serial.Serial('/dev/ttyS0', timeout=0.1)  # timeoutを秒で設定(default:None)ボーレートはデフォルトで9600
>>> c = ser.read()  # 1文字読み込み
>>> str = ser.read(10)  # 指定も字数読み込み ただしtimeoutが設定されている婆は読み取れた分だけ
>>> line = ser.readline()  # 行終端'¥n'までリードする
>>> ser.close()

参考

公式ドキュメント
Welcome to pySerial’s documentation

153
141
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
153
141