Tutorial
Tutorial
You may find somethings missing or broken, or some difficulty to learn the kit.
Freenove provides free and quick support, including but not limited to:
Quality problems of products
Problems in using products
Questions for learning and technology
Opinions and suggestions
Ideas and thoughts
If you have any concerns, please send email to us:
[email protected]
And suggestions and feedbacks are welcomed. Many customers offered great feedbacks. According to that,
we are keeping updating the kit and the tutorial to make it better. Thank you.
Safety
Do not expose children under 6 years of age to this product. Put it out of their reach.
Children lack safety ability should use this product under the guardianship of adults.
This product contains small and sharp parts. Do not swallow, prick and scratch to avoid injury.
This product contains conductive parts. Do not hold them to touch power supply and other circuits.
Some parts will rotate or move when it works. Do not touch them to avoid being bruised or scratched.
The wrong operation may cause overheat. Do not touch and disconnect the power supply immediately.
Operate in accordance with the requirements of the tutorial. Otherwise, the parts may be damaged.
Store the product in a dry place and avoid direct sunlight.
Turn off the power of the circuit before leaving.
About
Freenove is committed to helping customers learn programming and electronic knowledge, quickly realize
their creative ideas and product prototypes and launching innovative products. Our services include:
You can learn more about us or get our latest information through our website:
http://www.freenove.com
Copyright
All the files we provided are released under Creative Commons Attribution-NonCommercial-ShareAlike 3.0
Unported License. You can find a copy of the license in the folder.
This means you can use them on your own derived works, in part or completely. But NOT for the purpose of
commercial use.
Freenove brand and logo are copyright of Freenove Creative Technology Co., Ltd. Cannot be used without
formal permission.
○
R
Contents
Welcome ................................................................................. I
Contents.................................................................................. I
Preface .................................................................................... 1
Micro:bit ................................................................................. 2
Meet micro:bit ............................................................................................................................................................................ 2
Features ........................................................................................................................................................................................ 3
Hardware ..................................................................................................................................................................................... 4
[email protected] █
II Contents www.freenove.com █
█ [email protected]
█ www.freenove.com Contents III
[email protected] █
█ www.freenove.com Preface 1
Preface
Do you want to learn programming?
Nowadays, Program is developed into the younger age group, and everyone programming is a trend. From
Arduino and Raspberry Pi to micro:bit, simple graphical programming makes programming for kids possible.
Maybe you haven't heard of them, it doesn't matter. With this product and the tutorial, you can easily
complete a programming project and experience the fun as a Maker.
Micro:bit is a powerful and simple development board. Even if you’ve never programmed before, its simple
graphical programming interface allows you to master it easily. It doesn’t require any professional
programming software; just simply a browser is enough to program it. So, no matter your computer system
is Windows, Linux or Mac, you can program it. And you can also program it with Python.
It attracts a lot of fans in the world who are keen to exploration, innovation and DIY and have contributed a
great number of high-quality open-source code, circuit and rich knowledge base. So we can realize our own
creativity more efficiently by using these free resource. Of course, you can also contribute your own strength
to the resource.
With Micro:bit, we can make a lot of projects and by adding kits to breadboard, we can carry out more
interesting projects like ultrasonic ranging, gravity control, playing music, etc.
In each learning chapter of this tutorial, we provide program source code with detailed program explanations
and burnable binaries, so that you can understand the meaning of each section of program.
Additionally, if you have any difficulties or questions about this tutorial and the kit, you can always ask us for
quick and free technical support.
[email protected] █
2 Micro:bit www.freenove.com █
Micro:bit
This chapter is the Start Point in the journey to build and explore Micro:bit and Micro:Rover electronic projects.
Meet micro:bit
The BBC micro:bit is a pocket-size, programmable micro-computer that can be used for all sorts of cool
creations, from robots to musical instruments – the possibilities are infinite.
█ [email protected]
█ www.freenove.com Micro:bit 3
Features
[email protected] █
4 Micro:bit www.freenove.com █
Hardware
It is not required for beginners to master this section, but a brief understanding is necessary. However, if you
want to be a developer, hardware information will be very helpful. Detailed hardware information about
micro:bit can be found here: https://tech.microbit.org/hardware/.
First, get to know the micro:bit GPIO.
GPIO
GPIO, namely General Purpose Input/output Pins, is an important part of micro:bit for connecting external
devices. All sensors and devices on Rover communicate with each other through micro:bit GPIO. The following
is the GPIO serial number and function diagram of micro:bit:
█ [email protected]
█ www.freenove.com Micro:bit GPIO Extension Board 5
USB
Micro
port to
USB port
micro:bit
to PC
Micro:bit
DC power
slot
5V voltage 3.3V
indicator voltage
indicator
GPIO
Micro:bit GPIO Extension Board is connected to micro:bit board via a slot with its GPIO connected to
micro:bit’s GPIO. In addition, there are also 5V and VIN(9V) IO port on the extension board to meet
requirement of more devices.
[email protected] █
6 Micro:bit GPIO Extension Board www.freenove.com █
How to use?
If external device doesn’t require voltage of 5V and 9V, you can use the following wiring.
There is no
power in 5V
and VIN port
If external device uses 5v voltage, but power needed is not large, you can use the following wiring.
Program
download
side
5V with power
VIN with no power
█ [email protected]
█ www.freenove.com Micro:bit GPIO Extension Board 7
If external device uses 5v voltage, but power needed is large, you can use the following wiring.
Program
download
side
[email protected] █
8 Code & Programming www.freenove.com █
Quick Start
This section describes how to write programs for micro:bit and how to download them to micro:bit. There are
very detailed tutorials on the official website. You can refer to: Https://microbit.org/guide/quick/.
Connect the micro:bit to your computer via a micro USB cable. Macs, PCs, Chromebooks and Linux systems
(including Raspberry Pi) are all supported.
█ [email protected]
█ www.freenove.com Code & Programming 9
If your computer has Windows 10 operating system, you can also use Windows 10 App for programming,
which is exactly the same as programming on browsers. Get windows 10 App(Click).
[email protected] █
10 Code & Programming www.freenove.com █
Write your first micro:bit code. For example, drag and drop some blocks and try your program on the
Simulator in the MakeCode Editor, like in the image below that shows how to program a Flashing Heart.
█ [email protected]
█ www.freenove.com Code & Programming 11
The process of transferring the .HEX file to the BBC micro:bit is called flashing.
If you write program using Windows 10 App, you just need to click the “Download” button, then the program
will be downloaded directly to micro:bit without any other actions.
The micro:bit will pause and the yellow LED on the back of the micro:bit will blink while your code is flashed.
Once that's finished the code will run automatically! The micro:bit can only run one program at a time - every
time you drag-and-drop a hex file onto the device over USB it will erase the current program and replace it
with the new one.
Warning
The MICROBIT drive will automatically eject and reconnect each time you program it, but your hex file
will be gone. The micro:bit can only receive hex files and won't store anything else!
[email protected] █
12 Code & Programming www.freenove.com █
MakeCode
Open web version of MakeCode or windows 10 app version of MakeCode, which can be downloaded on
Microsoft store.
https://makecode.microbit.org/
Settings
Graphic code
and text code Code editing area
switch
Code library
Simulatorlator
Project name
In the code area, there are two fixed blocks “on start” and “forever”.
The code in the “on start” block will be executed only once after power-on or reset. And the code in “
forever” block will be executed circularly.
█ [email protected]
█ www.freenove.com Code & Programming 13
Quick Download
As mentioned earlier, if you use Windows 10 App of MakeCode (recommended), you can quickly download
the code to micro:bit by clicking the download button. Using browser version of MakeCode may require
more steps.
If you use browser version of MakeCode on Google Chrome 65+ for platform Android, Chrome OS, Linux,
macOS and Windows 10, you can also download file quickly.
Here we use webUSB feature of Chrome, which allows web pages to access your USB hardware devices. We
will complete the connection and pairing of the micro:bit device with the webpage in the following steps.
Pair device
[email protected] █
14 Code & Programming www.freenove.com █
Select device on the pop-up window and click “Connect” button. If there are no devices shown on the pop-
up window, please refer to following content:
https://makecode.microbit.org/device/usb/webusb/troubleshoot
We have save the page as a file “Troubleshooting downloads with WebUSB - Microsoft MakeCode.pdf”.
You can read it directly in the folder of this tutorial.
And the file “Firmware microbit.pdf” introduces how to update firmware of micro:bit. Its content come from:
https://microbit.org/guide/firmware/
After the connection succeeds, click the Download button and the program will be downloaded directly to
Micro: bit.
█ [email protected]
█ www.freenove.com Code & Programming 15
Import Code
We provide hex file (project files) for each project, which contains all the contents of the project and can be
imported directly. You can also complete the code of project manually. If you choose to complete the code
by dragging code block, you may need to add necessary extensions.
As for simple projects, it is recommended to complete the project by dragging code block.
As for complicated projects, it is recommended to complete the project by importing Hex code file.
Next, we will take “Heartbeat” project as an example to introduce how to load code.
[email protected] █
16 Code & Programming www.freenove.com █
█ [email protected]
█ www.freenove.com Code & Programming 17
Python
If you are not interested in python, you can skip this section.
Micro:bit can be programmed in Python. Since micro:bit is a microcontroller, the hardware difference makes
it not support pure Python. Here we use MicroPython, which is specially designed for micro:bit.
MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a
small subset of the Python standard library and is optimized to run on microcontrollers and in constrained
environments.
We designed block code and Python code with similar function for each project.
There are two kinds of python editors for micro:bit, web version and software.
It is highly recommended to use software Mu as a Python educator.
Mu. (https://codewith.mu/en/download)
Next, we will introduce Mu.
Mu
Mu is a Python code editor for beginner programmers based on extensive feedback given by teachers and
learners.
Official website: https://codewith.mu/
You can download it here: https://codewith.mu/en/download
Download and install it.
And you will see the following interface when opening it.
Click the Mode button in the menu bar and select "BBC micro:bit" in the pop-up dialog box. Click "OK".
[email protected] █
18 Code & Programming www.freenove.com █
Use the micro USB cable to connect micro:bit and PC, and click the Flash button to download the program
into micro:bit.
█ [email protected]
█ www.freenove.com Code & Programming 19
If there are errors in your code, you may be able to successfully download it to micro:bit, but it will not work
properly.
For example, the function sleep() was written as sleeps() in the following illustration. Click the button and the
code can be uploaded to Micro:bit successfully. However, after the downloading completes, LED matrix
prompts some error information and the number of the wrong line.
Click the “REPL” button and press the reset button (the button on the back, not A, B) on micro:bit. The error
message will be displayed in the REPL box, as shown below:
Click REPL again, you will close REPL mode. And then you can flash new code.
[email protected] █
20 Code & Programming www.freenove.com █
To ensure the code is correct, after completing the code, click the "Check" button to check the code for errors.
As shown below, click the “Check” button. Then Mu will indicate the error of the code.
Correct the code according to the error prompt. Then click the "Check" button again, Mu displays no error
on the bar below.
█ [email protected]
█ www.freenove.com Code & Programming 21
Copy “I2C_LCD1602_Class.py” and “DHT11_RW.py” from following path into “mu_code” directory.
File type Path File name
Python file .. /Projects/PythonLibrary I2C_LCD1602_Class.py DHT11_RW.py
[email protected] █
22 Code & Programming www.freenove.com █
Open the Mu software, click "Files". Here we take "I2C_LCD1602_Class.py" as an example, drag
"I2C_LCD1602_Class.py" into micro:bit.
Select it and keep pressing with left mouse button, drag it to left box.
The import method of "DHT11_RW.py" is the same as described above. You just need to import the one you
need to use.
Note, after you upload other file into micro:bit, the original content will be covered. You need to import
it next time you use it.
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 23
Component List
Circuit
[email protected] █
24 Chapter 1 LED matrix www.freenove.com █
Block code
Open the MakeCode for the web version or MakeCode for the win10 version. Click on "New Project"
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 25
Click basic in the list on the left, select the desired code block, and drag it into the right code editing area.
Right click the mouse and select Duplicate to duplicate the code block.
[email protected] █
26 Chapter 1 LED matrix www.freenove.com █
If you want to delete the block, you can right click on the block and select “Delete Block”. You can also drag
it to left to delete it.
On the second block, click on the drop-down triangle next to the heart-shaped pattern on the block to display
all the optional built-in patterns, select the second pattern, a small heart shape.
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 27
Reference
Block Function
Python Code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/01.1_Heartbeat Heartbeat.py
After loading successfully, the code is shown below:
Download the program to the microbit, theLED matrix on the micro:bit will continue to display a large heart-
shaped pattern and a small heart-shaped pattern, just like heartbeating.
[email protected] █
28 Chapter 1 LED matrix www.freenove.com █
Python language is an interpreted language that is executed sequentially. In the code of this project, the
micro:bit module is first imported, and then in a infinite loop statement, a large heart pattern and a small
heart pattern are alternately displayed.
Next, we will explain the code line by line.
while True:
An infinite loop that will be executed circularly by microbit constantly.
display.show(Image.HEART)
Display heart pattern on LED matrix.
sleep(1000)
Delay for one second.
display.show(Image.HEART)
sleep(1000)
display.show(Image.HEART_SMALL)
sleep(1000)
Display the heart pattern on the LED matrix for one second, and then display the small heart pattern for
another second.
Reference
from microbit import *
Import everything in the microbit module, including functions, classes, variables, etc. You can use all the
available contents in the micro:bit module in the next program.
while True:
While is a loop statement, if the condition is true, the code in while is executed.
This code with True means that the code in the while is always executed circularly.
display.show(image)
Display the image.
For more details about display,
please refer to: https://microbit-micropython.readthedocs.io/en/latest/display.html
For more details about image,
Please refer to: https://microbit-micropython.readthedocs.io/en/latest/image.html
sleep(t)
Delay for given number of milliseconds, should be positive or 0.
For more details about sleep function, please refer to:
https://microbit-micropython.readthedocs.io/en/latest/utime.html
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 29
In this project, we will use the LED matrix of the micro:bit to display numbers.
Circuit
[email protected] █
30 Chapter 1 LED matrix www.freenove.com █
Block code
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 31
Download the code into the micro:bit. After the downloading completes, the micro:bit LED matrix will start to
display the numbers 0, 1, 2, 3, 4...99. Then start again from 0 to 99, so that it will cycle permanently.
In this code, a for loop is used. Each time the loop is executed, the value of the variable index is increased by
1. When the value is greater than 99, the for loop is exited. In the body of the loop, the value of the numeric
index is displayed.
Reference
Block Function
[email protected] █
32 Chapter 1 LED matrix www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/01.2_ShowNumber ShowNumber.py
After loading successfully, the code is shown as below:
Download the code into the microbit. After the downloading completes, the micro:bit LED matrix will start to
display the numbers 1, 2, 3, 4...100. Then start again from 1 to 100, so that it will repeat endlessly.
The code of this project, in a 0-100 for loop, scrolls through the cyclic number index, which is incremented
by 1.
Reference
display.scroll(value)
Scrolls value horizontally on the display. If value is an integer or float it is first converted to a string using
str().
For more information, please refer to: https://microbit-micropython.readthedocs.io/en/latest/utime.html
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 33
This project uses the LED matrix of micro:bit to display text (ASCII).
Circuit
Block code
Open MakeCode first.Import the .hex file. The path is as below:(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/01.3_ShowText ShowText.hex
After loading successfully, the code is shown as below:
Download the code into the microbit, the micro:bit LED matrix will scroll from left to right to display "Hello,
Freenove!"
[email protected] █
34 Chapter 1 LED matrix www.freenove.com █
Reference
Block Function
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/01.3_ShowText ShowText.py
After loading successfully, the code is shown as below:
Download the code into the microbit, the micro:bit LED matrix will scroll from left to right to display "Hello,
Freenove!"
This code scrolls through the text "Hello, Freenove!" in a while loop.
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 35
Circuit
Block code
Check the connection of the circuit and verify it correct.. Then download the code into the microbit, and the
square pattern shown above will appear on the LED matrix of the micro:bit.
[email protected] █
36 Chapter 1 LED matrix www.freenove.com █
Reference
Block Function
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/01.4_ShowCustom ShowCustom.py
After loading successfully, the code is shown as below:
Download the code into the microbit, and a square pattern will appear on the micro:bit LED matrix.
(How to download?)
█ [email protected]
█ www.freenove.com Chapter 1 LED matrix 37
Create an image in the code and define it as img, then display the defined image in a while loop. As shown
in the code below, the parameters in Image consist of 5 strings. Each line of characters corresponds to a row
of LEDs. Each digit represents the brightness of an LED. The value ranges from 0 to 9, the larger the number,
the brighter the LED.
1 img = Image("00000:"
2 "09990:"
3 "09090:"
4 "09990:"
5 "00000")
Reference
img = Image("00000:"
"09990:"
"09090:"
"09990:"
"00000")
Create an image of LED, and set brightness of LED.
For more information, please refer to:
https://microbit-micropython.readthedocs.io/en/latest/image.html
[email protected] █
38 Chapter 2 Built-in Button www.freenove.com █
This project uses micro:bit integrated buttons A and B. When different buttons are pressed, micro:bit displays
different patterns.
Circuit
Block code
█ [email protected]
█ www.freenove.com Chapter 2 Built-in Button 39
Download the code into micro:bit. When button A is pressed, the micro:bit LED matrix will display an arrow
pointing to button A. When button B is pressed, the micro:bit LED matrix will display an arrow pointing to
button B. When the buttons A and B are pressed at the same time, the micro:bit LED matrix will display a
check mark. When no button is pressed, the micro:bit LED matrix displays a cross.
Reference
Block Function
[email protected] █
40 Chapter 2 Built-in Button www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/02.1_BuiltInButton BuiltInButton
After loading successfully, the code is shown as below:
Download the code into micro:bit. When button A is pressed, the micro:bit LED matrix will display an arrow
pointing to button A. When button B is pressed, the micro:bit LED matrix will display a an arrow pointing to
button B.When the buttons A and B are pressed at the same time, the micro:bit LED matrix will display a check
mark. When no button is pressed, the micro:bit LED matrix displays a cross.
█ [email protected]
█ www.freenove.com Chapter 2 Built-in Button 41
Use the if-elif-else statement to determine when the button is pressed. First, when the buttons A and B are
pressed at the same time, a check mark is displayed.
if button_a.is_pressed() and button_b.is_pressed():
display.show(Image.YES)
Then, determine in turn if the buttons A or B is pressed seperately, and the case where no button is pressed.
elif button_a.is_pressed():
display.show(Image.ARROW_W)
elif button_b.is_pressed():
display.show(Image.ARROW_E)
else:
display.show(Image.NO)
Note that it is necessary to first determine if buttons A and B are pressed at the same time. If-elif-else
statement will make the micro:bit execute only one situation. If the state with two buttoon pressed is placed
in last, the result of pressing A or B will appear first, then the statement will end, and then sentence met the
state with two button pressed will never be executed.
Reference
is_pressed()
Returns True if the specified button is currently being pressed, and False otherwise.
For more information, please refer to https://microbit-micropython.readthedocs.io/en/latest/button.html
[email protected] █
42 Chapter 3 LED www.freenove.com █
Chapter 3 LED
This section we will learn how to control external LEDs.
Component List
█ [email protected]
█ www.freenove.com Chapter 3 LED 43
Circuit Knowledge
Current
The unit of current (I) is ampere (A). 1A=1000mA, 1mA=1000μA.
Closed loop consisting of electronic components is necessary for current.
In the figure below: the left is a loop circuit, so current flows through the circuit. The right is not a loop
circuit, so there is no current.
Resistor
Resistors use Ohms (Ω) as the unit of measurement of their resistance (R). 1MΩ=1000kΩ, 1kΩ=1000Ω.
A resistor is a passive electrical component that limits or regulates the flow of current in an electronic
circuit.
On the left, we see a physical representation of a resistor, and the right is the symbol used to represent the
presence of a resistor in a circuit diagram or schematic.
The bands of color on a resistor is a shorthand code used to identify its resistance value. For more details
of resistor color codes, please refer to the card in the kit package.
With a fixed voltage, there will be less current output with greater resistance added to the circuit. The
relationship between Current, Voltage and Resistance can be expressed by this formula: I=V/R known as
Ohm’s Law where I = Current, V = Voltage and R = Resistance. Knowing the values of any two of these
allows you to solve the value of the third.
In the following diagram, the current through R1 is: I=U/R=5V/10kΩ=0.0005A=0.5mA.
[email protected] █
44 Chapter 3 LED www.freenove.com █
WARNING: Never connect the two poles of a power supply with anything of low resistance value (i.e. a
metal object or bare wire) this is a Short and results in high current that may damage the power supply
and electronic components.
Note: Unlike LEDs and Diodes, Resistors have no poles and re non-polar (it does not matter which
direction you insert them into a circuit, it will work the same)
Note that the Analog signals are curved waves and the Digital signals are “Square Waves”.
In practical applications, we often use binary as the digital signal, that is a series of 0’s and 1’s. Since a binary
signal only has two values (0 or 1) it has great stability and reliability. Lastly, both analog and digital signals
can be converted into the other.
█ [email protected]
█ www.freenove.com Chapter 3 LED 45
Component knowledge
Let us learn about the basic features of components to use them better.
Jumper
Jumper is a kind of wire, which is designed to connect the components together by inserting its two
terminals.
Jumpers have male end (pin) and female end (slot), so jumpers can be divided into the following 3 types.
Jumper M/M
Jumper F/F
Jumper F/M
Breadboard
[email protected] █
46 Chapter 3 LED www.freenove.com █
LED
An LED is a type of diode. All diodes only work if current is flowing in the correct direction and have two Poles.
An LED will only work (light up) if the longer pin (+) of LED is connected to the positive output from a power
source and the shorter pin is connected to the negative (-) negative output also referred to as Ground (GND).
This type of component is known as “Polar” (think One-Way Street).
All common 2 lead diodes are the same in this respect. Diodes work only if the voltage of its positive electrode
is higher than its negative electrode and there is a narrow range of operating voltage for most all common
diodes of 1.9 and 3.4V. If you use much more than 3.3V the LED will be damaged and burn out.
Note: LEDs cannot be directly connected to a power supply, which usually ends in a damaged component. A
resistor with a specified resistance value must be connected in series to the LED you plan to use.
Circuit
When wiring, it is recommended to disconnect all the power supplies in the circuit, and then build the circuit
according to the circuit (micro:bit board cannot be inserted reverse),
LED’s positive pole (long pin) should be connected to resistor while its negative pole (short pin) should
be connected to GND. After the circuit is built and verified correct, use the USB cable to connect the PC
to the micro:bit to power the circuit.
CAUTION: Avoid any possible short circuits (especially connecting 5V or GND, 3.3V and GND)!
WARNING: A short circuit can cause high current in your circuit, create excessive component heat and
cause permanent damage to your micro:bit!
█ [email protected]
█ www.freenove.com Chapter 3 LED 47
Schematic diagram
Hardware connection
[email protected] █
48 Chapter 3 LED www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/03.1_Blink Blink.hex
After import successfully, the code is shown as below:
Download the code into the micro:bit and the LED on the breadboard will begin to blink.
In the code, write 1 to the P0 port to turn ON the LED. After waiting for 500ms, write 0 to the P0 port to turn
OFF the LED. After waiting for 500ms, the LED will be turned ON again. Repeat the loop, then LED will start
blinking.
█ [email protected]
█ www.freenove.com Chapter 3 LED 49
Reference
Block Function
Pause the program for the number of milliseconds you set. You
can use this function to slow your program down.
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/03.1_Blink Blink.py
After loading successfully, the code is shown as below:
Download the code into micro:bit and the LED on the breadboard will start to blink.
(How to download?)
[email protected] █
50 Chapter 3 LED www.freenove.com █
In the code, write 1 to the P0 port to turn ON the LED. After waiting for 500ms, write 0 to the P0 port to turn
OFF the LED. After waiting for 500ms, the LED will be turned ON again. Repeat the loop, then LED will start
blinking.
Write a high level to pin P0.
pin0.write_digital(1)
Delay 500ms
sleep(500)
Then write low level, and then delay 500ms. Repeat actions above.
Reference
pin.write_digital(value)
Set the pin to high if value is 1, or to low, if it is 0.
For more information, please refer to:https://microbit-micropython.readthedocs.io/en/latest/pin.html
█ [email protected]
█ www.freenove.com Chapter 4 Button and LED 51
Control:
RPI, Arduino,
micro:bit,
MCU and etc.
Input: Output:
buttons, switches, LED, buzzer,
sensors and etc. motor and etc.
Next, we will build a simple control system to control an LED through a push button switch.
[email protected] █
52 Chapter 4 Button and LED www.freenove.com █
In the project, we will control the LED state through a Push Button Switch. When the button is pressed, our
LED will turn ON, and when it is released, the LED will turn OFF. This describes a Momentary Switch.
Component list
1kΩ x2
█ [email protected]
█ www.freenove.com Chapter 4 Button and LED 53
Circuit knowledge
In the above circuit diagram, when the button is not pressed, 3.3V (high level) will be detected by I/O port;
and when the button is pressed, it will be 0V (low level). Resistor R2 here is used to prevent the port from
being set to output high level by accident. Without R2, the port maybe connected directly to the cathode
and cause a short circuit when the button is pressed.
The following diagram shows another connection, in which the level detected by I/O port is opposite to
above diagram, when the button is pressed or not.
[email protected] █
54 Chapter 4 Button and LED www.freenove.com █
Circuit
The P0 pin detects the button and the P1 pin controls the LED.
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 4 Button and LED 55
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file . ../Projects/BlockCode/04.1_ButtonAndLED ButtonAndLED.hex
After import successfully, the code is shown as below:
Download the code into micro:bit. When the button is pressed, the LED will be turned on. When the button
is released, the LED will be turned off.
In the program, read the level of the P0 pin to determine if the button is pressed.
If P0 pin is low level, it indicates that the button is pressed, and make P1 pin output 1, then LED will be turned
ON.
Reference
Block Function
Read a digital (0 or 1) signal from a pin on the micro:bit
board.
[email protected] █
56 Chapter 4 Button and LED www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/04.1_ButtonAndLED ButtonAndLED.py
After loading successfully, the code is shown as below:
Download the code into micro:bit. When the button is pressed, the led will be turned ON. When the button
is released, the led will be turned OFF.
(How to download?)
█ [email protected]
█ www.freenove.com Chapter 4 Button and LED 57
In the program, read the level of the P0 pin, save the read level value in the variable buttonState, and then
determine whether the button is pressed.
buttonState = pin0.read_digital()
If the read P0 pin is low, it indicates that the button is pressed, and then make P1 pin output 1, so LED will be
turned ON. Otherwise, the P1 pin outputs 0, and the LED will be turned OFF.
if buttonState == 0:
pin1.write_digital(1)
else:
pin1.write_digital(0)
Reference
pin.read_digital()
Return 1 if the pin is high level, and 0 if it’s low.
For more information, please refer to:https://microbit-micropython.readthedocs.io/en/latest/pin.html
[email protected] █
58 Chapter 4 Button and LED www.freenove.com █
In this project, we will make a table lamp. The components and circuits used are exactly the same as the
previous one, but this will function differently: Press the button, the LED will turn ON, and pressing the button
again, the LED turns OFF. The ON switch action is no longer momentary (like a door bell) but remains ON
without needing to continually press on the Button Switch.
Component list
Circuit knowledge
Ideal state
Virtual state
Therefore, if we can directly detect the state of the Push Button Switch, there are multiple pressing and
releasing actions in one pressing cycle. This buffeting will mislead the high-speed operation of the
microcontroller to cause many false decisions. Therefore, we need to eliminate the impact of buffeting. Our
solution: to judge the state of the button multiple times. Only when the button state is stable (consistent)
over a period of time, can it indicate that the button is actually in the ON state (being pressed).
This project needs the same components and circuits as we used in the previous section.
█ [email protected]
█ www.freenove.com Chapter 4 Button and LED 59
Circuit
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/04.2_TableLamp TableLamp.hex
After importing successfully, the code is shown as below:
Download the code to micro:bit, press the button once, the LED turns ON, press the button again, the LED
turns OFF. .
[email protected] █
60 Chapter 4 Button and LED www.freenove.com █
In the program, when it is detected for the first time that the button is pressed, wait for 10ms to detect whether
the button is pressed again, to skip the bounce when the button is pressed. And if the button is still detected
as pressed for the second time, the button is considered to have been pressed and in a steady state. Otherwise,
it is considered to be a bounce and the program will stop detecting..
When it is determined that the key is pressed, change the status value. Status is used to save the state of LED.
And then write the new value of status to the P1 port to control the LED.
After the above operations done, the program will detect whether the button is released. And similarly, it will
first eliminate the bounce of the button.
Reference
Block Function
█ [email protected]
█ www.freenove.com Chapter 4 Button and LED 61
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/04.2_TableLamp TableLamp.py
After loading successfully, the code is shown as below:
Download the code to micro:bit, press the button once, the LED turns ON; press the button again, the LED
turns OFF.
[email protected] █
62 Chapter 4 Button and LED www.freenove.com █
In the program, when it is detected for the first time that the button is pressed, wait for 10ms to detect whether
the button is pressed again, to eliminate the impact of bounce when the button is pressed. And if the button
is still pressed for the second time, the button is considered to have been pressed and in a steady state.
Otherwise, it is considered to be a bounce and exit this judgment.
if pin0.read_digital() == 0:
sleep(10)
if pin0.read_digital() == 0:
When it is determined that the key is pressed, change the status value. Status is used to save the state of LED.
And then write the new value of status to the P1 port to control the LED.
if status == 0:
status = 1
else:
status = 0
pin1.write_digital(status)
After the above operations done, the program will detect whether the button is released. And similarly, it will
first eliminate the bounce of the button.
while pin0.read_digital() == 0:
sleep(10)
█ [email protected]
█ www.freenove.com Chapter 5 LED Bar Graph 63
In this project, we use LED Bar Graph to make a flowing water light.
Component list
[email protected] █
64 Chapter 5 LED Bar Graph www.freenove.com █
Component knowledge
Let us learn about the basic features of components to use and understand them better.
LED Bar Graph
A Bar Graph LED has 10 LEDs integrated into one compact component. The two rows of pins at its bottom
are paired to identify each LED like the single LED used earlier.
█ [email protected]
█ www.freenove.com Chapter 5 LED Bar Graph 65
Circuit
Schematic diagram
Hardware connection
If your project doesn’t work, please rotate LED bar 180°.
[email protected] █
66 Chapter 5 LED Bar Graph www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/05.1_FlowingLight01 FlowingLight01.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify that the circuit is connected correctly, download the code into
micro:bit, after the program is executed, you will see the LED turns ON from left to right, which repeats This
process is repeated to achieve the “movements” of flowing water.
█ [email protected]
█ www.freenove.com Chapter 5 LED Bar Graph 67
In the code, we need turn OFF the LED screen (which allows the GPIO pin associated with the LED screen
to be reused for other purposes).
Set one pin to high and the rest of 9 pins to low level at a time; Until all the 10 pins are set to high and low
level in turn.
Reference
Block Function
Turns the LED screen on and off (thus allowing you to
re-use the GPIO pins associated with the display for
other purposes).
[email protected] █
68 Chapter 5 LED Bar Graph www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/05.1_FlowingLight01 FlowingLight01.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify that the circuit is connected correctly, download the code into
micro:bit, after the program is executed, you will see the LED turns ON from left to right, which repeats to
achieve the “movements” of flowing water.
█ [email protected]
█ www.freenove.com Chapter 5 LED Bar Graph 69
In the code, we need to turn OFF the LED screen (which allows the GPIO pin associated with the LED
screen to be reused for other purposes).
display.off()
Change the level of the currently selected pin every 100ms to implement the effect of flowing water light.
for p in outPin:
p.write_digital(1)
sleep(100)
p.write_digital(0)
sleep(100)
Reference
display.off()
Use off() to turn OFF the display (thus allowing you to re-use the GPIO pins associated with the display for
other purposes)
[email protected] █
70 Chapter 6 PWM www.freenove.com █
Chapter 6 PWM
In this chapter, we will learn how to make a breathing LED.
Component list
█ [email protected]
█ www.freenove.com Chapter 6 PWM 71
Circuit knowledge
At first, let us learn the knowledge how to use the circuit to make LED emit different brightness of light,
PWM
PWM, Pulse-Width Modulation, is a very effective method for using digital signals to control analog circuits.
Digital processors cannot directly output analog signals. PWM technology makes it very convenient to
achieve this conversion (translation of digital to analog signals).
PWM technology uses digital pins to send certain frequencies of square waves, that is, the output of high
levels and low levels, which alternately last for a while. The total time for each set of high levels and low
levels is generally fixed, which is called the period (Note: the reciprocal of the period is frequency). The time
of high level outputs are generally called “pulse width”, and the duty cycle is the percentage of the ratio of
pulse duration, or pulse width (PW) to the total period (T) of the waveform.
The longer the output of high levels last, the longer the duty cycle and the higher the corresponding voltage
in the analog signal will be. The following figures show how the analog signal voltages vary between 0V-
5V (high level is 5V) corresponding to the pulse width 0%-100%:
The longer the PWM duty cycle is, the higher the output power will be. Now that we understand this
relationship, we can use PWM to control the brightness of an LED or the speed of DC motor and so on.
[email protected] █
72 Chapter 6 PWM www.freenove.com █
Circuit
Schematic Diagram
hardware connection
The pin for the circuit is P0. The long pin (positive) of LED is connected to the resistor, and the short pin
(negative) to ground.
█ [email protected]
█ www.freenove.com Chapter 6 PWM 73
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/06.1_BreathingLight BreathingLight.hex
After import successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
micro:bit. The LED will becomes brighter gradually, and then dimmer and dimmer. This process will be
repeated to achieve the effect of breathing.
[email protected] █
74 Chapter 6 PWM www.freenove.com █
Reference
Block Function
█ [email protected]
█ www.freenove.com Chapter 6 PWM 75
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/06.1_BreathingLight BreathingLight.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct and download the code into micro:bit, the LED will
becomes brighter gradually, and then dimmer and dimmer. This process will be repeated to achieve the
effect of breathing. (How to download?)
[email protected] █
76 Chapter 6 PWM www.freenove.com █
Reference
pin.write_analog(value)
Output a PWM signal on the pin, with the duty cycle proportional to the provided value. The value may be
either an integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty)..
For more information, please refer to:
https://microbit-micropython.readthedocs.io/en/latest/pin.html
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 77
Chapter 7 RGBLED
In this chapter, we will learn a new component, RGBLED.
Component list
[email protected] █
78 Chapter 7 RGBLED www.freenove.com █
Component knowledge
RGB LED
A RGB LED has 3 LEDs integrated into one LED component. It can respectively emit Red, Green and Blue light.
In order to do this, it requires 4 pins (this is also how you identify it). The long pin (1) is the common which is
the Anode (+) or positive lead, the other 3 are the Cathodes (-) or negative leads. A rendering of a RGB LED
and its electronic symbol are shown below. We can make RGB LED emit various colors of light and brightness
by controlling the 3 Anodes (2, 3 & 4) of the RGB LED
Red, Green, and Blue light are called 3 Primary Colors when discussing light (Note: for pigments such as
paints, the 3 Primary Colors are Red, Blue and Yellow). When you combine these three Primary Colors of
light with varied brightness, they can produce almost any color of visible light. Computer screens, single
pixels of cell phone screens, neon lamps, etc. can all produce millions of colors due to phenomenon
Red Yellow
While
Magenta
Turquoise
Blue
Green
If we use a three 8 bit PWM to control the RGB LED, in theory, we can create 28*28*28=16777216 (16
million) colors through different combinations of RGB light brightness.
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 79
Circuit
This circuit uses pins P2, P1, and P0 to connect the negative electrodes of the RGBLED.
Schematic diagram
Hardware connection
The longest pin of the RGB LED is connected to the power supply 3.3V.
[email protected] █
80 Chapter 7 RGBLED www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below: (how to import project)
File type Path File name
HEX file ../Projects/BlockCode/07.1_RGBLED RGBLED.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
micro:bit, and RGBLED will emit yellow color. RGB value of yellow is (255,255,0).
In this kit, three LEDs of RGB LED share a common anode(+) and their negative pins need to be set to LOW
level to have the RGB LED work. And the value of variables ‘red’, ‘green’, and ‘blue’ need to be converted from
the value ranging from 0-255 to analog signal values ranging from1023-0.
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 81
Reference
Block Function
Convert a value in one number range
to a value in another number range.
[email protected] █
82 Chapter 7 RGBLED www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/07.1_RGBLED RGBLED.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
micro:bit, and RGBLED will emit yellow color. (How to download?)
A custom map() function is used to convert a value in one range to another range.
def map(value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 83
In this kit, three LEDs of RGB LED share a common anode(+) and their negative pins need to be set to LOW
level to have the RGB LED work. And the value of variables ‘red’, ‘green’, and ‘blue’ need to be converted from
the value ranging from 0-255 to analog signal values ranging from1023-0.
red=map(red,0,255,1023,0)
green=map(green,0,255,1023,0)
blue=map(blue,0,255,1023,0)
Write the ‘red’, ‘green’, ‘blue’ to corresponding pins P2, P1, P0.
pin2.write_analog(red)
pin1.write_analog(green)
pin0.write_analog(blue)
Reference
map(value,fromLow,fromHigh,toLow,toHigh)
A custom function that converts a value in a range of numbers to a value in another range of numbers. For
example, map(8,0,10,0,100) returns a value of 80; map(8,0,10,100,0)=20.
map(8,0,10,0,100)=80.
[email protected] █
84 Chapter 7 RGBLED www.freenove.com █
Component list
HSL color
The HSL color mode is another color standard in the industry. It obtains a variety of colors by changing the
three color channels of hue (H), saturation (S), and lightness (L) and superimposing them with each other. This
color mode covers almost all colors that human vision can perceive. It is one of the most widely used color
systems to date.
As shown in the hue circle below, the 0 degree of the hue is R (red) color, 120 degrees is G (green) color, and
240 degrees is B (blue) color. Each angle represents a color. The default saturation (S) takes the maximum
value 100, the brightness (L) takes 50. If the hue angle is changed, the color will be changed. And the HSL
color system can be converted to the RGB color system, to change the color of the LED.
0°
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 85
Circuit
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/07.2_ColorfulLight ColorfulLight.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
the microbit, and RGBLED will emit different colors.
From the knowledge of HSL color, we can know that different hue angles correspond different colors. The
variable index represents hue angle, ranging from 0 to 360.
[email protected] █
86 Chapter 7 RGBLED www.freenove.com █
This block is to convert the HSL color system to the RGB color system, return the RGB value corresponding
to the current hue angle, and store the value in the variable RGBColor. For example: hexadecimal RGB value
0xFF0000 means red, FF is the value of the red channel in RGB, and 00 and 00 are the values of the green
and blue channels, respectively.
Assign the value of the lower eight-bit to blue channel, the value of the middle eight-bit to green channel,
and the value of the upper eight-bit to red channel.
In this kit, three LEDs of RGB LED share a common anode (+) and their negative pins need to be set to LOW
level to have the RGB LED work. And the variables ‘red’, ‘green’, and ‘blue’ need to be converted from the
value ranging from 0-255 to analog signal values ranging from1023-0.
Every 10ms, write the ‘red’, ‘green’, ‘blue’ to corresponding pins P2, P1, P0.
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 87
Reference
Block Function
This is an extra operator for division. You can find
out how much is left over if one number doesn’t
divide into the other number evenly.
Convert HSL color system to RGB color system, and
return the RGB value corresponding to the current
hue angle. It belongs to Neopixel expansion block.
Extensions
You can import Neopixel expansion block into new project as below:
1, Click “Advanced” to
Expand list.
2, Click “Extension”
[email protected] █
88 Chapter 7 RGBLED www.freenove.com █
3, Search “neopixel”
It is completed.
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 89
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/07.2_ColorfulLight ColorfulLight.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
the microbit, and RGBLED will emit different colors. (How to download?)
[email protected] █
90 Chapter 7 RGBLED www.freenove.com █
The map() function is used to convert a value in one range to another range.
def map(value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
█ [email protected]
█ www.freenove.com Chapter 7 RGBLED 91
The HSL_RGB() function is used to convert the HSL color system to RGB color, and return the RGB value
corresponding to the current hue angle.
def HSL_RGB (degree):
degree=degree/360*255
if degree < 85:
red = 255 - degree * 3
green = degree * 3
blue = 0
elif degree < 170:
degree = degree - 85
red = 0
green = 255 - degree * 3
blue = degree * 3
else:
degree = degree - 170
red = degree * 3
green = 0
blue = 255 - degree * 3
return red,green,blue
Repeat 360 times, display the hue angle color corresponding to 0 to 360 degrees, and replace it every 10ms.
while True:
for i in range(360):
red,green,blue=HSL_RGB(i)
red=map(red,0,255,1023,0)
green=map(green,0,255,1023,0)
blue=map(blue,0,255,1023,0)
pin2.write_analog(red)
pin1.write_analog(green)
pin0.write_analog(blue)
sleep(10)
Reference
HSL_RGB(degree)
Custom function, used to convert HSL color system to RGB color system, return the RGB value
corresponding to the current hue angle, for example: HSL_RGB(0), return red RGB value: red=255, green=0,
blue=0.
[email protected] █
92 Chapter 8 Neopixel www.freenove.com █
Chapter 8 Neopixel
In this chapter, we will learn Freenove 8 RGB LED Module
Component list
█ [email protected]
█ www.freenove.com Chapter 8 Neopixel 93
Component knowledge
And you can also control many modules at the same time. Just connect OUT pin of one module to IN pin of
another module. In such way, you can use one data pin to control 8, 16, 32 … LEDs.
Pin description:
(IN) (OUT)
symbol Function symbol Function
S Input control signal S Output control signal
V Power supply pin, +3.5V~5.5V V Power supply pin, +3.5V~5.5V
G GND G GND
[email protected] █
94 Chapter 8 Neopixel www.freenove.com █
Circuit
Schematic diagram
Hardware connection
8 RGB LED
Connect to
Module requires
computer
5V. Pay attention
to the wiring.
█ [email protected]
█ www.freenove.com Chapter 8 Neopixel 95
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/08.1_Neopixel Neopixel.hex
After import successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, download the code into the micro:bit, and then you
can see the rainbow water light.
Set the number of data pins and LEDs at "on start", as well as the type of LED.
In the 0-360 for loop, the hue difference between each two LEDs is 45. When the hue changes, each LED
succeeds the hue of the previous LED. And then the program converts the HSL color system to the RGB color
system, returns the RGB value corresponding to the current hue angle and write the value to LED to achieve
the effect of the rainbow water light.
[email protected] █
96 Chapter 8 Neopixel www.freenove.com █
Reference
Block Function
Set the number of data pins and LEDs, as
well as the type of LED.
Set LED color
Turn on LED
█ [email protected]
█ www.freenove.com Chapter 8 Neopixel 97
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/08.1_Neopixel Neopixel.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, confirm that the connection of the circuit is correct, download the code
into the micro:bit, and then you can see the rainbow water light. (How to download?)
[email protected] █
98 Chapter 8 Neopixel www.freenove.com █
█ [email protected]
█ www.freenove.com Chapter 8 Neopixel 99
Custom HSL_RGB() function is used to convert HSL color to RGB color, returning the RGB value corresponding
to the current hue angle.
def HSL_RGB(degree):
degree=degree/360*255
if degree < 85:
red = 255 - degree * 3
green = degree * 3
blue = 0
elif degree < 170:
degree = degree - 85
red = 0
green = 255 - degree * 3
blue = degree * 3
else:
degree = degree - 170
red = degree * 3
green = 0
blue = 255 - degree * 3
return int(red),int(green),int(blue)
In the 0-360 for loop, the hue difference between each two LEDs is 45. When the hue changes, each LED
succeeds the hue of the previous LED. And then the program converts the HSL color system to the RGB color
system, returns the RGB value corresponding to the current hue angle, and writes the value to LED to achieve
the effect of the rainbow water light.
while True:
for value in range(0,360,5):
for i in range(8):
value=value+i*45
if value > 360 :
value = value-360
red,green,blue=HSL_RGB(value)
np[i] = (red,green,blue)
np.show()
Reference
neopixel.NeoPixel(pin, n)
Initialize a new strip of n number of neopixel LEDs controlled via pin pin.
show()
Show the pixels. Must be called for any updates to become visible.
np[i]
Set pixels by indexing them (like with a Python list).
[email protected] █
100 Chapter 9 Buzzer www.freenove.com █
Chapter 9 Buzzer
In this chapter, we will learn about buzzers and the sounds they make. There are two kinds of buzzer: active
buzzer and passive buzzer.
Component knowledge
Transistor
A transistor is required in this project due to the buzzer’s current being so great that GPIO of RPi’s output
capability cannot meet the power requirement necessary for operation. A NPN transistor is needed here to
amplify the current.
Transistors, full name: semiconductor transistor, is a semiconductor device that controls current (think of a
transistor as an electronic “amplifying or switching device”. Transistors can be used to amplify weak signals,
or to work as a switch. Transistors have three electrodes (PINs): base (b), collector (c) and emitter (e). When
there is current passing between "be" then "ce" will have a several-fold current increase (transistor
magnification), in this configuration the transistor acts as an amplifier. When current produced by "be"
exceeds a certain value, "ce" will limit the current output. at this point the transistor is working in its saturation
region and acts like a switch. Transistors are available as two types as shown below: PNP and NPN,
In our kit, the PNP transistor is marked with 8550, and the NPN transistor is marked with 8050.
Thanks to the transistor's characteristics, they are often used as switches in digital circuits. As micro-controllers
output current capacity is very weak, we will use a transistor to amplify its current in order to drive components
requiring higher current.
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 101
Buzzer
A buzzer is an audio component. They are widely used in electronic devices such as calculators, electronic
alarm clocks, automobile fault indicators, etc. There are both active and passive types of buzzers. Active
buzzers have oscillator inside, these will sound as long as power is supplied. Passive buzzers require an
external oscillator signal (generally using PWM with different frequencies) to make a sound.
Active buzzers are easier to use. Generally, they only make a specific sound frequency. Passive buzzers
require an external circuit to make sounds, but passive buzzers can be controlled to make sounds of various
frequencies. The resonant frequency of the passive buzzer in this Kit is 2kHz, which means the passive
buzzer is the loudest when its resonant frequency is 2kHz.
Buzzer requires large current when it works. But generally, microcontroller port cannot provide enough
current for that. In order to control buzzer through micro:bit, a transistor can be used to drive a buzzer
indirectly.
When we use a NPN transistor to drive a buzzer, we often use the following method. If GPIO outputs high
level, current will flow through R1 (Resistor 1), the transistor conducts current and the buzzer will make
sounds. If GPIO outputs low level, no current will flow through R1, the transistor will not conduct current and
buzzer will remain silent (no sounds).
[email protected] █
102 Chapter 9 Buzzer www.freenove.com █
When we use a PNP transistor to drive a buzzer, we often use the following method. If GPIO outputs low
level, current will flow through R1. The transistor conducts current and the buzzer will make sounds. If GPIO
outputs high level, no current flows through R1, the transistor will not conduct current and buzzer will
remain silent (no sounds). Below are the circuit schematics for both a NPN and PNP transistor to power a
buzzer.
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 103
[email protected] █
104 Chapter 9 Buzzer www.freenove.com █
Component list
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 105
Circuit
Schematic diagram
Hardware connection
Active buzzer
[email protected] █
106 Chapter 9 Buzzer www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/09.1_ActiveBuzzer ActiveBuzzer.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, download the code into the micro:bit, and the buzzer on the breadboard
will make sounds.
In the for loop, P0 outputs a high level to make the buzzer sounds, then delay 100ms. And then P0 outputs a
low level to stop the buzzer. Then delay 100ms. After the loop ends, delay 500ms.
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 107
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/09.1_ActiveBuzzer ActiveBuzzer.py
After load successfully, the code is shown as below:
Check the connection of the circuit, download the code into the micro:bit, and the buzzer on the breadboard
will sound.
In the for loop, P0 outputs a high level to make the buzzer sound, then delay 100ms. And then P0 outputs a
low level to stop the buzzer. Then delay 100ms. After the loop ends, delay 500ms.
1 while True:
2 for i in range(4):
3 pin0.write_digital(1)
4 sleep(100)
5 pin0.write_digital(0)
6 sleep(100)
7 sleep(500)
[email protected] █
108 Chapter 9 Buzzer www.freenove.com █
In this project, we will make a passive buzzer to play a happy birthday melody.
Component list
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 109
Circuit
Schematic diagram
Hardware connection
Passive buzzer
[email protected] █
110 Chapter 9 Buzzer www.freenove.com █
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 111
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/09.2_Play-a-melody Play-a-melody.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
the micro:bit, and the buzzer on the breadboard will play a song “happy birthday”.
You can click on the small triangle next to "birthday" to expand the list, select other melody, and select the
number of times to play by clicking on the small triangle next to "once".
Reference
Block Function
Begin playing a musical melody through pin P0 of the
micro:bit. There are built-in melodies that you can
choose from the start melody block. These are already
composed for you and are easy to use by just selecting
the one you want.
[email protected] █
112 Chapter 9 Buzzer www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/09.2_Play-a-melody Play-a-melody.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, and download the code
into the micro:bit, and the buzzer on the breadboard will play a song “happy birthday”. (How to download?)
Reference
music.play()
It is used to play music. MicroPython has quite a lot of built-in melodies.
For more information, please refer to:
https://microbit-micropython.readthedocs.io/en/latest/tutorials/music.html
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 113
In this project, we will make the passive buzzer play a custom melody.
Component list
[email protected] █
114 Chapter 9 Buzzer www.freenove.com █
Circuit
Schematic diagram
Hardware connection
Passive buzzer
█ [email protected]
█ www.freenove.com Chapter 9 Buzzer 115
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/09.3_Play-a-custom-melody Play-a-custom-melody.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
the micro:bit, and the buzzer on the breadboard will play a custom melody.
The tune array holds a custom melody, and each element in the array contains notes and beats. For example,
"A1:4" refers to the note named A in octave number 1 to be played for a duration of 4.
[email protected] █
116 Chapter 9 Buzzer www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/09.3_Play-a-custom-melody Play-a-custom-melody.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, confirm that the circuit is connected correctly, download the code into
the micro:bit, and the buzzer on the breadboard will play a custom song.
The tune array holds a custom melody, and each element in the array contains notes and beats. For example,
"A1:4" refers to the note named A in octave number 1 to be played for a duration of 4.
█ [email protected]
█ www.freenove.com Chapter 10 Serial Communication 117
This project uses serial ports to transmit data and display data.
Component list
Circuit
[email protected] █
118 Chapter 10 Serial Communication www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/10.1_SerialPort SerialPort.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit and verify it correct download the code into the micro:bit, and then open
the serial controller, as shown below:
On the serial console, you can see the data sent by the microbit.
█ [email protected]
█ www.freenove.com Chapter 10 Serial Communication 119
Every 1 second, the value of the variable number is incremented by 1, and the new value will be sent to the
serial port.
Reference
Block Function
Write a name:value pair and a newline character (\r\n) to the serial
port.
The change blocks increase the value in the variable by the amount
you want. This is also known as an addition assignment operation.
[email protected] █
120 Chapter 10 Serial Communication www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/10.1_SerialPort SerialPort.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct and then download the code into the micro:bit.
Then press the reset button (the button on the back) of the Micro:bit and we will see the change of value.
█ [email protected]
█ www.freenove.com Chapter 10 Serial Communication 121
Every 1 second, the value of the variable number is incremented by 1, and the new value will be sent to the
serial port, where "\r\n" is the meaning of the newline.
uart.write('Counter: '+str(number)+ "\r\n")
sleep(1000)
number=number+1
Reference
uart.write(x)
Write the buffer to the bus, it can be a bytes object or a string:
uart.write('hello world')
uart.write(b'hello world')
uart.write(bytes([1, 2, 3]))
For more information, please refer to:
https://microbit-micropython.readthedocs.io/en/latest/uart.html
[email protected] █
122 Chapter 11 Magnetometer www.freenove.com █
Chapter 11 Magnetometer
In this chapter, we will learn the micro:bit built-in magnetometer chip.
This project will print the data obtained from the magnetometer chip on the serial console.
Component list
Circuit
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 123
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/11.1_DisplayMagnetometerData DisplayMagnetometerData.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, and then download the code into the micro:bit. After
completing downloading, the magnetometer needs to be calibrated (calibration must be performed using the
magnetometer program). Calibrating the magnetometer will cause the program to pause until the calibration
is completed. Start the calibration process, a prompt will scroll on the LED matrix, which indicates that you
need to rotate the micro:bit until all LEDs on the LED screen are illuminated, and then a smile is displayed
which means the calibration is completed, as shown below:
[email protected] █
124 Chapter 11 Magnetometer www.freenove.com █
Then open the serial console (Open the Serial Port), place the micro:bit horizontally on the desktop, and rotate
the micro:bit (clockwise or counterclockwise) to see the angular offset read from the magnetometer chip. As
shown below:
The angular offset is the angle between the directions of the micro:bit and the geographic North Pole, as
shown in the following figure.
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 125
The angular offset read from the magnetometer chip is stored in the variable azimuth.
Then the value of the variable azimuth is printed on the serial port interface.
Reference
Block Function
[email protected] █
126 Chapter 11 Magnetometer www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/11.1_DisplayMagnetometerData DisplayMagnetometerData.py
After loading successfully, the code is shown as below:
After checking the connection of the circuit and verify it correct, download the code into micro:bit.
Then press the reset button of the Micro:bit, you need to calibrate the magnetometer (the calibration must
be performed when downloading using the magnetometer program).
Calibrating the magnetometer will cause the program to pause until the calibration is complete. Start the
calibration process, a prompt will scroll on the LED matrix, which indicates that you need to rotate the micro:bit
until all LEDs on the LED screen are illuminated, and then a smile is displayed which means the calibration is
completed, as shown below:
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 127
Place the micro:bit horizontally on the desktop, and rotate the micro:bit (clockwise or counterclockwise) to
see the angular offset read from the magnetometer chip. As shown below:
[email protected] █
128 Chapter 11 Magnetometer www.freenove.com █
The angular offset is the angle between the direction of the micro:bit and the geographic north pole, as shown
in the following figure.
Magnetometer calibration.
compass.calibrate()
The angular offset read from the magnetometer chip is stored in the variable azimuth and then printed out
every 1s through a serial port.
azimuth = compass.heading()
uart.write(str(azimuth)+"\r\n")
sleep(1000)
Reference
compass.calibrate()
Starts the calibration process. An instructive message will scroll on the LED matrix, which indicates that you
need to rotate the micro:bit until all LEDs are illuminated.
compass.heading()
Gives the compass heading, calculated from the above readings, as an integer in the range from 0 to 360,
representing the angle in degrees, clockwise, with north as 0.
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 129
In this project, we will use micro:bit to make an electronic compass, displaying an arrow on the micro:bit, and
the arrow always points to the geographic north pole.
Component list
Circuit
[email protected] █
130 Chapter 11 Magnetometer www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/11.2_ElectronicCompass ElectronicCompass.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, and then download the code into the micro:bit.
Calibrate the electronic compass. After the calibration is successful, place the micro:bit horizontally and turn
the micro:bit to see that the arrow points to the geography Arctic.
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 131
The arrow will point to eight directions: northwest, west, southwest, south, southeast, east, northeast, north,
each direction is 45 degrees apart. Assuming that the direction of the micro:bit is rotated 45 degrees from the
north to the northeast of the geography, the arrow shown should be reversed, that is, it rotates
-45 degrees, pointing to the northwest of the micro:bit, which is the geographic north pole. Therefore, we
can adjust the direction of the arrow according to its angular offset from the geographic North Pole.
When the variable azimuth is less than 22.5 or greater than 337.5, the arrow points to the due north of the
micro:bit.
When the variable azimuth is greater than 22.5 or less than 67.5, the arrow points to the northwest of the
micro:bit.
And so on in the same fashion, in every 45 degrees, the arrow points to a particular direction indicating the
geographic north, as shown in the following illustration:
[email protected] █
132 Chapter 11 Magnetometer www.freenove.com █
The angular offset read from the magnetometer chip is stored in the variable azimuth
Determine the value of the variable azimuth to change the direction of the arrow.
Reference
Block Function
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 133
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/11.2_ElectronicCompass ElectronicCompass.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct,, download the code into the micro:bit and calibrate
the electronic compass. After the calibration is successful, place the micro:bit horizontally and rotate the
micro:bit to see that the arrow points to the geography Arctic.
[email protected] █
134 Chapter 11 Magnetometer www.freenove.com █
The arrow will point to eight directions:: northwest, west, southwest, south, southeast, east, northeast, north,
each direction is 45 degrees apart. Assuming that the direction of the micro:bit is rotated 45 degrees from the
north to the northeast of the geography, the arrow shown should be reversed, that is, rotated -45 degrees,
pointing to the northwest of the micro:bit, which is the geographic north pole. Therefore, the direction of the
arrow is adjusted according to the angular offset from the geographic North Pole.
When the variable azimuth is less than 22.5 or greater than 337.5, the arrow points to the true north of the
micro:bit.
When the variable azimuth is greater than 22.5 and less than 67.5, the arrow points to the northwest of the
micro:bit.
And so on in the same fashion, in every 45 degrees, the arrow points to a particular direction indicating the
geographic north, as shown in the following figure:
█ [email protected]
█ www.freenove.com Chapter 11 Magnetometer 135
Calibrate the electronic compass first and store the data on the variable azimuth.
compass.calibrate()
azimuth = compass.heading()
Determine the value of the variable azimuth and change the direction of the arrow.
if azimuth<22.5 and azimuth<67.5:
display.show(Image.ARROW_NW)
elif azimuth<67.5 and azimuth<112.5:
display.show(Image.ARROW_W)
elif azimuth<112.5 and azimuth<157.5:
display.show(Image.ARROW_SW)
elif azimuth<157.5 and azimuth<202.5:
display.show(Image.ARROW_S)
elif azimuth<202.5 and azimuth<247.5:
display.show(Image.ARROW_SE)
elif azimuth<247.5 and azimuth<292.5:
display.show(Image.ARROW_E)
elif azimuth<292.5 and azimuth<337.5:
display.show(Image.ARROW_NE)
elif azimuth<22.5 and azimuth>337.5:
display.show(Image.ARROW_N)
[email protected] █
136 Chapter 12 Accelerometer www.freenove.com █
Chapter 12 Accelerometer
In this chapter, we will learn about the built-in accelerometer sensor of micro:bit.
In this project, we will obtain data from the accelerometer sensor and print it on the serial console.
Component list
Circuit
█ [email protected]
█ www.freenove.com Chapter 12 Accelerometer 137
Block code
Check the connection of the circuit and verify it correct, download the code into the micro:bit, and then open
the serial console, you can see the data of the accelerometer, as shown below:
[email protected] █
138 Chapter 12 Accelerometer www.freenove.com █
Read the value of the accelerometer in three directions and print it out through the serial port every second.
█ [email protected]
█ www.freenove.com Chapter 12 Accelerometer 139
Reference
Block Function
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../PythonCode/12.1_DisplayAccelerometerData DisplayAccelerometerData.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, and then download the code into the micro:bit.
After the program is downloaded, open the plotter (Plotter), click on the REPL, you can see the x-axis, y-axis,
z-axis data collected by the accelerometer, as shown below:
[email protected] █
140 Chapter 12 Accelerometer www.freenove.com █
Every 1 second, the accelerometer data will be obtained and printed through the serial port.
1 uart.write(str(accelerometer.get_values())+"\r\n")
2 sleep(1000)
Reference
accelerometer.get_values()
Get the acceleration measurements in all axes at once, as a three-element tuple of integers ordered as X,
Y, Z. By default the accelerometer is configured with a range of +/- 2g, so X, Y, and Z will be within the
range of +/-2000mg.
█ [email protected]
█ www.freenove.com Chapter 12 Accelerometer 141
Component list
Circuit
[email protected] █
142 Chapter 12 Accelerometer www.freenove.com █
Block code
Check the connection of the circuit and verify it correct and download the code into micro:bit, you will observe
that the LED dot matrix will change with the tilt of micro:bit.
Detect the flip angle of the microbit in the x-axis and the y-axis. The return value ranges from -180 to 180
degrees. This project does not require such a wide range of flip angles, so we just set it within -30 to 30
degrees.
Since the LED screen is 5x5, map the range of -30-30 to the range of 0-4, and assign it to the X, Y variable.
█ [email protected]
█ www.freenove.com Chapter 12 Accelerometer 143
Turn OFF all the LED first, then turn ON the corresponding LED according to the value of the X, Y variables.
Reference
Block Function
Find how much the micro:bit is tilted in
different directions.
[email protected] █
144 Chapter 12 Accelerometer www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/12.2_Gradienter Gradienter.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, download the code into micro:bit, you will observe
that the LED dot matrix will change with the tilt of micro:bit.
█ [email protected]
█ www.freenove.com Chapter 12 Accelerometer 145
A custom mapping() function limits the input value to a range of -400 to 400 and maps to a range of 0-4.
def mapping(value):
if value < -400 :
value=-400
elif value > 400 :
value=400
value=(value+400)/200
return int(value)
Read the value of the accelerometer X, Y-axis direction. The return value range is -2000-2000. This project
does not require such a wide range, So we set it to the range of -400to 400. Call the mapping() function to
return the value ranging from 0-4 , lighting the LED corresponding to the x row and the y column.
while True:
value_x = accelerometer.get_x()
value_y = accelerometer.get_y()
x=mapping(value_x)
y=mapping(value_y)
display.clear()
display.set_pixel(x, y, 9)
Reference
display.clear()
Set the brightness of all LEDs to 0 (off).
display.set_pixel(x,y,9)
Set the brightness value of the LED at column x and row y, which has to be an integer between 0 and 9.
accelerometer.get_x()
Get the acceleration measurement in the x axis, as a positive or negative integer, depending on the
direction. The measurement is given in milli-g. By default the accelerometer is configured with a range of
+/- 2g, and so this method will return a value within the range of +/- 2000mg
accelerometer.get_y()
Get the acceleration measurement in the y axis, as a positive or negative integer, depending on the
direction. The measurement is given in milli-g. By default the accelerometer is configured with a range of
+/- 2g, and so this method will return a value within the range of +/- 2000mg.
[email protected] █
146 Chapter 13 Potentiometer www.freenove.com █
Chapter 13 Potentiometer
In this chapter, we will learn a new component: potentiometer
Component list
█ [email protected]
█ www.freenove.com Chapter 13 Potentiometer 147
Component knowledge
ADC
An ADC is an electronic integrated circuit used to convert analog signals such as voltages to digital or binary
form consisting of 1s and 0s. The range of our ADC module is 10 bits, that means the resolution is
2^10=1024, so that its range (at 3.3V) will be divided equally to 1024 parts.
Any analog value can be mapped to one digital value using the resolution of the converter. So the more bits
the ADC has, the denser the partition of analog will be and the greater the precision of the resulting conversion.
Potentiometer
Potentiometer is a resistive element with three Terminal parts. Unlike the resistors that we have used thus
far in our project which have a fixed resistance value, the resistance value of a potentiometer can be
adjusted. A potentiometer is often made up by a resistive substance (a wire or carbon element) and
movable contact brush. When the brush moves along the resistor element, there will be a change in the
resistance of the potentiometer’s output side (3) (or change in the voltage of the circuit that is a part). The
illustration below represents a linear sliding potentiometer and its electronic symbol on the right.
1 32
[email protected] █
148 Chapter 13 Potentiometer www.freenove.com █
Between potentiometer pin 1 and pin 2 is the resistive element (a resistance wire or carbon) and pin 3 is
connected to the brush that makes contact with the resistive element. In our illustration, when the brush
moves from pin 1 to pin 2, the resistance value between pin 1 and pin 3 will increase linearly (until it reaches
the highest value of the resistive element) and at the same time the resistance between pin 2 and pin 3 will
decrease linearly and conversely down to zero. At the midpoint of the slider the measured resistance values
between pin 1 and 3 and between pin 2 and 3 will be the same.
In a circuit, both sides of resistive element are often connected to the positive and negative electrodes of
power. When you slide the brush “pin 3”, you can get variable voltage within the range of the power supply.
Rotary potentiometer
Rotary potentiometers and linear potentiometers have the same function; the only difference being the
physical action being a rotational rather than a sliding movement.
█ [email protected]
█ www.freenove.com Chapter 13 Potentiometer 149
Circuit
Schematic diagram
Hardware connection
[email protected] █
150 Chapter 13 Potentiometer www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/13.1_Potentiometer Potentiometer.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit and verify it correct and then download the code into micro:bit.
Click on the console device, rotate the potentiometer, you will see the output ADC value and voltage value.
█ [email protected]
█ www.freenove.com Chapter 13 Potentiometer 151
Read the analog voltage value of the P0 pin, the range is 0-1023, and then convert the analog voltage value
into a digital voltage value.
Print the analog voltage and digital voltage of P0 pin every 1 second.
Reference
Block Function
[email protected] █
152 Chapter 13 Potentiometer www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/13.1_Potentiometer Potentiometer.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and confirm that the circuit is connected correctly. Download the code
into the micro:bit. (How to download?)
Click on the REPL, press the micro:bit reset button, and then rotate the potentiometer. You can see the change
in the value on the software Mu, as shown below.
█ [email protected]
█ www.freenove.com Chapter 13 Potentiometer 153
Read the analog voltage value of the P0 pin, the range is 0-1023, and then convert the analog voltage value
into a digital voltage value.
ADC = pin0.read_analog()
voltage = ADC/1023*3.3
Print the analog voltage and digital voltage of P0 pin every 1 second.
print("convertvalue: "+str(ADC)+" voltage: "+str(voltage))
sleep(1000)
Reference
read_analog()
Read an analog signal (0 to 1023) from the pin you set.
print()
Print() is a Python built-in function for printing.
[email protected] █
154 Chapter 14 Potentiometer and LED www.freenove.com █
Component list
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 155
Circuit
In this circuit, the port 1 and 2 of the potentiometer are respectively connected to the two ends of the power
supply, and the port3 is connected to the P0 pin of the micro:bit.
Schematic diagram
Hardware connection
P1 pin is connected to LED’s long pin (positive), and its short pin (negative) is connected to resistor.
[email protected] █
156 Chapter 14 Potentiometer and LED www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/14.1_SoftLight SoftLight.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct,, download the code into the micro:bit, and rotate the
potentiometer to see the change of the brightness.
Read the analog voltage value of the P0 pin, then the P1 pin outputs the same analog voltage value.
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 157
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/14.1_SoftLight SoftLight.py
After load successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, download the code into the micro:bit, and rotate the
potentiometer to see the change of the brightness of the LED.
The following is the program code:
1 from microbit import *
2 while True:
3 pin1.write_analog(pin0.read_analog())
Read the analog voltage value of the P0 pin, then the P1 pin outputs the same analog voltage value.
pin1.write_analog(pin0.read_analog())
[email protected] █
158 Chapter 14 Potentiometer and LED www.freenove.com █
Component list
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 159
Circuit
Schematic diagram
Hardware connection
RGBLED’s long pin (anode) is connected to 3.3V power supply.
[email protected] █
160 Chapter 14 Potentiometer and LED www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/14.2_ColorfulSoftLight ColorfulSoftLight.hex
After importing successfully, the code is shown as below:
Download the code into micro:bit, rotate the potentiometer, you can see that the color of the RGBLED is
changing.
Read the potentiometer's analog voltage and map the potentiometer's analog voltage ranging 0-1023 to the
hue angle ranging 0-360.
Convert the HSL color system to the RGB color system, return the RGB value corresponding to the current
hue angle, and store the value in the variable RGBColor.
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 161
The value of the lower eight-bit blue channel of the variable RGBColor is assigned to the variable blue, the
value of the middle eight-bit green channel is assigned to the variable green, and the value of the upper
eight-bit red channel is assigned to the variable red.
RGBLED is a common anode, so the pins are set to low to turn on the RGBLED. The values of the variables
'red', 'green', and 'blue' are converted from 0-255 to analog signal values in the range of 1023-0, and then
reassigned to 'red', 'green', 'blue 'variable. In this kit, three LEDs of RGB LED share a common anode(+) and
their negative pins need to be set to LOW level to turn ON the RGB LED work. And the value of variables ‘red’,
‘green’, and ‘blue’ need to be converted from the value ranging from 0-255 to analog signal values ranging
from 1023-0, and then reassigned to them.
Write the analog voltage value of the red, green, and blue variables to the corresponding P0, P1, and P2 pins
to change the LED color.
[email protected] █
162 Chapter 14 Potentiometer and LED www.freenove.com █
Python code
After checking the connection of the circuit, verify it correct, download the code into micro:bit. By rotating
the potentiometer, you can see that the color of RGB LED is changing.
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 163
Turn OFF the LED screen to use the P3 pin. A custom map() function converts values in one range of numbers
to values in another range of numbers.
display.off()
def map(value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
[email protected] █
164 Chapter 14 Potentiometer and LED www.freenove.com █
The custom function HSL_RGB()is used to convert the HSL color system to the RGB color system and return
the RGB value corresponding to the current hue angle.
def HSL_RGB(degree):
degree=degree/360*255
if degree < 85:
red = 255 - degree * 3
green = degree * 3
blue = 0
elif degree < 170:
degree = degree - 85
red = 0
green = 255 - degree * 3
blue = degree * 3
else:
degree = degree - 170
red = degree * 3
green = 0
blue = 255 - degree * 3
return red,green,blue
Read the analog voltage value of the P3 pin and convert it to the corresponding hue angle. Call the HSL_RGB()
function to return the RGB value corresponding to the current hue angle, and then write the corresponding
RGB values to the P0, P1, and P2 pins to change the LED color.
while True:
value=map(pin3.read_analog(),0,1023,0,360)
red,green,blue=HSL_RGB(value)
print(red,green,blue)
red=map(red,0,255,1023,0)
green=map(green,0,255,1023,0)
blue=map(blue,0,255,1023,0)
pin2.write_analog(red)
pin1.write_analog(green)
pin0.write_analog(blue)
sleep(10)
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 165
Component list
[email protected] █
166 Chapter 14 Potentiometer and LED www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 167
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/14.3_RainbowLight RainbowLight.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, download the code into the micro:bit, rotate the
potentiometer, and the color ring of the RGB LED module also rotates.
Set the number of pins and LEDs for the RGB LED module, as well as the type of LED.
Read the voltage of the potentiometer and map the analog value of 0-1023 to an angle of 0-360.
In the for loop, the hue difference between each two LEDs is 45. When the hue changes, it ensures that the
LED succeeds the hue of the previous LED. Then it converts the HSL color system to the RGB color system,
and returns the RGB value corresponding to the angle, to make the LED to achieve the effect of the rainbow.
[email protected] █
168 Chapter 14 Potentiometer and LED www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/14.3_RainbowLight RainbowLight.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into the micro:bit. Rotate the
potentiometer, and then the color ring of the RGB LED module also rotates.
█ [email protected]
█ www.freenove.com Chapter 14 Potentiometer and LED 169
[email protected] █
170 Chapter 14 Potentiometer and LED www.freenove.com █
Set the number of pins and LED to control the RGB LED module.
np = neopixel.NeoPixel(pin0, 8)
Custom HSL_RGB() function is used to convert HSL color to RGB color, returning the RGB value corresponding
to the current hue angle.
def HSL_RGB(degree):
degree=degree/360*255
if degree < 85:
red = 255 - degree * 3
green = degree * 3
blue = 0
elif degree < 170:
degree = degree - 85
red = 0
green = 255 - degree * 3
blue = degree * 3
else:
degree = degree - 170
red = degree * 3
green = 0
blue = 255 - degree * 3
return int(red),int(green),int(blue)
In the for loop, the analog voltage of the potentiometer is read and converted to the corresponding hue
angle. The hue difference between each two led is 45. The HSL_RGB() function is called to convert the HSL
color system to the RGB color system, return the RGB value corresponding to the current hue angle to make
the LED achieve the effect of rainbow.
while True:
for i in range(0, 8):
value=pin1.read_analog()/1023*360+i*45
if value > 360 :
value = value-360
red,green,blue=HSL_RGB(value)
np[i] = (red,green,blue)
np.show()
█ [email protected]
█ www.freenove.com Chapter 15 Light Sensor 171
In this project, we use the micro:bit built-in light sensor to measure the brightness of light.
Component list
Component knowledge
Light sensor
Micro:bit detects the ambient light intensity through the LED matrix. In forward bias mode, the LED screen
works as a display. In reverse bias mode, the LED screen works as a basic light sensor that can be used to
detect ambient light.
[email protected] █
172 Chapter 15 Light Sensor www.freenove.com █
Circuit
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/15.1_LightIntensityMeter LightIntensityMeter.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct and download the code into the micro:bit. Open the serial
port console, then you can see the reading light intensity. Cover the LED screen with your hand or increase
the light shining on it, you can see the change in value, the range of values is 0-255, 0 is dark, 255 is the
brightest, as shown below.
█ [email protected]
█ www.freenove.com Chapter 15 Light Sensor 173
Reference
Block Function
Detect the light level (how bright or dark it is) of the
environment where you are. The light level 0 means
darkness and 255 means bright light.
[email protected] █
174 Chapter 15 Light Sensor www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/15.1_LightIntensityMeter LightIntensityMeter.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, download the code into the micro:bit. Open the serial
port console, then you can see the reading light intensity. Cover the LED screen with your hand or increase
the light shining on it, you can see the change in value, the range of values is 0-255, 0 is dark, 255 is the
brightest, as shown below.
█ [email protected]
█ www.freenove.com Chapter 15 Light Sensor 175
Reference
display.read_light_level()
Use the display’s LEDs in reverse-bias mode to sense the amount of light falling on the display, return an
integer between 0 and 255 representing the light level. The larger the value, the brighter the light..
[email protected] █
176 Chapter 15 Light Sensor www.freenove.com █
Component list
Resistor 220Ω x1
█ [email protected]
█ www.freenove.com Chapter 15 Light Sensor 177
Component knowledge
Photoresistor
A Photoresistor is simply a light sensitive resistor. It is an active component that decreases resistance with
respect to receiving luminosity (light) on the component's light sensitive surface. A Photoresistor’s resistance
value will change in proportion to the ambient light detected. With this characteristic, we can use a
Photoresistor to detect light intensity. The Photoresistor and its electronic symbol are as follows.
The circuit below is often used to detect the change of a photoresistor’s resistance value:
In the above circuit, when a Photoresistor’s resistance vale changes due to a change in light intensity, the
voltage between the Photoresistor and Resistor R1 will also change. Therefore, the intensity of the light can
be obtained by measuring this voltage.
[email protected] █
178 Chapter 15 Light Sensor www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 15 Light Sensor 179
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/15.2_NightLight NightLight.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into the micro:bit. Cover the
photoresistor with your hand, the LED is turned ON. Move the hand away, the LED is turned OFF.
[email protected] █
180 Chapter 15 Light Sensor www.freenove.com █
If the analog voltage read is greater than or equal to 400, it is considered to be occluded, and the LED is
turned ON. Or the LED is turned OFF.
█ [email protected]
█ www.freenove.com Chapter 15 Light Sensor 181
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/15.2_NightLight NightLight.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into the micro:bit. Cover the
photoresistor with your hand, then the LED is turned ON. Move the hand away, then the LED is turned OFF.
[email protected] █
182 Chapter 15 Light Sensor www.freenove.com █
If the analog voltage read is greater than or equal to 400, it is considered to be occluded, and the LED is
turned ON. Otherwise the LED is turned OFF.
if value>=400:
pin1.write_digital(1)
else:
pin1.write_digital(0)
█ [email protected]
█ www.freenove.com Chapter 16 Temperature Sensor 183
In this project, we measure the temperature with the micro:bit’s built-in temperature sensor.
Component list
Circuit
[email protected] █
184 Chapter 16 Temperature Sensor www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/16.1_BuiltInThermometer BuiltInThermometer.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into micro:bit, and then LED
dot matrix screen will display the current detected temperature.
Reference
Block Function
Detect the temperature of the environment
where you are. The temperature is measured
in Celsius (metric).
█ [email protected]
█ www.freenove.com Chapter 16 Temperature Sensor 185
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/16.1_BuiltInThermometer BuiltInThermometer.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into micro:bit, and then LED
dot matrix screen will display the current detected temperature.
Reference
temperature()
Return the temperature of the micro:bit in Celcius.
display.scroll()
scrolls a string across the display
[email protected] █
186 Chapter 16 Temperature Sensor www.freenove.com █
Component list
█ [email protected]
█ www.freenove.com Chapter 16 Temperature Sensor 187
Component knowledge
Thermistor
Thermistor is a temperature sensitive resistor. When it senses a change in temperature, the resistance of
the Thermistor will change. We can take advantage of this characteristic by using a Thermistor to detect
temperature intensity. A Thermistor and its electronic symbol are shown below.
We can use the value measured by the analog pin of micro:bit to obtain resistance value of thermistor, and
then we can use the formula to obtain the temperature value.
Therefore, the temperature formula can be derived as:
T2 = 1/(1/T1 + ln(Rt/R)/B)
[email protected] █
188 Chapter 16 Temperature Sensor www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 16 Temperature Sensor 189
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/16.2_ExternalThermometer ExternalThermometer.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, download the code into the micro:bit, and the LED dot
matrix will display the detected temperature.
The temperature measured by the thermistor and the temperature measured by the micro:bit’s built-in
temperature sensor may have slight difference. This is because the hardware used is different, and there are
certain differences in the manufacturing of the components. It is within a reasonable range and can be ignored.
Obtain the temperature data measured by the thermistor, and then round up and display on the LED display.
Reference
Block Function
[email protected] █
190 Chapter 16 Temperature Sensor www.freenove.com █
Extensions
If you want to import Freenove extensions in a new project, follow the steps below to add them.
Click “Advanced” to
expand the list.
Click“Extension”.
█ [email protected]
█ www.freenove.com Chapter 16 Temperature Sensor 191
Click to add.
It is added successfully.
[email protected] █
192 Chapter 16 Temperature Sensor www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/16.2_ExternalThermometer ExternalThermometer.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, download the code into the micro:bit, and the LED dot
matrix will display the detected temperature.
Read the analog voltage of the thermistor and calculate the resistance of the thermistor.
adcValue = pin0.read_analog()
V = adcValue*3.3/1023.0
Rt = V/((3.3-V)/10)
Calculate the current temperature according to the resistance value of the thermistor and then display it on
the LED dot matrix screen. For the formula, please refer to the component knowledge.,.
tempC = (1/(1/(273.15+25) + math.log(Rt/10)/3950))-273.15
display.scroll(round(tempC))
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 193
Chapter 17 Joystick
In an earlier chapter, we learned how to use Rotary Potentiometer. We will now learn about joysticks, which
are electronic modules that work on the same principle as the Rotary Potentiometer.
In this project, we will read the output data of a joystick and display it.
Component list
[email protected] █
194 Chapter 17 Joystick www.freenove.com █
Component knowledge
Joystick
A Joystick is a kind of input sensor used with your fingers. You should be familiar with this concept already as
they are widely used in gamepads and remote controls. It can receive input on two axes (Y and or X) at the
same time (usually used to control direction on a two dimensional plane). And it also has a third direction
capability by pressing down (Z axis/direction).
This is accomplished by incorporating two rotary potentiometers inside the Joystick Module at 90 degrees
of each other, placed in such a manner as to detect shifts in direction in two directions simultaneously and
with a Push Button Switch in the “vertical” axis, which can detect when a User presses on the Joystick.
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 195
Circuit
Schematic diagram
Hardware connection
[email protected] █
196 Chapter 17 Joystick www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/17.1_DisplayJoystickData DisplayJoystickData.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into the micro:bit. Open the serial
console, then you can see the Joystick data, as shown below.
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 197
Read the analog voltage value of P1 and P2 pins and the digital voltage value of P0 pin, and print the values
every 500ms.
[email protected] █
198 Chapter 17 Joystick www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/17.1_DisplayJoystickData DisplayJoystickData.py
After loading successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into the micro:bit. Click on the
REPL, and then press the micro:bit reset button to see the Joystick data.
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 199
This project shows the direction of the Joystick with arrows on the dot matrix.
Joystick direction Arrow direction Joystick Direction Arrow Direction
Press
[email protected] █
200 Chapter 17 Joystick www.freenove.com █
Component list
Circuit
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/17.2_Joystick Joystick.hex
After importing successfully, the code is shown as below:
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 201
Check the connection of the circuit and verify it correct. Download the code into the micro:bit, and then the
direction of the Joystick will be displayed on the dot matrix.
[email protected] █
202 Chapter 17 Joystick www.freenove.com █
Display the corresponding arrow image according to the values of the X, Y, and Z directions.
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 203
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/17.2_Joystick Joystick.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct. Download the code into the micro:bit and then the
direction of the Joystick will be displayed on the dot matrix.
[email protected] █
204 Chapter 17 Joystick www.freenove.com █
█ [email protected]
█ www.freenove.com Chapter 17 Joystick 205
Custom image number "0" will be displayed when pressing the Joystick.
circle = Image("09900:"
"90090:"
"90090:"
"90090:"
"09900")
Display the corresponding arrow image according to the value of X, Y, Z in three directions
if zVal == 1:
display.clear()
display.show(circle)
elif xVal <450 and yVal < 650 and yVal >450:
display.clear()
display.show(Image.ARROW_N)
elif xVal >650 and yVal < 650 and yVal >450:
display.clear()
display.show(Image.ARROW_S)
elif yVal >650 and xVal < 650 and xVal >450:
display.clear()
display.show(Image.ARROW_W)
elif yVal < 450 and xVal < 650 and xVal >450:
display.clear()
display.show(Image.ARROW_E)
elif xVal <450 and yVal > 650:
display.clear()
display.show(Image.ARROW_NW)
elif xVal <450 and yVal < 450:
display.clear()
display.show(Image.ARROW_NE)
elif xVal > 650 and yVal > 650:
display.clear()
display.show(Image.ARROW_SW)
elif xVal > 650 and yVal < 450:
display.clear()
display.show(Image.ARROW_SE)
else:
display.clear()
[email protected] █
206 Chapter 18 74HC595 and LED Bar Graph www.freenove.com █
In this project, we will use a 74HC595 chip and LED Bar Graph to make a flowing water light.
Component list
█ [email protected]
█ www.freenove.com Chapter 18 74HC595 and LED Bar Graph 207
Component knowledge
74HC595
A 74HC595 chip is used to convert serial data into parallel data. A 74HC595 chip can convert the serial data
of one byte into 8 bits, and send its corresponding level to each of the 8 ports correspondingly. With this
characteristic, the 74HC595 chip can be used to expand the IO ports of a Raspberry Pi. At least 3 ports on the
RPI board are required to control the 8 ports of the 74HC595 chip.
[email protected] █
208 Chapter 18 74HC595 and LED Bar Graph www.freenove.com █
Circuit
Schematic diagram
Hardware connection
If LED bar doesn’t work, try rotating the LED bar 180°.
█ [email protected]
█ www.freenove.com Chapter 18 74HC595 and LED Bar Graph 209
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/18.1_FlowingLight02 FlowingLight02.hex
After importing successfully, the code is shown as below:
After checking the connection of the circuit and verify it correct, download the code into micro:bit, and you
can see that the LED flow from left to right in turn circularly.
[email protected] █
210 Chapter 18 74HC595 and LED Bar Graph www.freenove.com █
Set 74HC595’s data pin as P0, launch pin as P1, and clock pin as P2.
In the for loop, the number '1' moves index bit to the left, writes the shifted value to 74HC595 serially, and
then turn ON the LED through parallel output of Q0-Q7 to realize flowing water light.
Reference
Block Function
It belongs to Freenove
Extension Block. It is used
to set data pin, launch pin,
clock pin for 74HC595.
It belongs to Freenove
Extension Block. The data
of 0-255 is serially written
to 74HC595, and then
output in parallel through
Q0-Q7. The order of data
writing is either from the
highest bit or from the
least bit.
It belongs to Freenove
Extension Block. Move data
to the left (x) bit or to the
right (x) bit.
█ [email protected]
█ www.freenove.com Chapter 18 74HC595 and LED Bar Graph 211
python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/18.1_FlowingLight02 FlowingLight02.py
After loading successfully, the code is shown as below:
After checking the connection of the circuit and verify it correct, download the code into micro:bit, and you
can see that the LED flow from left to right in turn circularly.
[email protected] █
212 Chapter 18 74HC595 and LED Bar Graph www.freenove.com █
█ [email protected]
█ www.freenove.com Chapter 18 74HC595 and LED Bar Graph 213
else:
dPin.write_digital(0)
else:
flag=value>>i & 0x01
if flag==0x01:
dPin.write_digital(1)
else:
dPin.write_digital(0)
cPin.write_digital(1)
In the for loop, the value of the variable value shifts to the left i-bit, then the value of the variable value is
written to 74HC595, and then turn ON the LED one by one through parallel output of Q0-Q7 to realize
flowing water light.
while True:
for i in range(8):
value=0x01<<i
latchPin.write_digital(0)
shiftOut(value,dataPin,clockPin,LSBFIRST)
latchPin.write_digital(1)
sleep(500)
Reference
shiftOut(value,dPin,cPin,order)
This function is used to serially write 8 bits of data to 74HC595. Value represents data to be written to
74HC595 registers, dPin represents data pins, cPin represents clock pins, and order represents priority bit
flags (high or low). About order, LSBFIRST starts writing from low data, MSBFIRST starts writing from high
data.
<< operator
"<<" is a left shift operator that moves all bits of byte data to the left (high) direction by a few bits and add
0 on the right (low). For example, shift binary 0001 1110 to the left by 1 bit to get 0011 1100. If you shift 1
bit to the right, it is 0000 1111.
">>" is the right shift operator, as opposed to the left shift operator, which moves all bits of byte data to
the right (low) direction by a few bits and add 0 on the left(high).
& operator
& is a bitwise AND operation, which performs an AND operation on binary bit. Operation rules:
0&0=0;
0&1=0;
1&0=0;
1&1=1
For example:
A=0011 1100
B=0000 1101
---------------
A&B=0000 1100
[email protected] █
214 Chapter 19 74HC595 and 7-segment display www.freenove.com █
In this project, we will use the 74HC595 chip and a 7-segment digital tube display to display the numbers 0
to 9.
Component list
Resistor 220Ω x8
█ [email protected]
█ www.freenove.com Chapter 19 74HC595 and 7-segment display 215
Component knowledge
As we can see in the above circuit diagram, we can control the state of each LED separately. Also, by
combining LEDs with different states of ON and OFF, we can display different characters (Numbers and
Letters). For example, to display a “0”: we need to turn ON LED segments 7,6,4,2,1 and 9, and turn OFF LED
segments 10 and 5.
If we use a byte to show the state of the LEDs that connected to pin 5, 10, 9, 1, 2, 4, 6, 7, we can use 0 to
represent the state of on and 1 for off. Then the number 0 can be expressed as a binary number 11000000,
namely hex 0xc0.
The numbers and letters that can be display are shown below:
[email protected] █
216 Chapter 19 74HC595 and 7-segment display www.freenove.com █
█ [email protected]
█ www.freenove.com Chapter 19 74HC595 and 7-segment display 217
Circuit
Schematic diagram
Hardware connection
[email protected] █
218 Chapter 19 74HC595 and 7-segment display www.freenove.com █
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/19.1_SevenSegmentDisplay SevenSegmentDisplay.hex
After importing successfully, the code is shown as below:
After checking the connection of the circuit and verifying it correct, the code is downloaded into micro:bit.
You can see that the 7-segment display shows 0, 1... 9 in turn.
█ [email protected]
█ www.freenove.com Chapter 19 74HC595 and 7-segment display 219
Set 74HC595 data pin as P0, launch pin as P1, and clock pin as P2.
In the for loop, the digital tube displays the numbers 0 to 9 in turn, and change the number every 500ms.
Reference
Block Function
[email protected] █
220 Chapter 19 74HC595 and 7-segment display www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/19.1_SevenSegmentDisplay SevenSegmentDisplay.py
After loading successfully, the code is shown as below:
After checking the connection of the circuit and verifying it correct, the code is downloaded into micro:bit.
You can see that the 7-segment display shows 0, 1... 9 in turn.
█ [email protected]
█ www.freenove.com Chapter 19 74HC595 and 7-segment display 221
[email protected] █
222 Chapter 19 74HC595 and 7-segment display www.freenove.com █
Call the shiftOut() function, and write the hexadecimal number stored in the number variable to 74HC595
serially, then turn ON the LEDs through parallel output of Q0 ~ Q7.
while True:
for Num in number:
latchPin.write_digital(0)
shiftOut(Num,dataPin,clockPin,MSBFIRST)
latchPin.write_digital(1)
sleep(500)
█ [email protected]
█ www.freenove.com Chapter 20 LCD1602 223
Chapter 20 LCD1602
In this chapter, we will learn the LCD1602 display.
This project realizes the display of the current ambient temperature on the LCD1602 display.
Component list
LCD1602
[email protected] █
224 Chapter 20 LCD1602 www.freenove.com █
Component knowledge
LCD1602
The LCD1602 Display Screen can display 2 lines of characters in 16 columns. It is capable of displaying numbers,
letters, symbols, ASCII code and so on. As shown below is a monochrome LCD1602 Display Screen along with
its circuit pin diagram
I2C LCD1602 Display Screen integrates a I2C interface, which connects the serial-input & parallel-output
module to the LCD1602 Display Screen. This allows us to only use 4 lines to the operate the LCD1602.
The serial-to-parallel IC chip used in this module is PCF8574T (PCF8574AT), and its default I2C address is
0x27(0x3F).
█ [email protected]
█ www.freenove.com Chapter 20 LCD1602 225
PCF8574 module pin and LCD1602 pin are corresponding to each other and connected with each other:
Because of this, as stated earlier, we only need 4 pins to control the 16 pins of the LCD1602 Display Screen
through the I2C interface.
In this project, we will use I2CLCD1602 to display some static characters and dynamic variables.
[email protected] █
226 Chapter 20 LCD1602 www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 20 LCD1602 227
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/20.1_LCD1602 LCD1602.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into the micro:bit, and then the
LCD screen will display the current ambient temperature.
So far, at this writing, we have two types of LCD1602 on sale. One needs to adjust the backlight, and the
other does not.
The LCD1602 that does not need to adjust the backlight is shown in the figure below.
[email protected] █
228 Chapter 20 LCD1602 www.freenove.com █
If the LCD1602 you received is the following one, and you cannot see anything on the display or the display
is not clear, try rotating the white knob on back of LCD1602 slowly, which adjusts the contrast, until the
screen can display clearly.
LCD initialization, we provide two kinds of LCD screen, you can write I2C address (0x27 or 0x3F) according
to the LCD screen you receive. If you enter 0, it will automatically search for the correct I2C address and
connect.
Reference
Block Function
LCD initialization, input LCD I2C address (0x27 or 0x3F). If you
enter 0, it will automatically find the correct address and
connect.
█ [email protected]
█ www.freenove.com Chapter 20 LCD1602 229
Extensions
If you want to import the LCD1602 expansion block in a new project, follow the steps below to add it.
1 Click on "Advanced" to
expand the list
2 Click on "Extension"
Enter "i2Clcd1602" to
search.
[email protected] █
230 Chapter 20 LCD1602 www.freenove.com █
Click add.
It is completed.
█ [email protected]
█ www.freenove.com Chapter 20 LCD1602 231
Python code
Copy “I2C_LCD1602_Class.py” and “DHT11_RW.py” from following path into “mu_code” directory.
File type Path File name
Python file .. /Projects/PythonLibrary I2C_LCD1602_Class.py DHT11_RW.py
[email protected] █
232 Chapter 20 LCD1602 www.freenove.com █
Open the Mu software, click "Files". Here we take "I2C_LCD1602_Class.py" as an example, drag
"I2C_LCD1602_Class.py" into micro:bit.
Select it and keep pressing with left mouse button, drag it to left box.
The import method of "DHT11_RW.py" is the same as described above. You just need to import the one you
need to use.
Note, after you upload other file into micro:bit, the original content will be covered. You need to import
it next time you use it.
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/20.1_LCD1602 LCD1602.py
After the code is loaded, as shown below, import the "I2C_LCD1602_Class.py" file to micro:bit before
█ [email protected]
█ www.freenove.com Chapter 20 LCD1602 233
After the "I2C_LCD1602_Class.py" file is imported, check the connection of the circuit and verify it correct.
Download the code into the micro:bit and the LCD screen will display the current ambient temperature.
NOTE: After the program is executed, if you cannot see anything on the display or the display is not
clear, try rotating the white knob on back of LCD1602 slowly, which adjusts the contrast, until the screen
can display the Temperature clearly.
[email protected] █
234 Chapter 20 LCD1602 www.freenove.com █
Export everything from the I2C_LCD1602_Class module, create the object lcd of the I2C_LCD1602 class, and
enter the I2C address of the LCD screen. Change the I2C address according to the LCD type.
If the chip of LCD is PCF8574 T, the i2c address is 0x27.
If the chip of LCD is PCF8574A T, the i2c address is 0x3F.
from I2C_LCD1602_Class import *
lcd = I2C_LCD1602(0x27)
Read the temperature data, and then call the puts function in the I2C_LCD1602 class to display the
temperature on the LCD screen.
lcd.puts("temperature:"+str(temperature()), 0, 0)
Reference
puts(String,x,y)
This function is defined in the I2C_LCD1602 class. The function is to display the string on the LCD screen x
column, y row, x range is 0-15, y range is 0-1.
█ [email protected]
█ www.freenove.com Chapter 21 Motor 235
Chapter 21 Motor
In this chapter, we will learn the comprehensive application of motor.
Component list
Motor x1 L293D x1
[email protected] █
236 Chapter 21 Motor www.freenove.com █
Component knowledge
L293D
L293D is an IC Chip (Integrated Circuit Chip) with a 4-channel motor drive. You can drive a Unidirectional DC
Motor with 4 ports or a Bi-Directional DC Motor with 2 ports or a Stepper Motor (Stepper Motors are covered
later in this Tutorial).
█ [email protected]
█ www.freenove.com Chapter 21 Motor 237
The following connection uses two channels of the L239D: one channel outputs the PWM wave, and the
other channel connects to GND. Therefore, you can control the speed of the motor. When these two
channel signals are exchanged, not only controls the speed of motor, but also can control the speed of the
motor.
In practical use the motor is usually connected to channel 1 and by outputting different levels to in1 and in2
to control the rotational direction of the motor, and output to the PWM wave to Enable1 port to control the
motor’s rotational speed. If the motor is connected to channel 3 and 4 by outputting different levels to in3
and in4 to control the motor's rotation direction, and output to the PWM wave to Enable2 pin to control the
motor’s rotational speed.
[email protected] █
238 Chapter 21 Motor www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 21 Motor 239
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/21.1_Motor Motor.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit and verify it correct. Download the code into the micro:bit and rotate the
potentiometer. When the potentiometer is in the middle position, the motor stops rotating. When the
potentiometer gets away from middle position, the motor speed increases. The potentiometer moves to the
limit and the motor speed reaches its maximum value. When the potentiometer is on a different side, the
rotating direction of motor is different.
[email protected] █
240 Chapter 21 Motor www.freenove.com █
Read the analog value of the P0 pin of the potentiometer. When the analog value is less than 411, the motor
rotates forward. When the analog value is greater than 612, the motor reverses. When the analog value is
between 411 and 612, the motor does not rotate.
Set P2 to low level. P1 outputs PWM signal with an interval of 20ms and duty cycle changes with the change
of potentiometer variable, then motor rotates forward.
Set P1 to low level, P2 output PWM signal with an interval of 20ms, duty cycle changes with the change of
potentiometer variable, then motor rotates in a reverse direction.
When P1, P2 pin output high level, motor does not rotate.
█ [email protected]
█ www.freenove.com Chapter 21 Motor 241
Reference
Block Function
Write an analog signal (0 through 1023) to the pin you
set.
Configure the period of Pulse Width Modulation (PWM)
on the specified analog pin. Before you call this
function, you should set the specified pin as analog.
[email protected] █
242 Chapter 21 Motor www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/21.1_Motor Motor.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct. Download the code into the micro:bit and rotate the
potentiometer. When the potentiometer is in the middle position, the motor stops rotating. When the
potentiometer gets away from middle position, the motor speed increases. The potentiometer moves to the
limit and the motor speed reaches its maximum value. When the potentiometer is on a different side, the
rotating direction of motor is different.
█ [email protected]
█ www.freenove.com Chapter 21 Motor 243
Read the analog value of the P0 pin of the potentiometer. When the analog value is less than 411, the motor
rotates forward. When the analog value is greater than 612, the motor reverses. When the analog value is
between 411 and 612, the motor does not rotate.
potentiometer=pin0.read_analog()
if potentiometer<=411:
elif potentiometer>=612:
else:
Set P2 to low level. P1 outputs PWM signal with an interval of 20ms, duty cycle changes with potentiometer
variable, then motor rotates forward.
pin2.write_digital(0)
pin1.write_analog((411-potentiometer)/411*1023)
pin1.set_analog_period(20)
Set P1 to low level. P2 outputs PWM signal with an interval of 20ms, duty cycle changes with the change of
potentiometer variable, then motor rotates in a reverse direction.
pin1.write_digital(0)
pin2.write_analog((potentiometer-612)/411*1023)
pin2.set_analog_period(20)
When P1, P2 pins output high level, motor does not rotate.
pin1.write_digital(1)
pin2.write_digital(1)
Reference
pin.set_analog_period(int)
sets the interval; of the PWM output of the pin in milliseconds
see https://en.wikipedia.org/wiki/Pulse-width_modulation
pin.write_analog(value)
value is between 0 and 1023
[email protected] █
244 Chapter 22 Servo www.freenove.com █
Chapter 22 Servo
In this chapter, we will learn about Servos which are a rotary actuator type motor that can be controlled rotate
to specific angles.
Component list
Jumper F/M x3
█ [email protected]
█ www.freenove.com Chapter 22 Servo 245
Component knowledge
Servo
Servo is a compact package which consists of a DC Motor, a set of reduction gears to provide torque, a sensor
and control circuit board. Most Servos only have a 180-degree range of motion via their “horn”. Servos can
output higher torque than a simple DC Motor alone and they are widely used to control motion in model cars,
model airplanes, robots, etc. Servos have three wire leads which usually terminate to a male or female 3-pin
plug. Two leads are for electric power: Positive (2-VCC, Red wire), Negative (3-GND, Brown wire), and the
signal line (1-Signal, Orange wire) as represented in the Servo provided in your Kit.
We will use a 50Hz PWM signal with a duty cycle in a certain range to drive the Servo. The lasting time 0.5ms-
2.5ms of PWM single cycle high level corresponds to the Servo angle 0 degrees - 180 degree linearly. Part of
the corresponding values are as follows:
[email protected] █
246 Chapter 22 Servo www.freenove.com █
Circuit
This circuit Servo is powered by 5V, and the Micro:bit P0 pin controls the Servo rotation angle.
Diagram schematic
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 22 Servo 247
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/22.1_Sweep Sweep.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit, verify it correct, and download the code into micro:bit. The servo rotates
from 0 degrees to 180 degrees, then from 180 degrees to 0 degrees, and repeats in an endless loop.
In the for loop of 0-180, let the servo change from 0 to 180 degrees.
[email protected] █
248 Chapter 22 Servo www.freenove.com █
In the for loop of 0-180, take the difference between 180 and index2, and let the servo rotate from 180
degrees to 0 degrees.
Reference
Block Function
Write a value to the servo on the specified pin and control the
shaft.
█ [email protected]
█ www.freenove.com Chapter 22 Servo 249
python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/22.1_Sweep Sweep.py
After loading successfully, the code is shown as below:
After checking the connection of the circuit and verifying it correct, download the code into micro:bit, and
then the servo will from 0 degree to 180 degree, and then from 180 degree to 0 degree, which repeats in an
endless loop.
[email protected] █
250 Chapter 22 Servo www.freenove.com █
Define map functions to convert values in one range to values in another range.
def map(value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
Set the interval of the PWM signal to 20ms. In a 0-180 for loop, convert the value in the range 0-180 to an
analog voltage value in the range of 25.6~128, and then output the corresponding PWM signal to turn the
servo from 0 degrees to 180 degrees.
pin0.set_analog_period(20)
for i in range(180):
pin0.write_analog(map(i,0,180,25.6,128))
sleep(5)
In a 180-0 for loop, convert the value in the range 0-180 to the analog voltage value in the range of 25.6~128,
and then output the corresponding PWM signal to rotate the servo from 180 degrees to 0 degrees.
for i in range(180,0,-1):
pin0.write_analog(map(i,0,180,25.6,128))
sleep(5)
█ [email protected]
█ www.freenove.com Chapter 22 Servo 251
In this project, we will use a potentiometer to control the rotation angle of the Servo.
Component list
[email protected] █
252 Chapter 22 Servo www.freenove.com █
Circuit
The P0 pin of this circuit microbit reads the voltage of the potentiometer, and the P1 pin drives the servo.
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 22 Servo 253
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/22.2_Knob Knob.hex
After importing successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, download the code into the micro:bit, rotate the
potentiometer, and the servo will follow the rotation.
Read the analog voltage value of the P0 pin, map the analog voltage value in the range of 0-1023 to the
angle of the servo in the range of 0-180, and then drive the servo to rotate the corresponding angle through
the P1 pin.
[email protected] █
254 Chapter 22 Servo www.freenove.com █
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/22.2_Knob Knob.py
After loading successfully, the code is shown as below:
Check the connection of the circuit and verify it correct, download the code into the micro:bit, rotate the
potentiometer, and the servo will follow the rotation.
Define map functions to convert values in one range to values in another range.
def map(value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
Set the period of PWM signal to 20 ms. Read the analog voltage value of P0 foot, convert the analog voltage
value in the range of 0-1023 to the analog voltage value in the range of 25.6-128, and then output the
corresponding PWM signal to rotate the servo at the corresponding angle.
value=pin0.read_analog()
pin1.set_analog_period(20)
pin1.write_analog(map(value,0,1023,25.6,128))
█ [email protected]
█ www.freenove.com Chapter 23 Ultrasonic Ranging 255
In this project, we use HC-SR04 ultrasonic module to measure the distance between the module and the
obstacle in front of it and display it on LCD screen.
Component list
F/F x8 HC-SR04 x1
[email protected] █
256 Chapter 23 Ultrasonic Ranging www.freenove.com █
Component Knowledge
The Ultrasonic Ranging Module uses the principle that ultrasonic waves will reflect when they encounter any
obstacles. This is possible by counting the time interval between when the ultrasonic wave is transmitted to
when the ultrasonic wave reflects back after encountering an obstacle. Time interval counting will end after
an ultrasonic wave is received, and the time difference (delta) is the total time of the ultrasonic wave’s journey
from being transmitted to being received. Because the speed of sound in air is a constant, and is about
v=340m/s, we can calculate the distance between the Ultrasonic Ranging Module and the obstacle: s=vt/2.
The HC-SR04 Ultrasonic Ranging Module integrates a both an ultrasonic transmitter and a receiver. The
transmitter is used to convert electrical signals (electrical energy) into high frequency (beyond human hearing)
sound waves (mechanical energy) and the function of the receiver is opposite of this. The picture and the
diagram of the HC SR04 Ultrasonic Ranging Module are shown below:
█ [email protected]
█ www.freenove.com Chapter 23 Ultrasonic Ranging 257
Pin description:
VCC power supply pin
Trig trigger pin
Echo Echo pin
GND GND
Technical specs:
Working voltage: 5V Working current: 12mA
Minimum measured distance: 2cm Maximum measured distance: 200cm
Instructions for Use: output a high-level pulse in Trig pin lasting for least 10uS, the module begins to
transmit ultrasonic waves. At the same time, the Echo pin is pulled up. When the module receives the
returned ultrasonic waves from encountering an obstacle, the Echo pin will be pulled down. The duration of
high level in the Echo pin is the total time of the ultrasonic wave from transmitting to receiving, s=vt/2. This
is done constantly.
[email protected] █
258 Chapter 23 Ultrasonic Ranging www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ [email protected]
█ www.freenove.com Chapter 23 Ultrasonic Ranging 259
Block code
Open MakeCode first. Import the .hex file. The path is as below:
(How to import project)
File type Path File name
HEX file ../Projects/BlockCode/23.1_UltrasonicRanging UltrasonicRanging.hex
After importing successfully, the code is shown as below:
After checking the connection of the circuit and verifying it correct, download the code into micro:bit. The
LCD screen will show the distance between the obstacle and the ultrasonic module in CM.
[email protected] █
260 Chapter 23 Ultrasonic Ranging www.freenove.com █
Initialize LCD.
The distance of obstacles measured by the ultrasonic module will be assigned to the variable distance, and
then displayed on LCD. LCD refreshes every 1 second.
Reference
Block Function
█ [email protected]
█ www.freenove.com Chapter 23 Ultrasonic Ranging 261
Extensions
If you want to import the ultrasonic module expansion block into the new project, follow the steps below to
add it.
[email protected] █
262 Chapter 23 Ultrasonic Ranging www.freenove.com █
Click to add.
Completed.
█ [email protected]
█ www.freenove.com Chapter 23 Ultrasonic Ranging 263
Python code
Open the .py file with Mu. Code, the path is as below:
File type Path File name
Python file ../Projects/PythonCode/23.1_UltrasonicRanging UltrasonicRanging.py
After the code is loaded, as shown below, import the "I2C_LCD1602_Class.py" file to micro:bit before
downloading the code. (How to import?)
After importing the I2C_LCD1602_Class.py file, check the connection of the circuit and verify it correct. After
downloading the code into micro:bit, you can see that the LCD screen will show the distance between the
obstacle and the ultrasonic module. The unit is CM.
[email protected] █
264 Chapter 23 Ultrasonic Ranging www.freenove.com █
█ [email protected]
█ www.freenove.com Chapter 23 Ultrasonic Ranging 265
The custom getdistance() function is used to get the distance between the obstacle and the ultrasonic module.
The unit of return value is CM.
def getdistance():
distance=0
pin1.write_digital(1)
sleep_us(15)
pin1.write_digital(0)
while pin0.read_digital() == 0:
pass
if pin0.read_digital() == 1:
ts = ticks_us()
while pin0.read_digital() == 1:
pass
te = ticks_us()
tc = te - ts
print(te,ts)
distance = (tc*170)*0.0001
return distance
Create the object lcd of I2C_LCD1602 class, input I2C address 0x27, call getdistance() function, get the
distance of the obstacle to the ultrasonic module, assign it to the distance variable, and then display the
value of the distance variable on the LCD.
lcd = I2C_LCD1602(0x27)
while True:
distance=round(getdistance())
lcd.clear()
lcd.puts("Distance is:",0,0)
lcd.puts(str(distance),12,0)
sleep(1000)
Reference
getdistance()
Get the distance from the ultrasonic module to the obstacle. The unit is CM.
[email protected] █
266 What's Next? www.freenove.com █
What's Next?
THANK YOU for participating in this learning experience!
We have reached the end of this Tutorial. If you find errors, omissions or you have suggestions and/or
questions about the Tutorial or component contents of this Kit, please feel free to contact us:
[email protected]
We will make every effort to make changes and correct errors as soon as feasibly possible and publish a
revised version.
If you want to learn more about micro:bit, we have a smart Car named Micro:bit Rover. You can visit our
website to purchase. http://www.freenove.com/store.html
If you want to learn more about Arduino, Raspberry Pi, Smart Cars, Robotics and other interesting products
in science and technology, please continue to visit our website. We will continue to launch fun, cost-effective,
innovative and exciting products.
http://www.freenove.com/