python - Raspberry Pi 上的 GPIO 引脚状态更改后,如何在 pygame 中更新我的显示?
问题描述
这个想法是我有几个开关连接到 Raspberry Pi 3 B+ 上的 GPIO 引脚,一旦第一个开关打开,就会出现“文本 2”。只有第一个开关打开后,才能激活第二个开关。第二个开关打开后,会出现'text 3'。只有打开第二个开关后,才能激活第三个也是最后一个开关。激活第三个开关后,出现“文本 4”。
文本以它应该的方式显示,但是文本在彼此之上不断闪烁。我怀疑这是因为我在同一个循环中有多个 pygame.display.flip() ,但我找不到解决它的方法。我基本上可以更改背景颜色并移动新文本出现的位置以“隐藏”闪烁,但我觉得好像有一个更理智的解决方案。有没有人有任何想法可以让我开始?
这是相关代码(这里不包括颜色和文本的所有常量):
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if GPIO.input(24) == 1:
window.fill(white)
color1 = white
color2 = black
color3 = white
color4 = white
window.blit(text2, (window_width/2 - 50,window_height/2 - 100))
pygame.display.flip()
if GPIO.input(18) == 0:
color3 = white
if GPIO.input(18) == 1:
window.fill(white)
color1 = white#Second puzzle GPIO
color2 = white
color3 = black
color4 = white
window.blit(text3, (window_width/2 - 50,window_height/2 - 100))
pygame.display.flip()
if GPIO.input(16) == 0:
color4 = white
if GPIO.input(16) == 1:
window.fill(white)
color1 = white
color2 = white
color3 = white
color4 = black
window.blit(text4, (window_width/2 - 50,window_height/2 - 100))
pygame.display.flip()
解决方案
正如 OP 所说,闪烁确实是由对pygame.display.flip()
每个循环的多次调用引起的。
我认为最好在循环开始时获取您的 GPIO 引脚值,然后在单个屏幕绘制代码块中显示状态:
BLACK = ( 0, 0, 0 )
myfont = pygame.font.Font( None, 16 )
text1 = myfont.render( "Unused", True, BLACK )
text2 = myfont.render( "GPIO-24", True, BLACK )
text3 = myfont.render( "GPIO-18", True, BLACK )
text4 = myfont.render( "GPIO-16", True, BLACK )
# position texts every 100 pixels
text1_rect = text1.get_rect( top_left = ( 50, 100 ) )
text2_rect = text2.get_rect( top_left = ( 150, 100 ) )
text3_rect = text3.get_rect( top_left = ( 250, 100 ) )
text4_rect = text4.get_rect( top_left = ( 350, 100 ) )
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Read GPIO Pin values
gpio_pin16 = GPIO.input( 16 )
gpio_pin18 = GPIO.input( 18 )
gpio_pin24 = GPIO.input( 24 )
# Paint the screen
window.fill(white)
if ( gpio_pin24 == 1 ):
window.blit( text2, text2_rect )
if ( gpio_pin18 == 1 ):
window.blit( text3, text3_rect )
if ( gpio_pin16 == 1 ):
window.blit( text4, text4_rect )
pygame.display.flip()
pygame.quit()
我没有完整的代码可以使用,所以我只是猜测它应该如何真正工作。您现有的标签被绘制到完全相同的位置,这就是相互遮挡的原因。
所以在上面的代码中,我们定义text2_rect
了 etc. 来正式定位文本需要绘制的位置,并保证良好的布局。如果 GPIO 引脚为高电平,则主循环绘制文本,否则将屏幕的该区域留空。目前尚不清楚颜色如何与提供的代码一起工作,所以我忽略了这一点。
0
如果您希望它们自动在屏幕上定位,您可以使用、window_width//4
、window_width//2
、3*window_width//4
等的 x 坐标。
推荐阅读
- python - 在 Heroku-16 堆栈上安装 GCC (gfortran)
- javascript - 与“扩展”游标相关的内存使用和效率与 indexedDB 中的多个事务
- php - 我无法在 django 1.11.9 中进行迁移
- java - 如何从 1jframe 链接到另一个 jframe
- javascript - 选择数组javascript的一部分
- jenkins - 压缩 Jenkins Pipeline 中的目录
- typescript - 如何使用可观察对象和/或异步生成器递归访问 Promise?
- prolog - prolog:如果两个列表相同但没有特定元素,则谓词为真
- java - 如何使用 RabbitMQ Java 从每个客户端发送/接收消息
- java - indexOf 错误地表示整数不在数组中