Run Your Script
Either copy and paste, or re-create the following code into your own MakeCode editor by clicking the
open icon in the upper right-hand corner of the editor window. You can also just download this
example by clicking the download button in the lower right-hand corner of the code window.
Note:
Controlling a servo with the micro:bit is not intended to give you a highly accurate angle of
rotation, just basic movement from one position to another to get your project movin'. If you are
looking for a higher degree of accuracy from your servo we recommend powering your servo motor
with an external supply of 4.8V to 6V.
Note:
You may need to disable your ad/pop-up blocker to interact with the MakeCode programming
environment and simulated circuit!
Code to Note
Let’s take a look at the code blocks in this experiment.
If you are having a hard time viewing this code, click on the image above to get a better look!
Set “Direction To”
In the
On
Start
block we set the direction variable to
1
. This value will be toggled between 1 and -1
to determine the direction we want the servo to sweep.
Servo Write
We use the
Servo
Write
block to control a servo connected to a specific pin to rotate to a specific
angle we pass it in degrees. We use a variable we have labeled as
degrees
. You can use this
command to just write any angle between 0 and 180 to a servo motor at any time, but do remember
to add a small pause to make sure that you give it enough time to respond before moving to the next
angle.
Change by
If you want to increment or decrement a given variable by a certain value, which is positive or
negative, you use the
Change
by
block. You can select the variable you want to change and then the
value you want to increment by (positive value) or decrement by (negative value). We increment the
angle by 1 degree using this block.
Set “Direction to Direction x -1”
To change the direction of the servo once it reaches 0 or 180, we do some fancy math to multiply
the
direction
variable by -1 to toggle it from a positive value to a negative number or a negative
number to a positive value. That way when we use the
change
by
block, the number is positive or
negative.