# HG changeset patch # User Radomir Dopieralski # Date 1553123739 0 # Node ID 1dc1a2e5e642a147d6b2798bb961f1bc656fbe40 # Parent 6dcf45d13f35607585a96eb767be1e58fbab7fe3 add some comments diff -r 6dcf45d13f35 -r 1dc1a2e5e642 bot.py --- a/bot.py Tue Mar 14 13:00:05 2017 +0100 +++ b/bot.py Wed Mar 20 23:15:39 2019 +0000 @@ -2,23 +2,30 @@ class Servo: + """A class for controlling continuous-rotation servos.""" + def __init__(self, pin, trim=0): - self.pin = pin - self.trim = trim - self.speed = 0 - self.pin.set_analog_period(20) + self.pin = pin # The pin to which the servo is connected. + self.trim = trim # What value makes the servo stop. + self.speed = 0 # Current speed. + self.pin.set_analog_period(20) # Servo needs 20Hz signal. def set_speed(self, speed): + """Sets the rotation speed of the servo, range is -90 to +90.""" + # Value of 25 gives us around 1000us, which is the minimum duty cycle + # for the servo. 125 is the maximum. self.pin.write_analog(int(25 + 100 * (90 + speed) / 180 + self.trim)) self.speed = speed class Robot: def __init__(self): + # Initialize the servos. Adjust the trim as needed. self.left_servo = Servo(microbit.pin0, 2) self.right_servo = Servo(microbit.pin1, 1) def go(self, distance): + """Make the robot go straight for a given distance.""" microbit.display.show(microbit.Image.ARROW_S) self.left_servo.set_speed(-90) self.right_servo.set_speed(90) @@ -26,6 +33,7 @@ self.stop() def turn(self, angle): + """Make the robot turn in place by given angle in degrees.""" if angle > 0: microbit.display.show(microbit.Image.ARROW_E) self.left_servo.set_speed(-90) @@ -39,24 +47,26 @@ self.stop() def stop(self): + """Make the robot stop.""" microbit.display.show(microbit.Image.DIAMOND) self.left_servo.set_speed(0) self.right_servo.set_speed(0) def get_distance(self): + """Use the distance sensor on pin2.""" return microbit.pin2.read_analog() -robot = Robot() +robot = Robot() # Create the robot object. while True: - robot.go(5) - if robot.get_distance() > 700: - robot.turn(20) - left_distance = robot.get_distance() - robot.turn(-40) - right_distance = robot.get_distance() - robot.turn(20) - if left_distance < right_distance: + robot.go(5) # Go forward 5 units. + if robot.get_distance() > 700: # If the distance sensor returns something... + robot.turn(20) # Turn 20 degrees one way. + left_distance = robot.get_distance() # Take a measurement. + robot.turn(-40) # Turn 20 degrees the other way (40 in total) + right_distance = robot.get_distance() # Take a measurement. + robot.turn(20) # Turn back straight. + if left_distance < right_distance: # Pick whatever side was further away. robot.turn(60) else: robot.turn(-60)