From 9fbed050ce74194c39dee4cf3dfb2c8cd380c2f2 Mon Sep 17 00:00:00 2001 From: Andrew Scheller Date: Wed, 21 Sep 2016 16:16:42 +0100 Subject: [PATCH] Add a new alternating_values SourceTool --- docs/api_tools.rst | 2 ++ gpiozero/tools.py | 23 +++++++++++++++++++++++ tests/test_tools.py | 5 +++++ 3 files changed, 30 insertions(+) diff --git a/docs/api_tools.rst b/docs/api_tools.rst index 69b2a60..6f23668 100644 --- a/docs/api_tools.rst +++ b/docs/api_tools.rst @@ -69,6 +69,8 @@ Combining sources Artificial sources ================== +.. autofunction:: alternating_values + .. autofunction:: cos_values .. autofunction:: random_values diff --git a/gpiozero/tools.py b/gpiozero/tools.py index bf3329f..1613b7a 100644 --- a/gpiozero/tools.py +++ b/gpiozero/tools.py @@ -576,3 +576,26 @@ def cos_values(period=360): angles = (2 * pi * i / period for i in range(period)) for a in cycle(angles): yield cos(a) + + +def alternating_values(initial_value=False): + """ + Provides an infinite source of values alternating between ``True`` and + ``False``, starting wth *initial_value* (which defaults to ``False``). For + example, to produce a flashing LED:: + + from gpiozero import LED + from gpiozero.tools import alternating_values + from signal import pause + + red = LED(2) + + red.source_delay = 0.5 + red.source = alternating_values() + + pause() + """ + value = initial_value + while True: + yield value + value = not value diff --git a/tests/test_tools.py b/tests/test_tools.py index a06109e..35f4316 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -10,6 +10,7 @@ str = type('') import pytest from math import sin, cos, radians from time import time +from itertools import islice from gpiozero.tools import * try: @@ -227,6 +228,10 @@ def test_post_periodic_filtered(): assert list(post_periodic_filtered((1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 1, 2)) == [1, 4, 7, 10] assert list(post_periodic_filtered((1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 2, 1)) == [1, 2, 4, 5, 7, 8, 10] +def test_alternating_values(): + assert list(islice(alternating_values(), 5)) == [False, True, False, True, False] + assert list(islice(alternating_values(True), 5)) == [True, False, True, False, True] + def test_random_values(): for _, v in zip(range(1000), random_values()): assert 0 <= v <= 1