Add a new alternating_values SourceTool

This commit is contained in:
Andrew Scheller
2016-09-21 16:16:42 +01:00
parent f607a27c79
commit 9fbed050ce
3 changed files with 30 additions and 0 deletions

View File

@@ -69,6 +69,8 @@ Combining sources
Artificial sources
==================
.. autofunction:: alternating_values
.. autofunction:: cos_values
.. autofunction:: random_values

View File

@@ -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

View File

@@ -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