Exception on python code on pi doesn't work with threads

21 views Asked by At

I am trying to create an server where you can put on an led remotly and with a button on a pi. the code is working fine but I get an warning that the threads don't close properly and I think the exception is not working because the print won't show up after closing the program

import socket
import time
import RPi.GPIO as GPIO
import threading

event = threading.Event()
GPIO.setmode(GPIO.BCM)

ledsWithState = [       [21     ],
                                [False  ]]
for led in ledsWithState[0]:
        GPIO.setup(led, GPIO.OUT)
        GPIO.output(led, False)

def server():
        bufferSize = 1024
        serverIP = '192.168.2.5'
        serverPort = 9999
        RPIServer = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        RPIServer.bind((serverIP, serverPort))
        print("Server ready")
        try:
                while True:
                        cmd,adress = RPIServer.recvfrom(bufferSize)
                        cmd = cmd.decode('utf-8')
                        print("test")
                        print(cmd)
                        cmd.split("<")[1]
                        cmd.split(">")[0]
                        if cmd == "0":
                                changeLed(0)
                       if event.is_set():
                                break
        except KeyboardInterrupt:
                event.set()
                serverThread.join()
                readBtnThread.join()
                GPIO.cleanup()
                print("test")
def readBtn():
        btn = 20
        toggleBtn = 1
        GPIO.setup(btn, GPIO.IN,pull_up_down=GPIO.PUD_UP)
        try:
                while True:
                        readVal = GPIO.input(btn)
                        if readVal != toggleBtn and toggleBtn == 0:
                                changeLed(0)
                        toggleBtn = readVal
                        if event.is_set():
                                break
        except KeyboardInterrupt:
                event.set()
                serverThread.join()
                readBtnThread.join()
                GPIO.cleanup()
                print("test")
def changeLed(id):
        ledsWithState[1][id] = not ledsWithState[1][id]
        GPIO.output(ledsWithState[0][id], ledsWithState[1][id])

serverThread = threading.Thread(target=server)
readBtnThread = threading.Thread(target=readBtn)
serverThread.start()
readBtnThread.start()

I tried to do an try and except when starting the thread but that didn't work and then I made the try and except in each thread but I now still got the same problem

0

There are 0 answers