I designed a form in qtdesigner. It has 'on' and 'off' buttons. On button should start to blink led and off button should stop it.So, If the time.sleep duration is short there is no problem but when i write 10 seconds for sleep it doesn't stop instantly when i click on the off button. Program waits 10 seconds to stop Led blinking. So how can time.sleep be interrupted?
import time
import threading
import RPi.GPIO as GPIO
import sys
from time import sleep
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QLabel
from PyQt5 import QtCore, QtGui, QtWidgets
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
switch = True
def blink(self):
def run():
while (switch == True):
print('BLINK...BLINK...')
GPIO.output(17, GPIO.HIGH)
time.sleep(10.0)
GPIO.output(17, GPIO.LOW)
time.sleep(10.0)
if switch == False:
break
thread = threading.Thread(target=run)
thread.start()
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.pshbttn1 = QtWidgets.QPushButton(Form)
self.pshbttn1.setGeometry(QtCore.QRect(60, 170, 125, 50))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.pshbttn1.setFont(font)
self.pshbttn1.setObjectName("pshbttn1")
self.pshbttn1.clicked.connect(self.switchon)
self.pshbttn2 = QtWidgets.QPushButton(Form)
self.pshbttn2.setGeometry(QtCore.QRect(220, 170, 125, 50))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.pshbttn2.setFont(font)
self.pshbttn2.setObjectName("pshbttn2")
self.pshbttn2.clicked.connect(self.switchoff)
self.pshbttn3 = QtWidgets.QPushButton(Form)
self.pshbttn3.setGeometry(QtCore.QRect(140, 230, 125, 50))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.pshbttn3.setFont(font)
self.pshbttn3.setObjectName("pshbttn3")
self.pshbttn3.clicked.connect(app.exit)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(80, 80, 251, 51))
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "LED"))
self.pshbttn1.setText(_translate("Form", "ON"))
self.pshbttn2.setText(_translate("Form", "OFF"))
self.pshbttn3.setText(_translate("Form", "EXIT"))
self.label.setText(_translate("Form", "LED\'i açmak için butonları kullanın"))
def switchon(self):
global switch
switch = True
print ('switch on')
blink(self)
def switchoff(self):
print ('switch off')
global switch
switch = False
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Form()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())