Kalman
Posts: 31
Joined: Mon Apr 22, 2013 3:38 pm
Location: Sweden

Timers counting seconds

Sun Sep 25, 2016 2:05 pm

Hallo!
Programing a heater system for my home, I need some timers.
They shall count seconds, and after say 20 seconds passing send a signal to a GPIO pin. , then resetting the timer and start counting again.
An other timer compare time passing and if nothing happend during a specific time them do something.
Something like in Quasy program lines would be:

If timer (a) > 30
indent Gpio(23) = high


But how do I fix the timers themselves? Is there possible a downloadable programmodul/library?
I use the RaspPi vers 2 B and Python 3.xx
Appriciate any suggestions and Thanks in advance
Kalman

MarcScott
Raspberry Pi Foundation Employee & Forum Moderator
Raspberry Pi Foundation Employee & Forum Moderator
Posts: 81
Joined: Sat Aug 08, 2015 11:30 am

Re: Timers counting seconds

Mon Sep 26, 2016 6:46 am

Not sure if this is what you want - but you can make a basic timer using the time module

Code: Select all

import time
timer_a = time.time()
timer_b = time.time()
while True:
    if time.time() - timer_a > 20:
        timer_a = time.time()
        print('20 seconds')
    if time.time() - timer_b > 30:
        timer_b = time.time()
        #do something else

Kalman
Posts: 31
Joined: Mon Apr 22, 2013 3:38 pm
Location: Sweden

Re: Timers counting seconds

Tue Sep 27, 2016 3:17 pm

Thank You Marc
Yes, something like that. I also tested a similar smal prog but it didn´t work properly.
I shall test your lines.
But...there is a consequence question.
My program has a "big" while true loop. Everithing runs inside that loop.
when coming to the part where i check the if 20 seconds has passed, not time critical process, I must reset the "timer", and start it over again at the same time. I´m thinking a stopwatch.

And I need 4-5 processes/things to be "timed".
Call them timer_c; timer_d ; and so on?.
timer_c = time.time() and so on?

But how to reset? Or is the "time.time" running from starting the Pie so it is actually uppdated all the time? Is the time.time running, up-counting endless?
Can You explain further?

scotty101
Posts: 3735
Joined: Fri Jun 08, 2012 6:03 pm

Re: Timers counting seconds

Tue Sep 27, 2016 3:40 pm

time.time() returns the current system time which is constantly incrementing.

If you want to wait for 20 seconds then you set a value (timer_a) to the current time (time.time()) + 20.

If in your while loop timer_a is greater than the current time then 20 seconds has expired.

If you need to reset timer_a then you set it back to time.time() + 20.

I had written a simple timer class for this type of thing, You can find it here

Reposted here

Code: Select all

#We only need to import the time function
from time import time

class Timer:
    def __init__(self,timer_period):
        """Initialise the timer
        >>> t = Timer(2)"""
        self.timer_period = timer_period
        self.update_timer()
    def update_timer(self):
        """Resets the timer to expire after <timer_period> seconds."""
        self.last_time = time()
        self.timer_expires = self.last_time + self.timer_period
    def has_timer_expired(self):
        """Call this function to check if the time has elapsed
        It will return 1 when time is up and reset the timer."""
        if time() > self.timer_expires:
            self.update_timer()
            return 1
        else:
            return 0

if __name__ == '__main__':
    # Setup a timer with a 2 second period
    t = Timer(2)

    while True:
        if t.has_timer_expired():
            #If the timer has expired, print Hello World.
            print("Hello World")
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
Douglas6
Posts: 4778
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Timers counting seconds

Tue Sep 27, 2016 4:23 pm

Python's timer objects might be useful as well in some circumstances: https://docs.python.org/3.4/library/thr ... er-objects

Kalman
Posts: 31
Joined: Mon Apr 22, 2013 3:38 pm
Location: Sweden

Re: Timers counting seconds

Tue Sep 27, 2016 7:16 pm

Thank You all people!
Pleas give some days/week to test and check out.
Thank You this far.
:)

tom.slick
Posts: 190
Joined: Wed Jan 06, 2016 9:23 pm

Re: Timers counting seconds

Tue Sep 27, 2016 9:31 pm

This might be a little overkill, but should do exactly what you want.

Code: Select all

#!/usr/bin/env python

import time


# for convenience
hours = "h"
minutes = "m"
seconds = "s"

h = "h"
m = "m"
s = "s"


class SimpleTimer(object):
    """A simple timer
    
    Provides a simple timer to keep track of elapsed time.  It has methods to
    start, stop, get elapsed time, pause, unpause, reset and running status.
    
    example usage
    Create your timer
    >>> st = SimpleTimer()
    
    start your timer
    >>> st.start()
    
    get the elapsed time
    >>> st.elapsed()
    (0, 0, 8.17)
    >>> st.elapsed("seconds")
    8.17
    >>> st.elapsed("minutes")
    0
    >>> st.elapsed("hours")
    0
    
    check timer status
    >>> st.is_running()
    True
    >>> st.pause()
    >>> st.is_running()
    False
    """

    def __init__(self):
        self._hours = 0
        self._minutes = 0
        self._seconds = 0
        self._time = -1
        self._running = False
        self._paused = False

    def start(self):
        """Start the timer"""
        if not self._running and self._time < 0:
            self._hours = 0
            self._minutes = 0
            self._seconds = 0
            self._running = True
            self._time = time.time()

    def stop(self):
        """Stop the timer"""
        if self._running:
            self._minutes, self._seconds = divmod(time.time() - self._time, 60)
            self._hours, self._minutes = divmod(self._minutes, 60)
        self._running = False
        self._time = -1

    def reset(self):
        """Reset and restart the timer"""
        self._hours = 0
        self._minutes = 0
        self._seconds = 0
        self._running = True
        self._time = time.time()

    def elapsed(self, hms=None):
        """Return the elapsed time of the timer
        
        :param hms: string h, m, s for hours, minutes, seconds
                    defauts to None for all
        :type hms: str

        :return: hours, minutes, seconds
        :rtype: tuple / int / int / float
        """
        if self._running:
            self._minutes, self._seconds = divmod(time.time() - self._time, 60)
            self._hours, self._minutes = divmod(self._minutes, 60)
 
        if hms is not None:
            if hms.lower().startswith("h"):
                return int(self._hours)
            elif hms.lower().startswith("m"):
                return int(self._minutes)
            elif hms.lower().startswith("s"):
                return float("%.2f" % self._seconds)
        
        return int(self._hours), int(self._minutes), float("%.2f" % self._seconds)

    def pause(self):
        """Pause the timer"""
        if self._running and not self._paused:
            self._paused = True
            self._running = False
            self._time = time.time() - self._time
            self._minutes, self._seconds = divmod(self._time, 60)
            self._hours, self._minutes = divmod(self._minutes, 60)

    def unpause(self):
        """Unpause the timer"""
        if self._paused and self._time != -1:
            self._paused = False
            self._running = True
            self._time = time.time() - self._time

    def is_running(self):
        """Is the timer running
        
        Returns the status of timer
        
        :return: self._running
        :rtype: boolean

        """
        return self._running

    def is_paused(self):
        """Is the timer paused
        
        Returns the status of timer
        
        :return: self._paused
        :rtype: boolean

        """
        return self._paused


if __name__ == '__main__':
    st1 = SimpleTimer()
    st2 = SimpleTimer()
    st1.start()
    r = False
    p = False
    l = False
    
    while True:
        print(st1.elapsed(), "is running", st1.is_running(), "is paused", st1.is_paused())
        print(st2.elapsed(), "is running", st2.is_running(), "is paused", st2.is_paused())
        print("")
        time.sleep(1)
        
        if st1.elapsed(s) >= 5 and not r:
            print(st1.elapsed(), "is running", st1.is_running(), "is paused", st1.is_paused())
            print(st2.elapsed(), "is running", st2.is_running(), "is paused", st2.is_paused())
            print("over 5 seconds has passed")
            print("reset timer")
            st1.reset()
            r = True
            
        if st1.elapsed(s) >= 10 and not p:
            print(st1.elapsed(), "is running", st1.is_running(), "is paused", st1.is_paused())
            print(st2.elapsed(), "is running", st2.is_running(), "is paused", st2.is_paused())
            print("over 10 seconds has passed")
            print("pausing timer 1")
            print("starting timer 2")
            st2.start()
            st1.pause()
            p = True
             
        if st2.elapsed(s) >= 10 and not l:
            print(st1.elapsed(), "is running", st1.is_running(), "is paused", st1.is_paused())
            print(st2.elapsed(), "is running", st2.is_running(), "is paused", st2.is_paused())
            print("unpause timer 1")
            print("stop timer 2")
            st1.unpause()
            st2.stop()
            l = True
            
        if st1.elapsed(s) >= 15 and l:
            print(st1.elapsed(), "is running", st1.is_running(), "is paused", st1.is_paused())
            print(st2.elapsed(), "is running", st2.is_running(), "is paused", st2.is_paused())
            print("finished")
            st1.stop()
            break

Kalman
Posts: 31
Joined: Mon Apr 22, 2013 3:38 pm
Location: Sweden

Re: Timers counting seconds

Tue Nov 01, 2016 11:52 am

Thank You All.
It works.
And a friend of my mine wrote a small object/program/modul what so ever, and I can load it and number t(1), t(2) and so on.
But please don´t ask med how it works and I have not seen it/read it yet.
I can upload it later when I have it in my computer and tested.
Thanks again.

Return to “Python”