# WORKING CODE (SOLUTION) ![✅]()
Code:
import RPi.GPIO as GPIOimport timefrom samplebase import SampleBasefrom rgbmatrix import graphicsimport threadingBUTTON_GPIO = 0 # pin 27BOUNCE_DELAY = 0.2 # secondsclass ButtonClickCounter(SampleBase): def __init__(self, *args, **kwargs): super(ButtonClickCounter, self).__init__(*args, **kwargs) # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.count = 0 self.lock = threading.Lock() self.font = graphics.Font() self.font.LoadFont("../../../fonts/6x10.bdf") # use a small readable font self.color = graphics.Color(255, 255, 255) def button_watcher(self): was_pressed = False while True: if GPIO.input(BUTTON_GPIO) == GPIO.LOW and not was_pressed: was_pressed = True with self.lock: self.count += 1 print(f"Count is now {self.count}") time.sleep(BOUNCE_DELAY) elif GPIO.input(BUTTON_GPIO) == GPIO.HIGH: was_pressed = False time.sleep(0.01) def run(self): canvas = self.matrix.CreateFrameCanvas() # Start the button thread threading.Thread(target=self.button_watcher, daemon=True).start() while True: canvas.Clear() with self.lock: text = f"Clicks: {self.count}" graphics.DrawText(canvas, self.font, 1, 10, self.color, text) canvas = self.matrix.SwapOnVSync(canvas) time.sleep(0.1) def __del__(self): GPIO.cleanup()if __name__ == "__main__": app = ButtonClickCounter() if not app.process(): app.print_help()
Statistics: Posted by luckyMERLO — Fri Apr 11, 2025 8:15 am