因为要做一个电容传感器的项目,写了一个简单的串口通信,但是观察串口数据的时候发现了一个问题,负数数据读不到,所以根据这一问题又修改了代码如下。
# singed_bin2dec.py
import os, sys, re
def int_convert(data,width):
if (data > 2 ** (width - 1) - 1):
data = data - 2 ** width
return data
a = 255
b = 65535
print(int_convert(a,8))
print(int_convert(b,16))
简易的串口接收数据并且放入表格
#coding:utf-8 #由于.py文件是utf-8的,所以必须有这一句
import os
import csv
import time
import serial # pyserial
import serial.tools.list_ports
import os, sys, re
isexist = os.path.exists('./data')
if not isexist: #判断是否存在文件夹如果不存在则创建为文件夹
os.makedirs('./data') # makedirs 创建文件时如果路径不存在会创建这个路径
with open('./data/result.csv', 'w', newline='') as table:
csv_write = csv.writer(table)
csv_row = ['time', 'B', 'Bref', 'Aref', 'DD1', 'DD2'] # 定义表头
#print(csv_row)
csv_write.writerow(csv_row)
print("请选择串口选择方式:\n"+"1.自动选择\n"+"2.手动选择")
Mode = int(input("请根据需求输入”1“或者”2“进行选择:\n"), 10)
try:
# 端口:CNU; Linux上的/dev/ttyUSB0等; windows上的COM3等
port_list = list(serial.tools.list_ports.comports())
if len(port_list) == 0:
print('找不到串口')
exit()
else:
print('识别到当前计算机中的串口:')
for i in range(0, len(port_list)):
print(str(i + 1)+':'+str(port_list[i]))
#print(port_list[i])
if ("CH340" in str(port_list[i])):
CH340 = str(port_list[i])
if(Mode == 1):
CH340 = CH340[0:5].rstrip()#删除字符串末尾的空格
print('已经自动选择:' + CH340)
elif(Mode == 2):
CH340 = input("请输入需要使用的串口:\n")
portx = CH340
# 波特率,标准值有:50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
bps = 57600
# 超时设置,None:永远等待操作;
# 0:立即返回请求结果;
# 其他:等待超时时间(单位为秒)
timex = None
# 打开串口,并得到串口对象
ser = serial.Serial(portx, bps, timeout=timex)
print("串口详情参数:", ser)
# # 十六进制的发送
# result = ser.write(chr(0x06).encode("utf-8")) # 写数据
# print("写总字节数:", result)
# 十六进制的读取
#i = 0
# data1 = 1
# data2 = 1
# data3 = 1
# data4 = 1
# data5 = 0
# data6 = 0
# data7 = 0
# data8 = 0
# data9 = 0
ct_start = int(time.time()*10)
def int_convert(data, width):
if (data > 2 ** (width - 1) - 1):
data = data - 2 ** width
return data
while (1):
#i+=1
data1 = int(ser.read().hex(),16) # B键低字节
data2 = int(ser.read().hex(),16) # B键高字节
data3 = int(ser.read().hex(),16) # B参考低字节
data4 = int(ser.read().hex(),16) # B参考高字节
data5 = int(ser.read().hex(),16) # A参考低字节
data6 = int(ser.read().hex(),16) # A参考高字节
data7 = int(ser.read().hex(),16) # DD1低字节
data8 = int(ser.read().hex(),16) # DD1高字节
data9 = int(ser.read().hex(),16) # DD2低字节
data10 = int(ser.read().hex(),16) # DD2高字节
t1 = data1 + data2 * 256
t2 = data3 + data4 * 256
t3 = data5 + data6 * 256
t4 = data7 + data7 * 256
t5 = data9 + data10 * 256
T1 = int_convert(t1, 16)
T2 = int_convert(t2, 16)
T3 = int_convert(t3, 16)
T4 = int_convert(t4, 16)
T5 = int_convert(t5, 16)
ct_current = int(time.time()*10)
time_count_100ms = ct_current - ct_start
# print(int_convert(a, 8))
# print(int_convert(b, 16))
with open('./data/result.csv', 'a', newline='') as table:
csv_write = csv.writer(table)
#csv_row = ['T','R','B','D','S','TH','CT']
#print(csv_row)
csv_row = [time_count_100ms, T1, T2, T3, T4, T5]
print(csv_row)
csv_write.writerow(csv_row)
print("----------")
ser.close() # 关闭串口
except Exception as e:
print("error!", e)
希望可以对大家有所帮助。