0

On my Raspberry Pi I have this code to let LEDS blink in different hertz frequencies. Everything works fine, but I can´t stop it with ctrl+C.

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
from threading import Thread

GPIO.setmode(GPIO.BOARD)
GPIO.setup(32, GPIO.IN)
    #LED Blinking Function
    def blink(port, hz):
        GPIO.setup(port, GPIO.OUT)
        pulse = 0.5/hz
        dtm = time.time()

        while True:
            dtm+= pulse
            time.sleep(dtm - time.time())

            if GPIO.input(32) == 1:

                GPIO.output(port, not GPIO.input(port))

            else:
                GPIO.output(port, GPIO.LOW)

    #to make it easier to add new LED
    def start(port, hz):
    Thread(target=blink, args=(port, hz)).start()

#to add LED insert start(GPIOport, Hz)
start(15, 2)
start(16, 2)
start(18, 2)
start(22, 2)
start(29, 2)

I have tried so much, but I can´t handle it. Do you have any ideas to solve this problem?

Developer Guy
  • 2,318
  • 6
  • 19
  • 37
Kai
  • 147
  • 1
  • 2
  • 11

2 Answers2

1

You should set your threads to daemon=True. This way, the threads will stop should the main thread ever finish (such as in a Ctrl+C situation).

At the end of your main script after you've started your threads you'll want a while threads are alive loop which waits for either a KeyboardInterrupt to shut down the main script (consequently closing threads) or the threads to close of their own accord (in some later version of code maybe).

Let me know if you need further example on how this would be written. You can see the Python documentation for how thread objects work here.

Update: You can read about stopping threads in this very useful post. It is likely to be a much more robust solution than the one I suggested.

Nebbles
  • 113
  • 7
0

Try stopping it with Ctrl+Shift+\

Developer Guy
  • 2,318
  • 6
  • 19
  • 37
Shivam Singh
  • 1,584
  • 1
  • 10
  • 9