我编写了这段代码,它为我在 Raspberry pi 中的按钮数量创建了多个计时器。 我有三种类型的按钮,开始、重置和停止。 我有一个停止按钮,连接到一个紧急停止按钮,按下时会锁定。我目前有两个,它们是串联的。 (接线正确,多次测试)。当我在计时器运行期间按下其中一个 eStop 按钮时,它将暂停计时器。但是当我按下另一个 eStop 按钮时,没有任何反应,但当我释放它时会暂停。
这与去抖动有关吗?
这是我的代码,我希望当我按下一个或另一个 eStop 按钮时它会暂停所有计时器。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel
from PyQt5.QtCore import QTimer, pyqtSignal, QObject, Qt
class Timer(QWidget):
def __init__(self, parent=None):
super(Timer, self).__init__(parent)
self.time = 0
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_timer)
self.label = QLabel('00:00:00')
self.layout = QVBoxLayout()
self.layout.addWidget(self.label)
self.setLayout(self.layout)
def start(self):
self.timer.start(1000)
def stop(self):
self.timer.stop()
def reset(self):
self.time = 0
self.update_label()
def update_timer(self):
self.time += 1
self.update_label()
def update_label(self):
seconds = self.time % 60
minutes = (self.time // 60) % 60
hours = (self.time // 3600) % 24
self.label.setText('{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds))
class GPIOThread(QObject):
start_timer = pyqtSignal(int)
stop_timer = pyqtSignal(int)
reset_timer = pyqtSignal(int)
def __init__(self, start_pins, reset_pins, stop_pin, parent=None):
super(GPIOThread, self).__init__(parent)
from gpiozero import Button
self.start_buttons = [Button(pin) for pin in start_pins]
self.reset_buttons = [Button(pin) for pin in reset_pins]
self.stop_button = Button(stop_pin)
for i in range(len(start_pins)):
self.start_buttons[i].when_pressed = lambda i=i: self.start_timer.emit(i)
for i in range(len(reset_pins)):
self.reset_buttons[i].when_pressed = lambda i=i: self.reset_timer.emit(i)
#
self.stop_button.when_pressed = self.stop_timers
def stop_timers(self):
self.stop_timer.emit(-1)
class MainWindow(QWidget):
def __init__(self, start_pins, reset_pins, stop_pin, parent=None):
super(MainWindow, self).__init__(parent)
self.timers = []
for i in range(len(start_pins)):
timer = Timer()
self.timers.append(timer)
self.layout = QHBoxLayout()
for timer in self.timers:
self.layout.addWidget(timer)
self.setLayout(self.layout)
self.gpio_thread = GPIOThread(start_pins, reset_pins, stop_pin)
self.gpio_thread.start_timer.connect(self.start_timer)
self.gpio_thread.stop_timer.connect(self.stop_timer)
self.gpio_thread.reset_timer.connect(self.reset_timer)
def start_timer(self, index):
self.timers[index].start()
def stop_timer(self, index):
if index == -1:
for timer in self.timers:
timer.stop()
else:
self.timers[index].stop()
def reset_timer(self, index):
self.timers[index].reset()
self.timers[index].stop()
if __name__ == '__main__':
start_pins = [14, 15]
reset_pins = [4, 17]
stop_pin = 26
app = QApplication(sys.argv)
window = MainWindow(start_pins, reset_pins, stop_pin)
window.show()
sys.exit(app.exec_())