3

I have the following script which increases the counter every time a button is pressed. When the counter reaches a certain number i.e. 10 lets say I want an event to trigger.

from RPi import GPIO
from time import sleep

clk = 25
dt = 8

GPIO.setmode(GPIO.BCM)
GPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

counter = 0
clkLastState = GPIO.input(clk)

try:
        while True:
                clkState = GPIO.input(clk)
                dtState = GPIO.input(dt)
                if clkState != clkLastState:
                        if dtState != clkState:
                                counter += 1
                        else:
                                counter -= 1
                        print counter
                clkLastState = clkState
                sleep(0.01)
finally:
                GPIO.cleanup()

For the purposes of an example script it might be easiest just to get it to print something on reaching the required number i.e. 'target reached'.

This question relates to an earlier post of mine here - rotary encoder script for raspberry pi using python. Rather than add to or amend that question I thought it better to break down the problem for the purposes of understanding the various components.

Many thanks

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Nick C
  • 79
  • 8
  • There is no built in way to do that - the simplest would be to check whenever you modify `counter` whether the new value is 10 (using a simple `if`) and then you'd trigger your event. See also, e.g.: https://stackoverflow.com/questions/6190468/how-to-trigger-function-on-value-change – UnholySheep Jan 01 '19 at 12:31
  • Thanks. I should have perhaps pointed out that I found this script here - [link](https://www.modmypi.com/blog/how-to-use-a-rotary-encoder-with-the-raspberry-pi) and whilst it works as far as counting goes I don't really know how to modify it in order to get it to do what I want. Perhaps I should post on that site instead as it may be more conducive for beginners like myself anyway. – Nick C Jan 01 '19 at 12:54
  • https://raspberrypi.stackexchange.com might also help – Patrick Artner Jan 01 '19 at 13:11
  • Great thanks! Yes very apt. – Nick C Jan 01 '19 at 13:13

1 Answers1

1

If you wanted to perform a (conditional) action on assignment to a value, you'd want it to be an object attribute for which you can hijack the assignment to. Overload __setattr__ method or use a property. For instance:

class C:
    def __init__(self, trigger, init_val=0):
        self._v = init_val
        self.trigger = trigger

    @property
    def v(self):
        return self._v

    @v.setter
    def v(self, value):
        if value == self.trigger:
            print("Trigger {} hit, perform some action.".format(value))
        else:
            print("Nothing to do for {}".format(value))
        self._v = value

c = C(10)
while c.v < 12:  # Go couple turns past the "event" to see its effect
    c.v += 1

I suspect what you really are after though in these two questions is to run both loops so that you can keep counting switch events and to control spinning of the motor until latter is to stop after reaching a threshold in the former. There are more ways of achieving this, for instance threads come to mind. In the following example I've let the counter run in a separate thread and have the motor loop check how far did the counter progress:

from threading import Thread
from time import sleep

class Counter(Thread):
    def __init__(self, limit):
        self.value = 0
        self.limit = limit
        super().__init__()

    def run(self):
        while self.value < self.limit:
            # We'd be acquiring and accumulating actual values here         
            sleep(1)
            self.value += 1
            print("Counter now at {}".format(self.value))

counter = Counter(10)
counter.start()
while counter.value < counter.limit:
    print("Spinning motor")
    sleep(0.5)  # do actual work here
print("Stop motor")

You can combine both examples as well as run also/or motor control in its own thread. However, if both polling switch and spinning motor happen at the same frequency, it would be much simpler just to keep count and compare its value against limit within single loop. In case the motor gets started by one action and needs to be stop by another action when the limit has been reached, Just start, loop over the switch retrieval and stop it once that loop finishes.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
  • Many thanks for the detailed response. I did actually find the solution to what I wanted to achieve via the dedicated raspberry pi stack exchange forum as suggested but Patrick earlier. The link to this is here - [link] (https://raspberrypi.stackexchange.com/questions/92502/read-variable-and-trigger-event-python). That said I accepted your answer on the basis of its thoroughness. I will also bear it mind as an alternative solution. – Nick C Jan 02 '19 at 21:27