如何通过按下按钮停止被调用的UserDefined函数的运行?

2024-04-29 15:49:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近学习了一个关于如何用我的raspberry pi控制ws2812 LED条带的教程。该程序调用一个函数,其中彩虹颜色扫过条带。问题是,我想按下一个按钮来关闭它,但彩虹循环必须在光带关闭之前完成。我想这样,当我按下一个按钮时,色带会立即关闭

这里是我制作彩虹颜色的函数(正如你所看到的,它需要一些时间来完成)

def rainbow(strip, wait_ms=20, iterations=1):
    """Draw rainbow that fades across all pixels at once."""
    for j in range(256*iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(i, wheel((i+j) & 255))
        strip.show()
        time.sleep(wait_ms/1000.0)
if __name__ == '__main__':
    #Process arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
    args = parser.parse_args()

     "Create NeoPixel object with appropriate configuration."
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
     Intialize the library (must be called once before other functions).
    strip.begin()

    print ('Press Ctrl-C to quit.')
    if not args.clear:
        print('Use "-c" argument to clear LEDs on exit')

这里我用rainbow(strip)调用rainbow函数:

try:

    while True:
        rainbow(strip)
    if "buttonpress":
        colorWipe(strip,Color(0,0,0),10)



except KeyboardInterrupt:
    if args.clear:
        colorWipe(strip, Color(0,0,0), 10)

我想这样做,按下一个按钮,彩虹功能取消,条纹立即关闭,但现在我必须计时,以便在彩虹效果重新开始时按下按钮

它通过调用colorWipe(strip, color(0,0,0), 10)来关闭


Tags: 函数parserledif颜色args按钮ms