目前項目中所使用的基本分兩種,一種是直接串口通信,通過python發送串口指令進行通信,第二種是adb通信,通過adb指令進行通信。
一、串口通信
1.串口信息
import serial import serial.tools.list_ports if __name__ == "__main__": port_a = "COM19" #通過pc的設備管理器查看串口號 bps = 115200 #串口速率 Timeout = 5 #串口延時 #打開串口 ser_a = serial.Serial(port_a, bps, timeout = Timeout) #將串口返回值輸入到函數 test(ser_a)
2.將串口信息傳入函數
通過serial庫打開串口,並將返回值輸入到所需要的函數中,下面看如何發送串口指令
def SendAndWait(ser, sendstr, findstr, timeout): ser.write(SendStr.encode()) Timeout = math.ceil(timeout) time.sleep(timeout) result = str(ser.read_all())#讀出串口返回值 a = result.find(findstr)#找出返回值中所需要的語句作為判斷條件 #根據自己需要對a進行應用 return def test(ser): #發送串口指令 SendAndWait(ser, "xxxxx", "zzzzz", 5)#ser是打開的串口,xxxxx是串口指令,zzzzz是需要在串口指令返回值中尋找的語句,5是timeout
二、ADB通信
adb通信是通過usb通信,不用打開串口,直接用subporcess函數進行語句發送就可以。
import subprocess
def adb():
subprocess.call("adb", "shell", "xxx", shell=True)#adb shell是cmd必須的語句,后面指令根據需要來。
a = subprocess.getoutput("adb", "shell", "xxx")#該函數不在終端上打印adb返回值,但是可以賦值給變量,方便通過變量來判斷返回值中的內容