-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsensor-drive-servo.py
More file actions
executable file
·67 lines (53 loc) · 1.52 KB
/
Copy pathsensor-drive-servo.py
File metadata and controls
executable file
·67 lines (53 loc) · 1.52 KB
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
import asyncio
import analogio
import board
import pwmio
from adafruit_motor import servo
from varspeed_async import Vspeed, map_range
state = {}
SERVO_MIN = 0
SERVO_MAX = 180
SENSOR_MIN = 0
SENSOR_MAX = 65535
POLL_INTERVAL = 0.05
RUN_TIME = 30
async def init():
print("starting...")
state["analog_in"] = analogio.AnalogIn(board.A0)
state["pwm"] = pwmio.PWMOut(board.D13, duty_cycle=2**15, frequency=50)
state["servo"] = servo.Servo(state["pwm"])
state["servo"].angle = SERVO_MIN
state["sensor_value"] = 0
async def watch_sensor(name, delay):
try:
while True:
value = state["analog_in"].value
state["sensor_value"] = map_range(
value, SENSOR_MIN, SENSOR_MAX, SERVO_MIN, SERVO_MAX, result="int"
)
await asyncio.sleep(delay)
finally:
print(name, "done")
async def move_servo(name, delay):
try:
while True:
value = state["sensor_value"]
state["servo"].angle = value
print(name, value)
await asyncio.sleep(delay)
finally:
print(name, "done")
async def main():
await init()
task1 = asyncio.create_task(watch_sensor("sensor", POLL_INTERVAL))
task2 = asyncio.create_task(move_servo("servo", POLL_INTERVAL))
try:
await asyncio.sleep(RUN_TIME)
finally:
print("cancelling")
task1.cancel()
task2.cancel()
await asyncio.sleep(0)
state["pwm"].deinit()
state["analog_in"].deinit()
asyncio.run(main())