trigger event when variable equals x - python
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
python python-3.x variables raspberry-pi
add a comment |
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
python python-3.x variables raspberry-pi
There is no built in way to do that - the simplest would be to check whenever you modifycounter
whether the new value is 10 (using a simpleif
) and then you'd trigger your event. See also, e.g.: stackoverflow.com/questions/6190468/…
– UnholySheep
Jan 1 at 12:31
Thanks. I should have perhaps pointed out that I found this script here - link 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 1 at 12:54
raspberrypi.stackexchange.com might also help
– Patrick Artner
Jan 1 at 13:11
Great thanks! Yes very apt.
– Nick C
Jan 1 at 13:13
add a comment |
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
python python-3.x variables raspberry-pi
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
python python-3.x variables raspberry-pi
python python-3.x variables raspberry-pi
edited Jan 1 at 12:36
Patrick Artner
24.6k62443
24.6k62443
asked Jan 1 at 12:26
Nick CNick C
446
446
There is no built in way to do that - the simplest would be to check whenever you modifycounter
whether the new value is 10 (using a simpleif
) and then you'd trigger your event. See also, e.g.: stackoverflow.com/questions/6190468/…
– UnholySheep
Jan 1 at 12:31
Thanks. I should have perhaps pointed out that I found this script here - link 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 1 at 12:54
raspberrypi.stackexchange.com might also help
– Patrick Artner
Jan 1 at 13:11
Great thanks! Yes very apt.
– Nick C
Jan 1 at 13:13
add a comment |
There is no built in way to do that - the simplest would be to check whenever you modifycounter
whether the new value is 10 (using a simpleif
) and then you'd trigger your event. See also, e.g.: stackoverflow.com/questions/6190468/…
– UnholySheep
Jan 1 at 12:31
Thanks. I should have perhaps pointed out that I found this script here - link 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 1 at 12:54
raspberrypi.stackexchange.com might also help
– Patrick Artner
Jan 1 at 13:11
Great thanks! Yes very apt.
– Nick C
Jan 1 at 13:13
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.: stackoverflow.com/questions/6190468/…– UnholySheep
Jan 1 at 12:31
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.: stackoverflow.com/questions/6190468/…– UnholySheep
Jan 1 at 12:31
Thanks. I should have perhaps pointed out that I found this script here - link 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 1 at 12:54
Thanks. I should have perhaps pointed out that I found this script here - link 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 1 at 12:54
raspberrypi.stackexchange.com might also help
– Patrick Artner
Jan 1 at 13:11
raspberrypi.stackexchange.com might also help
– Patrick Artner
Jan 1 at 13:11
Great thanks! Yes very apt.
– Nick C
Jan 1 at 13:13
Great thanks! Yes very apt.
– Nick C
Jan 1 at 13:13
add a comment |
1 Answer
1
active
oldest
votes
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.
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53995417%2ftrigger-event-when-variable-equals-x-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
add a comment |
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.
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
add a comment |
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.
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.
answered Jan 2 at 16:37
Ondrej K.Ondrej K.
3,31671125
3,31671125
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
add a comment |
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
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] (raspberrypi.stackexchange.com/questions/92502/…). 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 2 at 21:27
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53995417%2ftrigger-event-when-variable-equals-x-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
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 simpleif
) and then you'd trigger your event. See also, e.g.: stackoverflow.com/questions/6190468/…– UnholySheep
Jan 1 at 12:31
Thanks. I should have perhaps pointed out that I found this script here - link 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 1 at 12:54
raspberrypi.stackexchange.com might also help
– Patrick Artner
Jan 1 at 13:11
Great thanks! Yes very apt.
– Nick C
Jan 1 at 13:13