以读取SBT力传感器数据为例
#! usr/bin/env pyhton
# coding:utf-8
import serial
import time
import csv
import os
originaltime = 0.0
starttime = 0.0
endtime = 0.0
endtimebefore = 0.0
def savedis(force , csvfile):
f = open(csvfile, 'a', encoding='utf-8', newline='') # 'w'覆盖写 'a'追加写
csv_writer = csv.writer(f)
global endtime
time_head = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(endtime))
time_sec = (endtime - int(endtime)) * 1000
timesample = "%s.%03d" % (time_head, time_sec)
csv_writer.writerow([timesample, str(force)])
# f.close()
def main():
# 文件处理
current_path = os.path.abspath(__file__)[:-len('sbt_test.py')]
currenttime = time.localtime(time.time())
csvfile = current_path + str(currenttime.tm_hour) + '-' + str(currenttime.tm_min) +'-'+ str(currenttime.tm_sec) + '.csv'
f = open(csvfile, 'a', encoding='utf-8', newline='') # 'w'覆盖写 'a'追加写
csv_writer = csv.writer(f)
csv_writer.writerow(['timestamp(ms)', 'display(N)'])
f.close()
# 串口声明
port = 'COM7' #根据设备管理器的端口号更改
baud = 115200
timex = 0.02 # 超时设置,None:永远等待操作,0为立即返回请求结果,其他值为等待超时时间(单位为秒)
global starttime
global endtime
global endtimebefore
sbtforce = serial.Serial(port, baud, timeout=timex) #此行不能放在循环内,因为耗时长
sendmessage = sbtforce.write(bytes.fromhex('FE010701000001CFFCCCFF'))
offset = 20 # 收到的数据跟放大器上的示数不对应,需要减去一个偏差值,根据示数调整
while True:
endtime = time.time()
startdata = sbtforce.read(1)
if startdata == b'\xFE':
buffer = sbtforce.read(10)
if (buffer[9] == 255):
print("buffer=",buffer)
force = buffer[2:6]
print('force = ',force)
force = force[0] << 24 | force[1] << 16 | force[2] << 8 | force[3]
if force > 100000000:
force = force - 2**32 - offset
if force > 0:
force -= offset
force = force / 100.0
print('压力值:', force)
savedis(force, csvfile)
if __name__ == '__main__':
main()
声明串口对象:
sbtforce = serial.Serial(port, baud, timeout=timex)
然后从串口读取字节,比如一次读取10个字节:
data = sbtforce.read(10)
然后,假如要访问data的第一个字节,如果直接写
data[0]
那么返回的将是第一个字节对应的整形,也就是说type(data[0])=int
那么如何拿到byte类型呢,可以这样做:
data[0:1]
这样返回的将会是字节类型的第一个字节的数据。