python桥接手柄和串口实现通信

python桥接手柄和串口实现通信,第1张

概述一、需求分析需要使用游戏手柄来控制平衡小车,由于游戏手柄和平衡小车不能连接,所以使用电脑作为中介实现两者通信。需要实现以下功能接收手柄或键盘的键值处理接受的键值通过串口发送指定信息给下位机读取下位机发送的消息并显示二、环境搭建Python扩展程序包的二进制文 一、需求分析

需要使用游戏手柄来控制平衡小车,由于游戏手柄和平衡小车不能连接,所以使用电脑作为中介实现两者通信。

需要实现以下功能

接收手柄或键盘的键值处理接受的键值通过串口发送指定信息给下位机读取下位机发送的消息并显示二、环境搭建

Python扩展程序包的二进制文件下载网址为:

https://www.lfd.uci.edu/~gohlke/pythonlibs/

pygame 是一个可以读取手柄和键盘模块,我的python环境为3.7版本所以我下载的的是pygame‑2.0.1‑cp37‑cp37m‑win_amd64.whl

pyserial是一个串口通信模块,我下载的为pyserial‑3.5‑py3‑none‑any.whl

下载完成后以管理员的身份打开命令提示符使用 pip 指令安装:

# 跳转到文件下载的目录C:\windows\system32> cd C:\Users\administrator\Downloads# 使用 pip 安装 文件C:\Users\administrator\Downloads> pip install pygame‑2.0.1‑cp37‑cp37m‑win_amd64.whl

pyserial的啊安装也是一样的。

注意:如果是使用pycharm 编写的程序,会提示找不到模块,因为pycharm 运行环境的扩展库只扫描当前项目下的,因此我是使用VScode 编写。

三、程序实现

定义通信规则:为了方便起见每次只发送一个字符,直行发送 ‘q’,加速发送 ‘s’,减速发送 ‘e’,左转发送 ‘l’,右转发送 ‘r’。

第一次调试可以打开print(message)查看系统获取的信息

import pygameimport timeimport serialimport serial.tools.List_ports# 串口通信端口号portx = ''# 串口通信 波特率Baud = 115200# 程序状态state = True# 消息message = dict()# 串口对象ser = serial.Serial()# 检查并选择端口def set_port():    global portx    print("正在检查可用端口。。")    port_List = List(serial.tools.List_ports.comports())    if len(port_List) == 0:        print("无可用串口!")        return 0    else:        print('序号\t名称')        for i in range(0, len(port_List)):            print(i + 1, '\t', port_List[i])        n = 1        if len(port_List) != 1:            n = int(input('输入端口序号:'))        portx = str(port_List[n - 1].device)        print('已选择端口:', portx)        return 1def open_port():    global portx    try:        ser.baudrate = Baud        ser.port = portx        ser.open()  # 打开串口    except Exception as e:        ser.close()  # 关闭端口        print('端口打开失败,尝试更换端口:', e)        return 0    return 1def send_joystick():    print('连接成功!')    global state    pygame.init()    pygame.joystick.init()    while state:        time.sleep(0.2)        message.clear()        for event in pygame.event.get():            if event.type == pygame.QUIT:                done = True            if event.type == pygame.JOYbuttonDOWN:                message['JOYbuttonDOWN'] = event.button            if event.type == pygame.JOYbuttonUP:                message['JOYbuttonUP'] = event.button        joystick_count = pygame.joystick.get_count()        for nums in range(joystick_count):            joystick = pygame.joystick.Joystick(nums)            joystick.init()            axes = joystick.get_numaxes()            for i in range(axes):                axis = joystick.get_axis(i)                message['axes' + str(i)] = int(axis * 10)        # print(message)	#打印获取的信息        if message == {}:  # 未连接            state = False            print('没有找到手柄')            break        if message.get('JOYbuttonDOWN') == 0:  # 直行            ser.write(b'z')            print('直行')        if message.get('JOYbuttonDOWN') == 1:  # 停车            ser.write(b'q')            print('停车')        if message.get('axes5') >= 0:  # 加速            ser.write(b's')            print('加速')        if message.get('axes2') >= 0:  # 减速            ser.write(b'e')            print('减速')        if message.get('axes0') <= -5:  # 左转            ser.write(b'l')            print('左转')        if message.get('axes0') >= 5:  # 右转            ser.write(b'r')            print('右转')        if message.get('JOYbuttonDOWN') == 7:  # 退出            state = False            print('退出')        if ser.in_waiting:            print(ser.read(ser.in_waiting).decode("gbk"), end='')if set_port() == 1:    if open_port() == 1:        send_joystick()    ser.close()  # 关闭端口input("按任意键退出!")
总结

以上是内存溢出为你收集整理的python桥接手柄和串口实现通信全部内容,希望文章能够帮你解决python桥接手柄和串口实现通信所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1187364.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存