- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在 Raspberry Pi 3 上从 USB 读取序列号时遇到问题。我正在阅读的设备是 Arduino NANO。那里的代码对于基于 Windows 的机器来说是干净和好的。
但是,在 Raspberry Pi 3 (debian jessie) 上,我发现通过串行读取时 CPU 使用率达到 100%。这些是我安装的包:
python-pygame python-serial python-netifaces cu python-wxgtk3.0
我使用此代码不停地检查串行输入:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import config
from config import officialwebsite
import pygame
from pygame.locals import *
import serial
import sys
import glob
import time
#
####################
# New Fresh class that handle all input types at once
####################
class CInput():
def __init__(self,Logs,Config,myDisplay):
self.Logs=Logs
self.shift=False
self.clock = pygame.time.Clock()
self.Config = Config
self.Lang=None
self.ConfigKeys=Config.ConfigFile['SectionKeys']
self.last_click = 0
self.myDisplay=myDisplay
self.ser = False # Init serial connexion
####### SERIAL
def Serial_Connect(self):
self.SerialBypass = bool(self.Config.GetValue('SectionAdvanced','noserial'))
# Check input serial port (if no param --noserial)
if not self.SerialBypass:
try:
if self.Config.detectedserialport:
serialport=self.Config.detectedserialport
else:
serialport=self.Config.GetValue('SectionGlobals','serialport')
serialspeed = int(self.Config.GetValue('SectionGlobals','serialspeed'))
self.ser = serial.Serial(serialport,serialspeed)
self.Logs.Log("DEBUG","Successfully loaded serial port {} at speed {}".format(serialport,serialspeed))
except:
self.Logs.Log("FATAL","Unable to load serial port : {} . Common errors are : \n * Your board is not connected \n * Your config file is not set properly (pydarts.cfg in your home folder)\n * Your arduino driver is not installed properly (windows only)\n * You're not part of the dialout group (Linux only).\n -- Note : You can use --noserial argument to bypass serial connection.".format(self.Config.GetValue('SectionGlobals','serialport')))
self.myDisplay.PlaySound('whatamess')
self.myDisplay.InfoMessage([self.Lang.lang['serial-issue-1'],self.Lang.lang['serial-issue-2'],self.Lang.lang['serial-issue-3'],officialwebsite,self.Lang.lang['serial-issue-4']],None,None,'middle','small')
sys.exit(2)
else:
self.Logs.Log("DEBUG","Serial connection bypass as requested. No need for a dart board mate !")
#
# Flush
#
def Serial_Flush(self):
if not self.SerialBypass:
try:
self.ser.flushInput() #Flush Serial input values (prevent user to hit while prog sleeps)
except:
self.Logs.Log("DEBUG","Unable to flush input from serial port.")
else:
self.Logs.Log("DEBUG","Bypassing serial port flush")
#
# Read serial connection.
#
def Serial_Read(self,context=False):
DartStroke = False
KeyStroke = False
# Listen on serial cx
try:
# This event (get) solve the bug on windows (waiting screen)
pygame.event.get()
# Read into the serial buffer if there is somthing inside
serdata=False
try:
serdata=self.ser.in_waiting()#pyserial v2.x
except:
pass
try:
serdata=self.ser.inWaiting()#pyserial v3.x
except:
pass
if serdata: #Read only if there is something in the serial buffer (non-blocking mode)
DartStroke=self.ser.read()
DartStroke=DartStroke.decode(encoding='UTF-8')
except Exception as e:
print("Error {}".format(e))
#print(DartStroke)
# Find unique key in config dict. Returns uppercase (only if something has been hit on board)
if DartStroke:
for TheKey, TheConfig in self.ConfigKeys.items():
if TheConfig == DartStroke:
KeyStroke=TheKey.upper()
# Debug Serial Input (only if something has been hit on board)
if DartStroke and KeyStroke:
self.Logs.Log("DEBUG","DEBUGINPUT : You hit \"{}\" which is associated to \"{}\" in your configuration file.".format(DartStroke,KeyStroke))
elif DartStroke and KeyStroke==False:
self.Logs.Log("DEBUG","You hit \"{}\" which doesn't exists in your configuration file.".format(DartStroke))
# If asked to return KEY, else return VAL
if context=='wizard':
return DartStroke
else:
return KeyStroke
#### KEYBOARD & MOUSE (from pygame)
# Context can be different, dependanding from where this method is used. So far : 'menus' or 'game'
#
def KbdAndMouse(self,ktype, specials, context=None):
keypressed = ""
realkey=-1
double_click_duration=500
clicktype=False
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
print("Exit requested")
sys.exit(0)
# Case of Key UP
if event.type == KEYUP:
if pygame.key.name(event.key) == 'left shift':
self.shift=False
# Case of key PRESSED
if event.type == KEYDOWN:
#self.clock.tick(30)
keyname = pygame.key.name(event.key)
unicodekey = event.dict['unicode']
if len(keyname)==1 and unicodekey!='':
keycouple = self.RealKey(unicodekey,context)
else:
keycouple = self.RealKey(keyname,context)
realkey = keycouple[1]# Get pydarts translation of key
realtype = keycouple[0]# Get pydarts translation of key type (alpha, fx, num, etc...)
#print("Key analysis : original {}, translated as {} in unicode and {} in pydarts key".format(keyname,unicodekey,realkey))
if realkey in specials:# return special key if allowed
return realkey
elif realtype in ktype:# Return standard key if allowed/expected
return realkey
# Case of MOUSE BUTTON PRESSED
if event.type == pygame.MOUSEBUTTONDOWN:
#on click
self.clock.tick(30)
self.diff = self.clock.get_time()
if self.diff <= double_click_duration:
clicktype='double-click'
#self.clock.tick()
#self.last_click = 0
else:
clicktype='single-click'
#self.last_click = self.now
if clicktype:
keycouple = self.RealKey(clicktype,context)
realkey = keycouple[1]# Get pydarts translation of key
realtype = keycouple[0]# Get pydarts translation of key type (alpha, fx, num, etc...)
if realkey in specials:
return realkey
# Everything else failed, return -1 (0 is a valid char)
return -1
def ListenInputs(self,ktype=['num','alpha','fx','arrows'], specials = ['enter','tab','backspace','left shift','escape','space','double-click','single-click'] ,WaitFor=[], context='menus'):
SerialInput = False
pyGameInput = -1
while True:
# First try to read serial
if not self.SerialBypass:
#print("Before serial")
SerialInput = self.Serial_Read(context)
#print("After serial")
# If serial returns false, try to read keyboard
if not SerialInput:
#print("Before pyGame Input")
pyGameInput = self.KbdAndMouse(ktype,specials,context)
#print("After pyGame Input")
# If any input return anything, exit from loop
if pyGameInput!=-1:
self.Logs.Log("DEBUG","Input debug : {}".format(pyGameInput))
# Return Serial input if expected (or if nothing expected)
if (SerialInput and WaitFor==[]) or (SerialInput in WaitFor):
return SerialInput
# Return pyGame input if expected (or if nothing expected)
if (pyGameInput!=-1 and WaitFor==[]) or (pyGameInput in WaitFor):
return pyGameInput
#### COMMON
#
# Function to get key and type from current state
#
def RealKey(self,keypressed,context):
if (keypressed == "&" and self.shift) or keypressed=="[1]" or keypressed=="1":
kvalue = 1
ktype = 'num'
elif (keypressed == "world 73" and self.shift) or keypressed=="[2]" or keypressed=="2":
kvalue = 2
ktype = 'num'
elif (keypressed == "\"" and self.shift) or keypressed=="[3]" or keypressed=="3":
kvalue = 3
ktype = 'num'
elif (keypressed == "'" and self.shift) or keypressed=="[4]" or keypressed=="4":
kvalue = 4
ktype = 'num'
elif (keypressed == "(" and self.shift) or keypressed=="[5]" or keypressed=="5":
kvalue = 5
ktype = 'num'
elif (keypressed == "-" and self.shift) or keypressed=="[6]" or keypressed=="6":
kvalue = 6
ktype = 'num'
elif (keypressed == "world 72" and self.shift) or keypressed=="[7]" or keypressed=="7":
kvalue = 7
ktype = 'num'
elif (keypressed == "_" and self.shift) or keypressed=="[8]" or keypressed=="8":
kvalue = 8
ktype = 'num'
elif (keypressed == "world 71" and self.shift) or keypressed=="[9]" or keypressed=="9":
kvalue = 9
ktype = 'num'
elif (keypressed == "world 64" and self.shift) or keypressed=="[0]" or keypressed=="0":
kvalue = 0
ktype = 'num'
elif (keypressed == "=" and self.shift) or keypressed=="[+]":
kvalue = '+'
ktype = 'math'
elif (keypressed == "*" and self.shift==False) or keypressed=="[*]":
kvalue = '*'
ktype = 'math'
elif (keypressed == "-" and self.shift==False) or keypressed=="[-]":
kvalue = '-'
ktype = 'math'
elif (keypressed == ":" and self.shift) or keypressed=="[/]":
kvalue = '/'
ktype = 'math'
elif (keypressed == "world 64" and self.shift) or keypressed=="[0]" or keypressed=="0":
kvalue = 0
ktype = 'math'
elif (keypressed == ";" and self.shift) or keypressed==".":
kvalue = '.'
ktype = 'alpha'
elif keypressed == "down" or keypressed == "up" or keypressed == "right" or keypressed == "left":
kvalue = keypressed
ktype = 'arrows'
elif keypressed == 'escape' and context=='game': # In-game context, escape means ABORT
kvalue='GAMEBUTTON'
ktype='special'
elif keypressed == 'escape': # All others context, it means 'escape'
kvalue=keypressed
ktype = 'special'
elif keypressed == 'space' and context=='game': # In-game context, space means NEXT PLAYER
kvalue='PLAYERBUTTON'
ktype='special'
elif keypressed == 'space': # All other context, space means 'space'
kvalue=keypressed
ktype='special'
elif keypressed == 'enter' or keypressed=='return': # Enter and Return are comfunded volontarily
kvalue='enter'
ktype='special'
elif keypressed == 'tab':
kvalue=keypressed
ktype='special'
elif keypressed == 'backspace':
kvalue=keypressed
ktype='special'
elif keypressed == 'b' and context=='game': # In-game, 'b' means 'BACKUPTURN'
kvalue='BACKUPBUTTON'
ktype='special'
elif (keypressed == 'f' or keypressed=='double-click'): # Everywhere, 'f' and double-click means "Fullscreen"
kvalue='TOGGLEFULLSCREEN'
ktype='special'
elif keypressed == 'left shift':
kvalue=keypressed
ktype='special'
self.shift=True #Enable Shift !
# Other special chars, need to be at the end (based on length)
elif (len(keypressed)== 2 or len(keypressed)==3) and keypressed[:1] == "f": # Detect Fx keys
kvalue = keypressed
ktype = 'fx'
elif len(keypressed)== 1:# Detect any other key (simple alpha keys)
kvalue = keypressed
ktype = 'alpha'
else:
kvalue=None
ktype=None
return [ktype,kvalue]
我不确定如何解决 100% CPU 问题。在某处添加一个 time.sleep(0.3)
语句会有帮助吗?有人对 debian jessie 上的 Raspberry Pi 3 串行 CPU 负载有更多经验吗?
最佳答案
while True:
pygame.time.wait(5)# A few ms to reduce cpu...
True 解决了问题!
关于 python 3 time.sleep() "serial read",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41664667/
我在 linux (Centos) 上使用 pthread 编程?我想让线程休眠一小段时间以等待某些事情。我正在尝试使用 sleep()、nanosleep() 或 usleep() 或其他可以做到这
此要求出现在我的 Android 应用程序中,但它通常适用于 Java。我的应用程序每隔几秒钟“做某事”。我已经按如下方式实现了这一点(只是相关的 fragment - 不是完整的代码): fragm
我正在使用 esp8266 构建 IR 到 WiFi 桥接器。基本上,我正在构建一个连接到红外 Remote 内的 esp8266 的红外接收器,以通过 wifi 将接收到的红外远程按键转发到服务器。
我想让 Toast 出现,然后让 sleep 运行。 如果我这样做,Toast 会在 sleep 后出现,但我希望反过来。有人有建议吗?这是我的代码 switch (checkedRadioButto
我在做一件简单的事情,打印一条错误消息,延迟执行 5 秒,然后调用另一个函数,这是代码 public void saveAndDisplay() throws InterruptedException
我的 Activity 上有一个按钮,当我单击它时,我希望按钮改变颜色,等待一段时间,然后再次改变颜色。 我尝试过以下两个版本的 sleep : 尝试1: public void buClick(Vi
我尝试过这个: for(int i =0; i1。创建ScheduledExecutorService public static ScheduledExecutorService createSch
我有一个 Winform,需要等待大约 3 - 4 小时。我无法关闭并以某种方式重新打开应用程序,因为它在等待时在后台做的事情很少。 为了实现等待 - 不给 UI 线程造成麻烦和其他原因 - 我有一个
我在网上看到了下面一段关于 Linux 线程的代码。但是当我运行它时,所有线程似乎都在 sleep ,而不仅仅是主线程。为什么?另外,如果没有 sleep(5),“线程创建成功”语句会运行 3 次而不
我有一个 php 脚本,我需要每 5 秒运行一次(运行,等待它完成,等待 5 秒,再次运行) 我有两种方法。要么在脚本中有一个带有 sleep 功能的无限循环,看起来像这样: while (1) {
我有一个图形用户界面,我想显示一些文本,然后稍等一下。 我的代码看起来像这样: //do something (add JTextArea, revalidate, repaint) try{
我想知道安卓手机的 sleep 模式和深度 sleep 模式有什么区别,手机进入休眠模式和深度 sleep 模式会有什么影响。 请提供详细的答案。 问候,皮克斯 最佳答案 深度 sleep 模式与休眠
我正在学习 C。在这个节目中我使用 sleep 功能来减慢倒计时。我的教科书没有指定我应该包含的库来使用 sleep 功能。所以我使用它时没有为它包含任何特殊的库并且它可以工作。但它在代码块中给了我这
我正在尝试模拟按键按下和按键 Action 。 例如:2638 毫秒。 SendMessage(hWnd, WM_KEYDOWN, keyCode, 0); Sleep(2638); SendMess
我在 while 循环中调用一个线程 hibernate 1 秒。当标志为真时,循环将运行(标志为真无限时间)。在循环线程内应该 hibernate 1 秒,唤醒并增加计数器,检查 IF 条件,在 F
有很多文件说“你应该避免使用带警报的 sleep ,因为许多系统使用警报来实现 sleep ”。实际上,我正在为这个问题而苦恼。 那么,当 sleep() 不能很好地处理警报时,是否有人可以帮助我“
我有两个带有图像的jlabel..我尝试在单击另一个标签时更改标签中的图像..(例如游戏)..我有一个问题..当我编写 Thread.sleep 时,图像没有改变..请参阅代码: public cla
我正在研究多线程,我有一个关于线程 sleep 方法的问题。当我在已经处于 sleep 线程(时间 t2)中执行 sleep()(时间 t1)方法时。总 sleep 时间为 t1+t2 或 t2(如果
如果我们不向 sleep( ) 函数传递任何参数,默认 sleep 时间是多少? #include int main() { int pid,dip,cpid; pid = fork(
当我转到 asyncio 页面时,第一个示例是一个 hello world 程序。当我在 python 3.73 上运行它时,我看不出与正常的有什么不同。 谁能告诉我区别并举一个重要的例子? In [
我是一名优秀的程序员,十分优秀!