Science Oxford Logo

Using variables to control the servo


Creating and using a variable

Instead of manually setting a value for each sleep , you can set a speed variable, allowing you to use code to change the value.

Set your new variable before while True to make sure it doesn't reset it every time:

speed = 1000

Inside your loop, change the value inside sleep :

sleep(speed)

The full code will look like this:

speed = 1000
while True:
    if button_a.was_pressed():
        pin1.write_analog(35)
        sleep(speed)
        pin1.write_analog(85)
        sleep(speed)

Adding more variables

You can add more variables, to control the position of the servo. By using a variable for this, you can change the values in other parts of your code.

speed = 1000
position1 = 35
position 2 = 85
while True:
    if button_a.was_pressed():
        pin1.write_analog(position1)
        sleep(speed)
        pin1.write_analog(position2)
        sleep(speed)

Adding random

Now you are set up, you can start having fun with your variables.

One thing to try, is getting the micro:bit to choose the speed for you, randomly.

Add the following line to your code, above while True:

from random import randint

To choose a new speed every loop, add a new line of code after your if statement:

speed = randint(500, 5000)

The first number is the minimum number it can choose, and the second is the maximum.


The full code will look like this:

from random import randint
position1 = 35
position 2 = 85
while True:
    if button_a.was_pressed():
        speed = randint(500, 5000)
        pin1.write_analog(position1)
        sleep(speed)
        pin1.write_analog(position2)
        sleep(speed)

What other ways can you think of to change the variables?


Some Python syntax for using variables is listed below, to help you once you decide where and how you want to change the variables.