程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

【用文本方式做數據處理】基於Python的串口協議數據處理(可以用Python調用GPIO口模擬串口數據處理 如樹莓派)

編輯:Python

【用文本方式做數據處理】基於Python的串口協議數據處理(可以用Python調用GPIO口模擬串口數據處理 如樹莓派)

通訊協議如下:

數據位定義功能:

比如23 55 00 01 52 02 02 00 CF 0D 0A
功能就是“右”

# -*- coding: utf-8 -*-
""" Spyder Editor This is a temporary script file. """
def trans(x):
x=str(x)
start_byte = [0x23,0x55]
data_len = 0
device_address = []
data = []
datasum = "0x"
command_list = [None,"左","右","上","下","前","後"]
checksum = 0
stop_byte = [0x0D,0x0A]
x_list = []
y_list = []
re_list = []
command_str = ""
try:
x_list = x.split(" ")
for i in x_list:
i = int("0x"+i,16)
y_list.append(i)
except:
return "Trans Error"
print(x_list,y_list)
try:
if y_list[0] == start_byte[0] and y_list[1] == start_byte[1]:
print("Start Success")
else:
return "Start Error"
except:
return "Start Error"
try:
data_len = int(str('0x'+x_list[2]+x_list[3]),16)
print("Data Length = "+str(data_len))
except:
return "Data Length Error"
try:
if y_list[8+data_len] == stop_byte[0] and y_list[9+data_len] == stop_byte[1]:
print("Stop Success")
else:
return "Stop Error"
except:
return "Stop Error"
try:
device_address.append('0x'+x_list[4])
device_address.append('0x'+x_list[5])
print("Device Address = "+str(device_address))
except:
return "Device Address Error"
try:
for i in range(0,data_len):
data.append(x_list[6+i])
print("Data = "+str(data))
except:
return "Data Error"
try:
for i in data:
datasum = datasum + str(i)
datasum = int(datasum,16)
print("Datasum = "+str(datasum))
except:
return "Datasum Error"
try:
for i in range(0,6+data_len):
checksum = checksum + y_list[i]
print("Checksum = "+str(checksum))
if checksum == int(str('0x'+x_list[6+data_len]+x_list[7+data_len]),16):
print("Check Success")
else:
return "Check Error"
except:
return "Check Error"
try:
command_str = command_list[datasum]
except:
return "Command Error"
re_list.append(device_address)
re_list.append(datasum)
re_list.append(command_str)
return re_list
if __name__ == '__main__':
x='23 55 00 01 52 02 02 00 CF 0D 0A'
print(trans(x))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved