LoginSignup
37
36

More than 5 years have passed since last update.

pythonでシリアル通信を行う

Posted at

pyserialを使う

シリアル通信を行う場合、pyserialを使うと便利。

  • OSX 10.10.1
  • python2.7

install

まずはpipを使ってpyserialをインストール。

$ pip install pyserial

これだけ。

使い方

送信

インポートして、設定して、出力、最後にクローズ。
非常に簡単。

>>> import serial
>>> ser = serial.Serial('/dev/tty.usbserial-******', 9600, timeout=1)
>>> ser.write("hello")
>>> ser.close()

設定の部分では、第一引数にデバイス名、次にボーレート、次にタイムアウトを指定。
macでデバイス名を調べる場合は、ターミナルで

$ ls /dev/tty.*

と入力してやれば、'/dev/tty.usbserial-*****'と表示されるので確認できる。

受信

read()の引数に、

  • 何も指定しなければ、1文字読み込み
  • 整数(10など)を指定してやれば、指定された文字数分読み込み
  • readline()としてやれば行末端まで読み込み
>>> import serial
>>> ser = serial.Serial('/dev/tty.usbserial-*****', 9600, timeout=1)
>>> c = ser.read()
>>> string = ser.read(10)
>>> line = ser.readline()
>>> ser.close
37
36
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
37
36