LoginSignup
1
0

More than 1 year has passed since last update.

Raspberry Pi 上で UART通信をする Python環境で プログラム

Last updated at Posted at 2021-10-21

はじめに
Raspberry Pi4 上で UART通信を行う プログラムを Pythonで書いてみました。

環境は、Raspberry Pi4 に標準で搭載されている [Thonny Python IDE]


準備
シリアル通信を行うためのライブラリーを Raspberry Pi4 に入れる

>$ pip install pyserial

簡単なプログラム

import serial
import time

#File Open
File = open('response.txt', 'w')

#Open SerialDevice
SerDevice = serial.Serial('/dev/ttyS0', 115200, timeout=10)

#Set Command
#'GetVersion' という文字列のコマンドを出す
Command = "GetVersion\r"

#Send Command
SerDevice.write(Command.encode())


#******************************
#Recieve Response
while True:
    #Read data one Line (top->'\r\n')
    L_RecieveData=SerDevice.readline()
    RecieveData = L_RecieveData.decode()

    #Get Data Length
    DataLength = len(L_RecieveData)

    #If DataLength = 2, then Response END!!
  #1行の文字列が2文字があることが受信データの終わりという条件にした
   if DataLength==2: break
    else:
        File.writelines(RecieveData)
        print(RecieveData)

#******************************
#Close Serial Device
SerDevice.close()
#File Close
File.close()

☆2021年10月21日(木) 午後2時45分 初版 (Ver1.00) 作成
☆2021年11月09日(火) 午後2時30分 初版 (Ver1.10) 作成 <簡単なプログラムの入れ替え>

1
0
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
1
0