python 串口读取byte类型数据并访问

以读取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]
这样返回的将会是字节类型的第一个字节的数据。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千里飞刀客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值