Hello all,
I'm new to mindstorms and I'm trying to do some first programming attemps, but I have a problem. I prefer usage of python over scratch, but I don't know how to handle multi thread (parallel) processes using python. What I'm talking about is following:
In scratch I can easily create more independent blocks which are all active and all are performed when event happens (condition is met). I can have e.g. something like this in scratch:
1) Sensor C - if color is green
Start motor A
2) Sensor C - if color is red
Stop motor A
3) Sensor E - if distance is smaller than 20 cm
Stop motor A
In above mentioned case both color sensor is able to stop the motor in case of red color, but also distance sensor in case of distance smaller than 20cm. Program is always checking both these sensors and waiting for data from them. But how can I do the same thing in python? If I do something like following, then it won't work for obvious reason because all those "waiting" functions are blocking and therefore if code is waiting for distance sensor, it won't react fo colors and vice versa:
pohon = Motor('B')
color_sensor = ColorSensor('C')
distance_sensor = DistanceSensor('D')
while True:
color = color_sensor.wait_for_new_color()
if color == 'red':
pohon.stop()
elif color == 'green':
pohon.start(50)
distance_sensor.wait_for_distance_closer_than(20, 'cm')
pohon.stop()
I can (for some cases) replace it with loop which checks current status and reacts appropriately without waiting such as
while True:
color = color_sensor.get_color()
if color == 'red':
pohon.stop()
elif color == 'green':
pohon.start(50)
distance = distance_sensor.get_distance_cm()
if distance < 20:
pohon.stop()
But I dont like it, it will be not usable in all cases and it doesn't allow to perform parallel activities (e.g. if I will request to move motor A on red and move motor B when distance is < 20 cm, then this will allow to do it only sequentially when one of motors will always move first and another second - even in case that distance will go under 20cm at the same time when color sensor detects red).
I expect that I'm looking for something like define new methods via DEF where each method will be similar to one of those scratch blocks (probably having infinite loop inside) and somehow run them as an independent processes (something like fork?) so all methods will be working at the same time and I will be able to handle multiple events at the same time.
Is there some possibility to do this? Can you please help me with some example or link me to some resource where is described this micropython in better detail than in Mindstorms knowledge base? Thank you very much.