我正在使用Raspberry Pi 3进行7个段显示(4个显示)记分板3。我制作了一个Python程序,该程序从数据库中读取2个数字并将它们存储在变量中,请检查如何检查那里有许多数字(因为我只能将一位数字发送到一个显示),然后将适当的信息发送到GPIO引脚。每个数字均为0.001,因此在0.004中通过所有4个。然后,它循环循环200个重复,然后再返回并检查数据库中是否进行了任何更改。
但是,虽然数据库正在重新读取它,但所有显示器都略有关闭。我想知道是否可以使用先前存储的变量继续循环(具有200个重复的循环),并且仅在数据库完成读取新信息后才与新信息重新启动。
#i have set up the database and all other important stuff outside this loop
while 1:
digitTipe = 0
digitTipe2 = 0
timer = 0 #counter for the GPIO loop
#it gets the info from db and then it lists the digits
cur.execute("SELECT gol_domaci FROM tekme ORDER BY id DESC LIMIT 0, 1")
db.commit()
home_team = cur.fetchall()
for q in home_team-:
digits= list(int(d) for d in str(q[0]))
#same but for the other team
cur.execute("SELECT gol_gosti FROM tekme ORDER BY id DESC LIMIT 0, 1")
db.commit()
guest_team = cur.fetchall()
for e in guest_team:
digit2 = list(int(d) for d in str(e[0]))
#here checks if both digits are the same (11, 22, 33...), is just one digit(3, 6, ...) or if is just a random number (12, 23, 45,...)
#based on these results the GPIO output knows how to properly send out voltage... i tried with other methods but this one works for me
if len(digit) < 2:
digitTipe = 1
else:
if digit[0] == digit[1]:
digitTipe = 2
if len(digit2) < 2:
digitTipe2 = 1
else:
if digit2[0] == digit2[1]:
digitTipe2 == 2
while timer < 200: #this is the loop that has code for GPIO pins
#("insert digit output code")
"滞后"不错,最多只能达到0.1,但它引人注目且令人讨厌,所以我的"同事"想要修复它。但是如果可能的话,我不想制作两个单独的代码文件
我为编码的质量不佳而感到抱歉。这是我在Python和总体上的第一个"真实"程序。我也很抱歉,如果我没有足够的具体,因为它也恰好是我在Stackoverflow上的第一个问题。预先感谢!
从我收集的内容中,while timer < 200: …
循环激活显示。因此,当由于cur.execute(…)
而没有执行此循环等等,依此类推,显示器将被停用。
解决方案是使用异步编程。这是一个关于该主题的好问题:python中的异步编程
这是一个从一个答案中复制和粘贴的示例(作者杰西·迪隆):
from threading import Thread
def background_stuff():
while True:
print "I am doing some stuff"
t = Thread(target=background_stuff)
t.start()
# Continue doing some other stuff now
您可以创建与background_stuff
类似的两个功能,一个功能可以处理显示,另一个可以从数据库中获取信息。然后根据这两个函数实例化两个线程,然后同时启动。所以:
# declare variables here
def handle_display():
while True:
# put here what is under the `while timer < 200: … ` loop
def fetch_from_db():
# every time timer runs out, fetch info from database
# and store in variables declared at line 1
t1 = Thread(target=handle_display)
t2 = Thread(target=fetch_from_db)
t1.start()
t2.start()