Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Count Button Press
#1
Hi , hope all is good. I'm trying to put together a project to learn python and raspberry pi and have looked at counting how many times a button is pressed in an hour. Just now i'm just trying to out put to the screen , next to excel, then try to send via a pi to a network location.

The code i've got now i though worked , but now realise that there's a bug and cant seem to reset the minute properly.The program counts the number of button presses in an hour.
What i've noticed is that the last button for example if i press the button
say 6 times in minute 23, then dont register another button press for
say 3 mins, then the next button press is registered as minute 23 instead of minute
26. Could someone have a look please and see where the reset should be to close the count of that minute and be ready to count whenever another press occurs. Any help would be greatly appreciated for what is hopefully my new hobby. thanks

import time

# Initialize a dictionary to store button counts
button_counts = {}

# Initialize the current hour
current_hour = None

while True:
    # Get the current time
    now = time.localtime()
    hour = now.tm_hour
    mins = now.tm_min #added for mins

    print(mins)    #added for mins

    # Check if a new min has started
   # if min != current_hour: added
    if mins != current_hour:
        # Print the counts for the previous hour
        if current_hour is not None:
            print(f"min {current_hour}:") #added to view minute
            for button, count in button_counts.items():
                print(f"Button {button}: {count} presses")
            print("\n")

        # Reset counts for the new min
        button_counts = {}
        current_hour = mins

    # Simulate button press ()
    button = input("Enter button number (1-5): ")
    if button.isdigit():
        button = int(button)
        button_counts.setdefault(button, 0)
        button_counts[button] += 1
    else:
        print("Invalid input. Please enter a number between 1 and 5.")
Reply
#2
You need to keep a list of times when the button was pressed. Each time you compute the clicks per hour you remove any clicks that are more than an hour old. This is an example using tkinter to have a button to press. I changed to clicks per minute so I wouldn't have to wait an hour to see the old clicks being removed.
import tkinter as tk
from datetime import datetime, timedelta


class CounterWindow(tk.Tk):

    def __init__(self):
        super().__init__()
        button = tk.Button(self, text="Push Me", command=self._button_clicked)
        label = tk.Label(self, text="Button clicks per minute:", anchor="e")
        self.tics_per_hour = tk.IntVar(self, 0)
        display = tk.Label(self, textvariable=self.tics_per_hour, width=6, anchor="w")
        label.grid(row=0, column=0, padx=(10, 5), pady=10, sticky="e")
        display.grid(row=0, column=1, padx=(0, 10), pady=10, sticky="w")
        button.grid(row=1, column=0, columnspan=2, padx=10, pady=(0, 10), sticky="news")

        self._clicks = []
        self._periodic_update()

    def _button_clicked(self):
        self._clicks.append(datetime.now())
        self._update_display()

    def _update_display(self):
        start = datetime.now() - timedelta(minutes=1)
        while self._clicks and start > self._clicks[0]:
            self._clicks.pop(0)
        self.tics_per_hour.set(len(self._clicks))

    def _periodic_update(self):
        self._update_display()
        self.after(1000, self._periodic_update)


CounterWindow().mainloop()
chizzy101010 likes this post
Reply
#3
Thanks for the reply deanhystad it was more than i was expecting, i'll try and incorporate what you have with my code to try and understand it better.

thanks again
Reply
#4
The tricky part is periodically calling a function, but I believe there are timers in raspberry pi that you can configure to call a function (Timer.PERIODIC). The timer can call the _update_display function directly. The _periodic_update() function in my example was required because tkinter doesn't have anything as nice as Timer.

You should be able to hook the button directly to the _button_clicked function (button.when_pressed = _button_clicked).

I wrote my code as a class, but it can be functions.
import tkinter as tk
from datetime import datetime, timedelta


def update_display():
    start = datetime.now() - timedelta(minutes=1)
    while clicks and start > clicks[0]:
        clicks.pop(0)
    tics_per_hour.set(len(clicks))


def button_clicked():
    clicks.append(datetime.now())
    update_display()


def periodic_update():
    update_display()
    root.after(1000, periodic_update)


root = tk.Tk()
button = tk.Button(root, text="Push Me", command=button_clicked)
label = tk.Label(root, text="Button clicks per minute:", anchor="e")
tics_per_hour = tk.IntVar(root, 0)
display = tk.Label(root, textvariable=tics_per_hour, width=6, anchor="w")
label.grid(row=0, column=0, padx=(10, 5), pady=10, sticky="e")
display.grid(row=0, column=1, padx=(0, 10), pady=10, sticky="w")
button.grid(row=1, column=0, columnspan=2, padx=10, pady=(0, 10), sticky="news")
clicks = []
periodic_update()
root.mainloop()
Nowhere in your code can you have this:
while True:
Loops should be rare in raspberry pi code.
chizzy101010 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,518 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  How to break out of a for loop on button press? philipbergwerf 6 2,018 Oct-06-2022, 03:12 PM
Last Post: philipbergwerf
  tkinter auto press button kucingkembar 2 3,453 Dec-24-2021, 01:23 PM
Last Post: kucingkembar
  Count to movement according to the time pressed button noartist 1 2,619 Feb-27-2019, 01:33 PM
Last Post: noartist
  Conditional Button Press Raudert 8 21,993 Mar-17-2017, 07:32 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020