mirror of
				https://github.com/KevinMidboe/python-gpiozero.git
				synced 2025-10-29 17:50:37 +00:00 
			
		
		
		
	Merge pull request #460 from lurch/alternating_values
Add a new alternating_values SourceTool
This commit is contained in:
		| @@ -69,6 +69,8 @@ Combining sources | ||||
| Artificial sources | ||||
| ================== | ||||
|  | ||||
| .. autofunction:: alternating_values | ||||
|  | ||||
| .. autofunction:: cos_values | ||||
|  | ||||
| .. autofunction:: random_values | ||||
|   | ||||
| @@ -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 | ||||
|   | ||||
| @@ -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 | ||||
|   | ||||
		Reference in New Issue
	
	Block a user