forked from peterhinch/micropython-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathastests.py
94 lines (85 loc) · 2.63 KB
/
astests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# Test/demo programs for the aswitch module.
# Tested on Pyboard but should run on other microcontroller platforms
# running MicroPython with uasyncio library.
# Author: Peter Hinch.
# Copyright Peter Hinch 2017 Released under the MIT license.
from machine import Pin
from pyb import LED
from aswitch import Switch, Pushbutton
import uasyncio as asyncio
helptext = '''
Test using switch or pushbutton between X1 and gnd.
Ground pin X2 to terminate test.
Soft reset (ctrl-D) after each test.
'''
# Pulse an LED (coroutine)
async def pulse(led, ms):
led.on()
await asyncio.sleep_ms(ms)
led.off()
# Toggle an LED (callback)
def toggle(led):
led.toggle()
# Quit test by connecting X2 to ground
async def killer():
pin = Pin('X2', Pin.IN, Pin.PULL_UP)
while pin.value():
await asyncio.sleep_ms(50)
# Test for the Switch class passing coros
def test_sw():
print('Test of switch scheduling coroutines.')
print(helptext)
pin = Pin('X1', Pin.IN, Pin.PULL_UP)
red = LED(1)
green = LED(2)
sw = Switch(pin)
# Register coros to launch on contact close and open
sw.close_func(pulse, (green, 1000))
sw.open_func(pulse, (red, 1000))
loop = asyncio.get_event_loop()
loop.run_until_complete(killer())
# Test for the switch class with a callback
def test_swcb():
print('Test of switch executing callbacks.')
print(helptext)
pin = Pin('X1', Pin.IN, Pin.PULL_UP)
red = LED(1)
green = LED(2)
sw = Switch(pin)
# Register a coro to launch on contact close
sw.close_func(toggle, (red,))
sw.open_func(toggle, (green,))
loop = asyncio.get_event_loop()
loop.run_until_complete(killer())
# Test for the Pushbutton class (coroutines)
def test_btn():
print('Test of pushbutton scheduling coroutines.')
print(helptext)
pin = Pin('X1', Pin.IN, Pin.PULL_UP)
red = LED(1)
green = LED(2)
yellow = LED(3)
blue = LED(4)
pb = Pushbutton(pin)
pb.press_func(pulse, (red, 1000))
pb.release_func(pulse, (green, 1000))
pb.double_func(pulse, (yellow, 1000))
pb.long_func(pulse, (blue, 1000))
loop = asyncio.get_event_loop()
loop.run_until_complete(killer())
# Test for the Pushbutton class (callbacks)
def test_btncb():
print('Test of pushbutton executing callbacks.')
print(helptext)
pin = Pin('X1', Pin.IN, Pin.PULL_UP)
red = LED(1)
green = LED(2)
yellow = LED(3)
blue = LED(4)
pb = Pushbutton(pin)
pb.press_func(toggle, (red,))
pb.release_func(toggle, (green,))
pb.double_func(toggle, (yellow,))
pb.long_func(toggle, (blue,))
loop = asyncio.get_event_loop()
loop.run_until_complete(killer())