From 65c81834c9d3ec469dd20666518ec3fe4ae3de89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pavel=20Lobodinsky=CC=81?= Date: Mon, 3 Jan 2022 23:35:34 +0100 Subject: [PATCH] pybricks.hubs.PrimeHub: Added a cleanup example. --- doc/main/hubs/primehub.rst | 7 ++++++ examples/pup/hub_primehub/cleanup.py | 33 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 examples/pup/hub_primehub/cleanup.py diff --git a/doc/main/hubs/primehub.rst b/doc/main/hubs/primehub.rst index a194296..6cc4aec 100644 --- a/doc/main/hubs/primehub.rst +++ b/doc/main/hubs/primehub.rst @@ -235,3 +235,10 @@ Turning the hub off .. literalinclude:: ../../../examples/pup/hub_primehub/system_shutdown.py + +Clean up after program stop +***************************************** + +.. literalinclude:: + ../../../examples/pup/hub_primehub/cleanup.py + diff --git a/examples/pup/hub_primehub/cleanup.py b/examples/pup/hub_primehub/cleanup.py new file mode 100644 index 0000000..e7de877 --- /dev/null +++ b/examples/pup/hub_primehub/cleanup.py @@ -0,0 +1,33 @@ +from pybricks.hubs import PrimeHub +from pybricks.parameters import Color, Port +from pybricks.pupdevices import ColorSensor, UltrasonicSensor + +# Initialize the hub +hub = PrimeHub() + +# Initialize the sensors +ultrasonic_sensor = UltrasonicSensor(Port.E) +color_sensor = ColorSensor(Port.F) + +# Turn on upper halves +ultrasonic_sensor.lights.on([50, 50, 0, 0]) + + +# Your robot's code goes here +def main(): + while True: + color = color_sensor.color() + if color == Color.RED: + hub.display.text("R") + else: + hub.display.text("?") + + +# Wrap the code in try-finally to ensure the cleanup code is always executed +# no matter if the program gets stopped gracefully by the user or by an error +try: + main() +finally: + # The cleanup code goes here + color_sensor.lights.off() + ultrasonic_sensor.lights.off()