gpt4 book ai didi

python - 使用 PyGame 时的非阻塞串行读取线

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:47 24 4
gpt4 key购买 nike

我正在开发一个使用 PyGame 编写的心率监测器,使用 Arduino 作为输入,该游戏的想法是让您无论屏幕上显示什么,都可以通过放松练习来尝试和控制您的心率。

我希望能够在游戏本身中运行视频/鼠标/键盘按钮捕获等功能,同时在左上角显示心率并在它发生变化时从 arduino 更新它。

arduino 读取心率监视器,然后发布格式如下的 JSON 字符串:

{'heart_rate': 65,'state': 'running'}

“状态”可以是“初始化”、“运行”、“失败”或“停止”之一。

虽然我非常熟悉 Python,但我已经从 http://www.akeric.com/blog/?p=1237 中获取了代码让我开始使用 PyGame,因为我以前没有在这里冒险过。

我遇到的问题是,当我尝试从串行端口读取时,它会锁定游戏。

我已经阅读了有关线程的文章,并且我认为我已经正确地实现了它,但是以下代码仍然会阻塞:

"""
default.py
www.akeric.com - 2010-09-07
Default, base, initial setup for a pygame program.
In this case, black background, white circle follows mouse position, and
framerate is shown in the title-bar.
"""

#-------------------------------------------------------------------------------
# Imports & Inits
import sys
import serial
import json
import threading

import pygame
from pygame.locals import *
pygame.init()
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)


#-------------------------------------------------------------------------------
# Constants
VERSION = '1.0'
WIDTH = 800
HEIGHT = 600
FRAMERATE = 60
CURRENT_MESSAGE = {'heart_rate': 0}

#-------------------------------------------------------------------------------
# Screen Setup
screen = pygame.display.set_mode((WIDTH, HEIGHT))
bgCol = Color('black')
clock = pygame.time.Clock()
moduleName = __file__.split('\\')[-1]

#-------------------------------------------------------------------------------
# Define helper functions, classes, etc...
def text_objects(text, font):
textSurface = font.render(text, True, (255,255,255))
return textSurface, textSurface.get_rect()

def message_display(text,x_pos=(WIDTH/2),y_pos=(HEIGHT/2)):
largeText = pygame.font.Font('freesansbold.ttf',25)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = (x_pos,y_pos)
screen.blit(TextSurf, TextRect)

def spam():
pos = pygame.mouse.get_pos()
pygame.draw.circle(screen, Color('white'), pos, 32)

def handle_data(data):
CURRENT_MESSAGE = json.loads(data)
message_display("HR: %s" % CURRENT_MESSAGE['heart_rate'],50,20)

def read_from_port(ser):
while True:
reading = ser.readline().decode()
if len(reading) > 0:
print "Data Recieved"
handle_data(reading)



#-------------------------------------------------------------------------------
# Main Program
def main():
print "Running Python version: %s"%sys.version
print "Running PyGame version: %s"%pygame.ver
print "Running %s version: %s"%(moduleName, VERSION)
looping = True

# Main Loop-----------------------
while looping:
# Maintain our framerate, set caption, clear background:
clock.tick(FRAMERATE)
pygame.display.set_caption("%s - FPS: %.2f" %(moduleName,clock.get_fps()) )
screen.fill(bgCol)
spam()


# Update our display:---------
pygame.display.flip()

#-------------------------------------------------------------------------------
# Execution from shell\icon:
if __name__ == "__main__":
# Make running from IDE work better:
thread = threading.Thread(target=read_from_port, args=(ser,))
thread.start()
sys.exit(main())

任何人都可以帮助我了解我哪里出错了吗?

最佳答案

我对 Python 知之甚少,但我会测试看看是否有任何字符等待读取,然后只读取该数字而不是使用 readline。我认为您想使用 in_waiting 和 read(size)。

Readline 将阻塞,直到收到回车。

所以,我想是这样的:

def read_from_port(ser):
while True:
if in_waiting > 0:
reading = read(in_waiting)
print "Data Recieved"
handle_data(reading)

现在您需要连接并解析定界符处的字符串,以确保已接收到整个字符串。

关于python - 使用 PyGame 时的非阻塞串行读取线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37608799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com