0

this is my first raspberry pi project and it’s for university. I have a led, a button a buzzer and a servo motor connected, they all work perfectly fine. The idea is, when the servo motor is moved, the LED goes on and if the LED is on for more than 5 seconds the buzzer needs to go off. For some reason, I can’t delay the sound, is there a way to delay the sound of the buzzer for 5 seconds? Any help or guidance is appreciated!

This is the code I used:

buzzer = Buzzer(18)
servo = Servo(17)
button = Button(2)
led = Led(27) 

While True:
button.wait_for_press()
led.on()
servo.max()
buzzer.on(on_time_0.5,off_time:5,n=None,background=True)
sleep(0.5)
button.wait_for_press()
buzzer.off()
led.off()
servo.min()
sleep(0.5)
1
  • Your code is incomplete, contains errors and is improperly formatted. It would not run without error. If you want help post working code, with detail of what happens. You would be better to use when_pressed and a callback. gpiozero.readthedocs.io/en/v1.6.2/….
    – Milliways
    Dec 14, 2021 at 5:51

1 Answer 1

0

There's a few ways you could do this. One is to use the signal module and set an alarm (see python docs). An alarm can trigger asynchronously after a set period of time, then call a function that checks if the led is still on and sound the buzzzer. eg.

import signal

# define alarm signal handler
def buzzer_active(signum, stackframe):
   if led.is_lit:
       buzzer.on()
       print('buzzing!')
   else:
       print('not buzzing')

# assign a callback for SIGALRM
signal.signal(signal.SIGALRM, buzzer_active)

# your program
while True:
    button.wait_for_press()
    led.on()
    servo.max()
    signal.alarm(5)  # led is on, trigger the alarm buzzer in 5 sec

# rest of your program - use signal.alarm(0) to cancel the alarm if it didn't
# trigger before the button was pressed again, but this may not be needed if the
# led is turned off as the callback will check the led state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.