Skip to content

Instantly share code, notes, and snippets.

@wolf0403
Created October 3, 2014 01:05
Show Gist options
  • Save wolf0403/f77d927ca62895057afb to your computer and use it in GitHub Desktop.
Save wolf0403/f77d927ca62895057afb to your computer and use it in GitHub Desktop.
Schmitt trigger in python coroutines
from __future__ import print_function
def schmitt_trigger(lo, hi, cb, value):
"""http://en.wikipedia.org/wiki/Schmitt_trigger"""
while True:
newvalue = (yield value)
if newvalue is None:
raise StopIteration()
if newvalue >= hi and value < hi:
cb(hi, newvalue, 'to-hi')
elif newvalue <= lo and value > lo:
cb(lo, newvalue, 'to-lo')
value = newvalue
def test():
i = [1, 2, 3, 4, 5, 4, 2, 6, 3]
r = []
def cb(*a):
signal, value = a[:2]
r.append(value)
pass
lo = 2
hi = 5
g = schmitt_trigger(lo, hi, cb, 0)
g.next()
for x in i:
g.send(x)
assert r == [5, 2, 6], str(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment