Pythonでシリアル(RS232C)通信
Pythonでシリアル通信(RS232C)通信をして、Arduinoマイコンのテストコマンドを制御してみました。
【準備】pipでpyserialのインストールが必要です。
pip install pyserial
#!/usr/bin/python3 """ Python RS232C ***need pyserial module*** pip install pyserial Python3 OS:Windows or Linux DATE VER NAME COMMENT 2020/03/02 0.00 garyo NEW """ import serial import time import datetime class PyRs232c(): VERSION = "0.00" logFilename = "SIO.log" def __init__(self): self.baudrate = 9600 self.com_name = "COM1" #self.com_name = '/dev/ttyUSB0' self.timeout = 1.0 def setComName(self,com_name): self.com_name = com_name def setBaudrate(self,baudrate): self.baudrate = baudrate def sioOpen(self,com_name="",baudrate = 0): if com_name != "" : self.com_name = com_name if baudrate != 0: self.baudrate = baudrate self.ser = serial.Serial(self.com_name,self.baudrate,timeout = self.timeout) self.waitt(2) def sioClose(self): self.ser.close() def waitt(self,s): time.sleep(s) def send(self,s): self.logPrintln(self.disp("[Tx:]" + s)) s = s.encode("shift-jis") self.ser.write(s) def recv(self,Tout = 10): t = time.time() timeout = Tout ret = b"" while 1: if time.time() - t > timeout : break c = self.ser.read() ret = ret + c if c == b'\r': pass elif c == b'\n': break else: pass self.logPrintln(self.disp("[Rx:]" + str(ret,encoding='utf-8'))) r = str(ret,encoding='utf-8') return (r) def Send_Command(self,Cmd,jug_str,Tout = 5): r = "" jug = False self.ret = "" self.send(Cmd + "\r\n") t = time.time() while 1: if time.time() - t > Tout : break r = r + self.recv() if r.find(jug_str) > -1: jug = True break self.ret = r return(jug) def getRet(self): return (self.ret) def disp(self,s): s=s.replace("\r","[CR]") s=s.replace("\n","[LF]") return (s) #Log def setLogFilename(self,filename): self.logFilename = filename def logPrint(self,s): f = open(self.logFilename,'a') f.write(s) f.close() def logPrintln(self,s): self.logPrint(s + "\n") if __name__ == "__main__": rs232c = PyRs232c() rs232c.sioOpen("COM3",9600) rs232c.logPrintln("\n[START]" + datetime.datetime.now().strftime('%Y/%m/%d_%H:%M:%S')) jug = True if jug == True : jug = rs232c.Send_Command("PS130","OK") while 1: if jug == True : jug = rs232c.Send_Command("PW130","OK") rs232c.waitt(.5) if jug == True : jug = rs232c.Send_Command("PW131","OK") rs232c.waitt(.5) if jug == False: break rs232c.sioClose()
コメント
コメントを投稿