LoginSignup
10
17

More than 5 years have passed since last update.

Raspberry Piでシリアル通信試してみた

Posted at

目的

Raspberry PiとSTM32をシリアル通信で接続して、Raspberry Pi上で動作させたROSからSTM32を制御したい。
まずはPythonからシリアル通信を試してみる。

シリアル通信を使ってみる

環境

Raspberry Pi3 model B
Raspbian Stretch (2018-11-13)

USBシリアルで

とりあえずUSBシリアルで試そう。(別にPCでもできる)
http://akizukidenshi.com/catalog/g/gM-08461/
これをラズパイのUSBポートにさして、TX/RXを直結しておく。

USBシリアルがどれか確認する。

pi@raspberrypi:~/work/python $ ls -l /dev/ttyUSB*
crw-rw---- 1 root dialout 188, 0 Jan 27 03:02 /dev/ttyUSB0

忘れずにシリアルのアクセス権限を追加

$ sudo usermod -a -G dialout $USER

まずはPythonからシリアルアクセスしてみる。

$ pip install pyserial

で、モジュールをインストールして

testser.py
import serial
import time
import threading
import Queue

class SerCom:
    def __init__(self, tty, baud='115200'):
        self.ser = serial.Serial(tty, baud, timeout=0.1)
        self.queue = Queue.Queue()

        self.event = threading.Event()
        self.thread_r = threading.Thread(target=self.recv_)
        self.thread_r.start()

    def recv_(self):
        while not self.event.is_set():
             line = self.ser.readline()
             if len(line) > 0:
                 print(line)
                 self.queue.put(line)

    def send(self, data):
        self.ser.write(data)

    def stop(self):
        self.event.set()
        self.thread_r.join()

ser = SerCom('/dev/ttyUSB0', '115200')
ser.send('test')
time.sleep(2)
ser.stop()

こんな感じのお試しプログラムを書いて、実行してみる

pi@raspberrypi:~/work/python $ python testser.py
test

testが表示されればOK
TX/RXの線を外すと、何も表示されないはず。

今度はラズパイ本体のシリアルを試す

こちらの回答を参考に、シリアルを有効にする(しなくてもいいのかもしれなが、試してない)
https://raspberrypi.stackexchange.com/questions/45570/how-do-i-make-serial-work-on-the-raspberry-pi3-pi3b-pizerow

たぶん、これがピンヘッダに出ているUART

pi@raspberrypi:~ $ ls -l /dev/ttyS*
crw-rw---- 1 root dialout 4, 64 Jan 27 03:17 /dev/ttyS0

ピンヘッダの8pinがTX、10pinがRXのようなので、またこの間をショートしておく。
testser.pyのSerCom('/dev/ttyUSB0', '115200')SerCom('/dev/ttyS0', '115200')に書き換える。
試して、testが表示されればOK。

pi@raspberrypi:~/work/python $ python testser.py
test
10
17
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
10
17