LoginSignup
18
16

More than 1 year has passed since last update.

Raspberry PiでUARTの有効化+シリアル通信

Last updated at Posted at 2020-02-03

Raspberry Piでシリアル通信を使う機会があったので、疎通までのやり方を備忘録として載せておきます。

環境

  • Raspberry Pi 3 Model B+
  • Raspbian Buster
  • Python 2.7.16

Raspberry Piのセットアップ

デフォルトだとRaspberry Piはシリアルポートが無効になっているので、設定を変更します。
LXTerminalを開き、コマンドを入力します。

pi@raspberrypi:~ $ sudo raspi-config

次のような画面になるので、「5 Interfacing Options」を選択します。
image.png
次に、「P6 Serial」を選択します。
image.png
「いいえ」を選択します。
image.png
「はい」を選択します。
image.png
するとこのような画面になり、シリアルポートが有効になります。
そのままraspi-configを終了すると、再起動するかどうかの選択を求められるので、再起動しておきます。
image.png
再起動後、下記のコマンドを入力すると、/dev/配下に有効化したシリアルポートttyS0が表示されます。

pi@raspberrypi:~ $ ls -l /dev/ttyS*

Raspberry Piの配線

Raspberry Piの8番ピン(GPIO14)と10番ピン(GPIO15)がUARTピンになっているので、
ワイヤージャンパでショートさせます。
image.png

実装

pyserialライブラリを使用して疎通確認をします。

serialTest.py
import serial

# 通信確立
ser = serial.Serial('/dev/ttyS0', '9600', timeout=0.1)
# データ送受信
ser.write('Hello, World!')
print(repr(ser.readline()))
ser.close()

ファイルを保存した後、LXTerminalでファイルが保存されているディレクトリに移動して実行します。
成功すると、送信したメッセージが表示されます。

pi@raspberrypi:~/work $ python setialTest.py
Hello World!

まとめ

Raspberry Piをあまり触った経験が無かったため、
シリアル通信がデフォルトでOFFになっていることを知りませんでした。
センサーやArduinoに繋げたりと、様々なことに使っていければと思います。

18
16
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
18
16