Python3 Simple Method for Serial Communication

  • 2021-06-28 09:34:50
  • OfStack

As follows:


import serial
import sys
import os
import time
import re
 
def wait_for_cmd_OK():
    while True:
        line = ser.readline()
        try:
            print(line.decode('utf-8'),end='')
        except:
            pass
        if ( re.search(b'OK',line)):
            break
 
def sendAT_Cmd(serInstance,atCmdStr):
    serInstance.write(atCmdStr.encode('utf-8'))
    wait_for_cmd_OK()
 
ser = serial.Serial("/dev/ttyACM0",9600,timeout=30) # Select the serial number and baud rate because I am ubuntu The serial number is /dev/ttyACM0
sendAT_Cmd(ser,'AT+CFUN=1\r')
ser.close() 

Related articles: