In the previous lesson, you learned to use the position servo, which moves to a particular angle. In this lesson, you will learn to use the rotation servo. The rotation servo is a motor that can rotate at different speeds.
Lesson 5 – Rotation Servos
1 Rotation Servo, 1 Tri-Color LED
Generating random numbers
Plug in the rotation servo to SERVOS port 1 on the Bit. Make sure the black wire is aligned to ‘-,’ the red wire to ‘+,’ and the white wire to ‘S.’
Write a program that makes the servo spin clockwise quickly for 2 seconds, then counterclockwise slowly for 3 seconds.
Write a program that makes the motor run then stop 10 times.
To make the behavior of your robot less predictable, you may want to incorporate some variation so that your robot does something slightly different each time you run the program. To do this, you can use a random number generator. A random number generator is a function that picks a random number each time you call it. In Python, use randint() to pick an integer. This function takes two parameters that define the range of numbers that you are interested in. The first is the lowest number that should be generated, and the second parameter is the highest number that should be generated. For example, this line of code will generate a random number from 0 to 5.
Modify the code from Exercise 4 to set the rotation servo to a random speed between -100 and 100.
Connect a tri-color LED to your Hummingbird. Using the randint() function to set the tri-color LED to a random color. Then use a loop to set the LED to a random color 5 times.
The random library also includes other random number generators. For example, random.random() generates a random number between 0.0 and 1.0 (not including 1.0). Use this function to modify your code from Exercise 6 so that the LED stays each color for a random number of seconds between 0 and 1. Can you then make the LED stay each color for a random number of seconds between 0 and 5? Note: random.random() does not take any arguments.
Now that you know how to use the rotation servo, try building and programming a rover! Note that the two rotation servos on the rover point in opposite directions. This means that to move the rover forward, the two servos must move in opposite directions.