m.ipp m.ipp - 5 months ago 9
Ruby Question

How to set a loop to run continously without getting stuck in infinite loop?

I have some code the executes every n minutes and updates some values. I check those values with conditionals and if needed, I call a loop that makes an LED blink. That loop function looks like:

def blink_led_constant
while 1
# RPi::GPIO.set_high 18
# sleep(1)
# RPi::GPIO.set_low 18
# sleep(1)
end
end


Basically I want this LED to blink in the background until a certain condition is met. How do I set this to function to run, but also continue past the function call to reiterate my program?

Right now based on how I wrote this, if this function is called it gets stuck infinitely.

Thanks

Answer

You can use a thread to do this.

def blink_led_constant
  loop do
    #  RPi::GPIO.set_high 18
    #  sleep(1)
    #  RPi::GPIO.set_low 18
    #  sleep(1)
  end 
end

thread = Thread.new { blink_led_constant }

Then you can execute other commands while blink_led_constant runs in the background. Change the loop do to a while if you want it to break once a condition is met. Once the condition is met to stop the led from blinking call Thread.kill(thread) or thread.kill.

Comments