1
|
|
|
import logging |
2
|
|
|
from itertools import cycle |
3
|
|
|
from curio import sleep |
4
|
|
|
from bricknil import attach, start |
5
|
|
|
from bricknil.hub import PoweredUpHub |
6
|
|
|
from bricknil.sensor import TrainMotor, VisionSensor, Button, LED |
7
|
|
|
from bricknil.process import Process |
8
|
|
|
from bricknil.const import Color |
9
|
|
|
|
10
|
|
|
@attach(Button, name='train_btn', capabilities=['sense_press']) |
11
|
|
|
@attach(LED, name='train_led') |
12
|
|
|
@attach(VisionSensor, name='train_sensor', capabilities=['sense_count', 'sense_distance']) |
13
|
|
|
@attach(TrainMotor, name='motor') |
14
|
|
|
class Train(PoweredUpHub): |
15
|
|
|
|
16
|
|
|
async def train_btn_change(self): |
17
|
|
|
self.message_info(f'train button push {self.train_btn.value}') |
18
|
|
|
btn = self.train_btn.value[Button.capability.sense_press] |
19
|
|
|
if btn == 1: |
20
|
|
|
# Pushed! |
21
|
|
|
self.go = True |
22
|
|
|
|
23
|
|
|
|
24
|
|
View Code Duplication |
async def train_sensor_change(self): |
|
|
|
|
25
|
|
|
self.message_info(f'Train sensor value change {self.train_sensor.value}') |
26
|
|
|
distance = self.train_sensor.value[VisionSensor.capability.sense_distance] |
27
|
|
|
count = self.train_sensor.value[VisionSensor.capability.sense_count] |
28
|
|
|
|
29
|
|
|
if count > 3: |
30
|
|
|
# Wave your hand more than three times in front of the sensor and the program ends |
31
|
|
|
self.keep_running = False |
32
|
|
|
|
33
|
|
|
# The closer your hand gets to the sensor, the faster the motor runs |
34
|
|
|
self.motor_speed = (10-distance)*10 |
35
|
|
|
|
36
|
|
|
# Flag a change |
37
|
|
|
self.sensor_change = True |
38
|
|
|
|
39
|
|
|
async def run(self): |
40
|
|
|
self.message_info("Running") |
41
|
|
|
self.motor_speed = 0 |
42
|
|
|
self.keep_running = True |
43
|
|
|
self.sensor_change = False |
44
|
|
|
self.go = False |
45
|
|
|
|
46
|
|
|
# Blink the color from purple and yellow |
47
|
|
|
colors = cycle([Color.purple, Color.yellow]) |
48
|
|
|
while not self.go: # Wait until the hub button is pushed |
49
|
|
|
await self.train_led.set_color(next(colors)) |
50
|
|
|
await sleep(1) |
51
|
|
|
|
52
|
|
|
colors = cycle([Color.green, Color.orange]) |
53
|
|
|
# Ready to go, let's change the color to green! |
54
|
|
|
while self.keep_running: |
55
|
|
|
if self.sensor_change: |
56
|
|
|
await self.train_led.set_color(next(colors)) |
57
|
|
|
await self.motor.ramp_speed(self.motor_speed, 900) # Ramp to new speed in 0.9 seconds |
58
|
|
|
self.sensor_change = False |
59
|
|
|
await sleep(1) |
60
|
|
|
await self.train_led.set_color(next(colors)) |
61
|
|
|
else: |
62
|
|
|
await sleep(1) |
63
|
|
|
|
64
|
|
|
async def system(): |
65
|
|
|
train = Train('My Train') |
66
|
|
|
|
67
|
|
|
if __name__ == '__main__': |
68
|
|
|
logging.basicConfig(level=logging.INFO) |
69
|
|
|
start(system) |
70
|
|
|
|