简体   繁体   English

如何在不使用睡眠的情况下闪烁 LED?

[英]how to blink a LED without using a sleep?

I am using motion sensor when the motion sensor is detected I wan to turn ON the LED and buzzer at the same time.当检测到运动传感器时,我正在使用运动传感器 我想同时打开 LED 和蜂鸣器。 The buzzer which I am using is a passive buzzer.我使用的蜂鸣器是无源蜂鸣器。 How can I Turn ON LED and buzzer at the same time when motion sensor detect without using sleep().如何在不使用 sleep() 的情况下在运动传感器检测到时同时打开 LED 和蜂鸣器。

import RPi.GPIO as GPIO
from time import sleep

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT) # LED PIN
GPIO.setup(27, GPIO.OUT) # buzzer PIN

def TURN_ON():          
    GPIO.output(17, GPIO.HIGH)
    GPIO.setup(27, GPIO.HIGH)
    print("LED ON and BUZZER ON")    
    sleep(5)
    GPIO.output(17, GPIO.LOW)
    GPIO.setup(27, GPIO.LOW)
    print("LED OFF and BUZZER OFF")

I'm not sure if your environment supports threading, but it probably does.我不确定您的环境是否支持线程,但它可能支持。

This article is a great introduction to threading in python .这篇文章是python 中对线程的一个很好的介绍

Here is a really quick and dirty example of what you are trying to do:这是您正在尝试做的一个非常快速和肮脏的例子:

def led_on():
    GPIO.output(17, GPIO.HIGH)

def buzz_on():
    GPIO.setup(27, GPIO.HIGH)

def delay():
    sleep(5)


def main():
    led_thread = threading.Thread(target=led_on)
    buzz_thread = theading.Thread(target=buzz_on)
    delay_thread = threading.Threading(target=delay)

    all_threads = [led_thread, buzz_thread, delay_thread]

    for thread in all_threads:
        thread.start()

    # at this point, all three functions will be running parallel

    for thread in all_threads:
        thread.join()

    # at this point, we have waited for all three threads to complete
    # the sleep 5 should be the longest running one

The above is a very simplistic example of how to accomplish your question.以上是如何完成您的问题的一个非常简单的示例。 There are many ways it can be improved.有很多方法可以改进它。 For instance, you can pass parameters/args to the thread constructor and those could be used to set the pin # (avoiding the need for two functions for _on).例如,您可以将参数/args 传递给线程构造函数,这些可用于设置引脚 #(避免 _on 需要两个函数)。

This should put you on the right track.这应该让你走上正轨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM