Python操作串口通信

Python操作串口通信

注意Linux下先要修改串口的权限:

sudo chmod 777 /dev/ttyUSB0

以下是python代码:

python 复制代码
# coding=utf-8
# 包:pyserial,pymysql
# 权限:sudo chmod 777 /dev/ttyUSB0
import serial
# import pymysql
import threading
import time

# x=serial.Serial('COM3',9600)  # winsows系统使用com3口连接串行口
# x=serial.Serial("/dev/ttyUSB0",9600,timeout=0.5)  # 使用USB连接串行口
x=serial.Serial("/dev/ttyS4",9600,timeout=0.5)  # Linux系统使用com4口连接串行口


def fasong():#发送函数
    while True:
        time.sleep(3)
        myinput= bytes([0x01,0X03,0X00,0X00,0X00,0X01,0X84,0X0A])
        #这是我要发送的命令,原本命令是:01 03 00 00 00 01 84 0A
        x.write(myinput)


def jieshou():#接收函数
    while True:
       while x.inWaiting()>0:
           myout=x.read(7)#读取串口传过来的字节流,这里我根据文档只接收7个字节的数据
           datas =''.join(map(lambda x:('/x' if len(hex(x))>=4 else '/x0')+hex(x)[2:],myout))#将数据转成十六进制的形式
           new_datas = datas.split("/x")#将字符串分割,拼接下标4和5部分的数据
           need = new_datas[4]+new_datas[5];#need是拼接出来的数据,比如:001a
           my_need = int(hex(int(need,16)),16)#将十六进制转化为十进制
           sql = "INSERT INTO VOC_DATA(value,create_time)VALUES('"+str(my_need)+"',"+str(int(time.time()))+")"
           print(sql)
           # 使用 execute()  方法执行 SQL 查询
           # 执行sql语句
           # cursor.execute(sql)
            # 提交到数据库执行
           # db.commit()


if __name__== '__main__':
    # 打开数据库连接
     # db = pymysql.connect("localhost","root","123456789","voc" )
    # 使用 cursor() 方法创建一个游标对象 cursor
     # cursor = db.cursor()
     t1 = threading.Thread(target=jieshou,name="jieshou")#线程1:不断的去请求数据
     t2= threading.Thread(target=fasong, name="fasong")#线程2:不断地去接收数据
     t2.start()#开启线程1
     t1.start()#开启线程2


#import serial
#ser = serial.Serial('/dev/ttyS3')  # 'COM3'
#ser.setBaudrate(9600)
#ser.setByteSize(8)
#ser.setStopbits(1)
#print(ser.portstr)
#data = ser.readline(0,'\r\n')
#data = ser.read(20)
#print(data)

参考博客:

https://www.cnblogs.com/zhengweizhao/p/8426826.html

https://blog.csdn.net/xuzhexing/article/details/91043579

相关推荐
技术无疆2 分钟前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
羊小猪~~10 分钟前
机器学习/数据分析--用通俗语言讲解时间序列自回归(AR)模型,并用其预测天气,拟合度98%+
人工智能·python·机器学习·数据挖掘·数据分析·回归·时序数据库
qq_2739002322 分钟前
解析TMalign文本文件中的转换矩阵
python·生物信息学
阿华的代码王国1 小时前
【JavaEE】——文件IO的应用
开发语言·python
电饭叔2 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
程序猿小D2 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
杰哥在此4 小时前
Python知识点:如何使用Multiprocessing进行并行任务管理
linux·开发语言·python·面试·编程
zaim16 小时前
计算机的错误计算(一百一十四)
java·c++·python·rust·go·c·多项式
PythonFun10 小时前
Python批量下载PPT模块并实现自动解压
开发语言·python·powerpoint
炼丹师小米10 小时前
Ubuntu24.04.1系统下VideoMamba环境配置
python·环境配置·videomamba