这个Python中的Arduino代码是错误的,我不知道为什么

wbrvyc0a  于 2023-09-29  发布在  Python
关注(0)|答案(1)|浏览(116)

我有一个运行在Arduino板上的代码,它是用Python写的,但我不知道为什么它不工作。我希望LED自动打开和关闭(这部分是正确的),但我也希望当它打开时,它打印“LED打开”,当它关闭时,它打印“LED关闭”。但现在它只打印“led on”。代码有什么问题?

from fhict_cb_01.custom_telemetrix import CustomTelemetrix

import time

board = CustomTelemetrix()

board.set_pin_mode_digital_output(5)
def print_numbers():
    while True:  
        board.digital_write(5,1) 
        time.sleep(1) 
        board.digital_write(5,0) 
        time.sleep(1) 
        Led_state = board.digital_read(5)    
        if Led_state == 0: 
            print("led off") 
        else: 
            print("led on") 

print_numbers()
r1zhe5dt

r1zhe5dt1#

像这样的问题很容易通过检查程序的代码并查看程序的状态如何随时间变化来解决。在你的函数print_numbers()(顺便说一句,什么数字?),只有一种状态,即LED的开/关状态。
我在源代码中添加了一些非常冗长的注解。在实践中,在心理上这样做往往就足够了。

def print_numbers():
    while True:                             # loop forever
        board.digital_write(5,1)            # turn LED on
        time.sleep(1)                       # wait for one second
        board.digital_write(5,0)            # turn LED off
        time.sleep(1)                       # wait for one second
        Led_state = board.digital_read(5)   # read on/off state of LED, this will always be off because we turned it off two lines above
        if Led_state == 0:                  # print stuff
            print("led off") 
        else: 
            print("led on")                 
                                            # jump to beginning of loop, start over

使程序打印实际LED状态的一种方法是首先查询,然后将其翻转到其他状态:

def print_numbers():
    while True:
        Led_state = board.digital_read(5)
        if Led_state == 0:
            board.digital_write(5, 1)
            print("led on")                 
        else: 
            board.digital_write(5, 0)
            print("led off") 
        time.sleep(1)

它也可以在不阅读LED状态的情况下完成,保持原始的展开循环:

def print_numbers():
    while True:
        board.digital_write(5, 1)
        print("led on")                 
        time.sleep(1)
        board.digital_write(5, 0)
        print("led off")
        time.sleep(1)

相关问题