Getting Started with MicroPython and the SparkFun Inventor's Kit for micro:bit

Pages
Contributors: LightningHawk
Favorited Favorite 5

Introduction to the SparkFun Inventor's Kit for micro:bit for MicroPython

Note: This tutorial applies to KIT-14542, KIT-15228, KIT-17362, and lab packs. For more information, check out the note in the Included Materials.

MicroPython is an open source interpreter for the Python programming language developed specifically for microcontrollers. In this experiment guide, we will show you how to get started using MicroPython with the popular micro:bit board and our SparkFun Inventor's Kit for micro:bit.

SparkFun Inventor's Kit for micro:bit v2

SparkFun Inventor's Kit for micro:bit v2

KIT-17362
$53.50
SparkFun Inventor's Kit for micro:bit v2 Lab Pack

SparkFun Inventor's Kit for micro:bit v2 Lab Pack

LAB-17363
$460.00
Note: This experiment guide assumes you have experience with programming. If you have never used a programming language before, we recommend checking out the MakeCode version of this guide. MakeCode is a drag-and-drop editor that is great for beginners of all ages learning to program.

When you're done with this guide, you'll have the know-how to start creating your own projects and experiments with MicroPython for micro:bit!

Included Materials

The SparkFun Inventor's Kit (SIK) for micro:bit includes the following:

  • micro:bit --- The brains of the outfit with a bunch of onboard components. The version will vary depending on the kit or lab pack that you ordered.
  • micro:bit Breakout (with Headers) --- Allows you to connect the micro:bit to the breadboard. The version will vary depending on the kit or lab pack that you ordered.
  • Breadboard --- Excellent for making circuits and connections off the micro:bit. We included a full-sized breadboard to give you plenty of room.
  • Small Servo --- Here is a simple, low-cost, high-quality servo for all your mechatronic needs.
  • Piezo Buzzer --- BUZZZZ! Used to make different frequencies of sound.
  • USB micro-B Cable --- This 6-foot cable provides you with a USB-A connector at the host end and standard B connector at the device end.
  • Male-to-Male Jumper Wires --- These are high-quality wires that allow you to make connections with components on the breadboard.
  • TMP36 Temperature Sensor - A sensor for detecting temperature changes.
  • Photocell --- A sensor to detect ambient light. Perfect for detecting when a drawer is opened or when nighttime approaches.
  • Tri-Color LED --- Because everyone loves a blinky.
  • Red, Blue, Yellow, and Green LEDs --- Light-Emitting Diodes make great general indicators.
  • Momentary Pushbutton Switch --- Go crazy with buttons.
  • 10kΩ Trimpot --- Also known as a variable resistor, this is a device commonly used to control volume and contrast, and makes a great general user control input.
  • 100Ω Resistors --- Great current-limiting resistors for LEDs, and strong pull-up resistors.
  • 10kΩ Resistors --- These make excellent pull-ups, pull-downs and current limiters.
  • 2x AAA Battery Pack --- AAA battery pack with the JST connector that fits the micro:bit
  • Alligator Clip with Pigtail --- A great way to connect individual components on a breadboard to the micro:bit ring connectors.
Note: This tutorial applies to KIT-14542, KIT-15228, KIT-17362, and lab packs. For those interested in what the differences are between each revision, check below!

SparkFun Inventor's Kit
micro:bit SKU
Revision History
KIT-17362, LAB-17363 - Switch to micro:bit V2.
- Switch to Qwiic micro:bit breakout board (with headers).
KIT-15228, LAB-15229 Switch to 2xAAA battery holder with a built-in switch.
KIT-14542, LAB-14301 Initial release.
Note: The kit does not include AAA batteries in the individual SparkFun Inventor's Kit for micro:bit V2 and they will need to be purchased separately. For older versions of the kit, you will need to purchase AA batteries for the AA battery pack.


750 mAh Alkaline Battery - AAA

PRT-09274
Retired

What's that? You've already got a micro:bit but still want to follow along? We have options!

SparkFun Inventor's Kit Bridge Pack for micro:bit

SparkFun Inventor's Kit Bridge Pack for micro:bit

KIT-14719
$42.95
1
  • Alternatively, you can pick and choose parts for individual experiments. This is a great option for folks who may already have some of the items in this tutorial just hanging around. Throughout this guide, we will provide links to the parts used for each circuit. Below is a wishlist for the parts used in the kit. Depending on what you have, you may not need everything on this list. Add it to your cart, read through the guide, and adjust the cart as necessary.

Suggested Reading

If you have never worked with electronics before, we recommend you be somewhat familiar with the concepts in the following tutorials:

  • Getting Started with the micro:bit --- Basic guide to getting started with the micro:bi such as programming with MakeCode to the hardware overview.
  • Voltage, Current, Resistance, and Ohm's Law --- The most basic concepts in electronics and electrical engineering. Get very familiar with these concepts, as they will be used throughout your electronics adventure.
  • What is a Circuit? --- In this guide, we will be building a variety of circuits. Understanding what that means is vital to understanding the Inventor's Kit.
  • How to Use a Breadboard --- First time working with a breadboard? Please check out this tutorial! It will help you understand why the breadboard is great for prototyping and how to use one.

Getting Started with the micro:bit

September 2, 2021

The BBC micro:bit is a compact, powerful programming tool that requires no software installation. Read on to learn how to use it YOUR way!

Voltage, Current, Resistance, and Ohm's Law

February 6, 2013

Learn about Ohm's Law, one of the most fundamental equations in all electrical engineering.

What is a Circuit?

February 6, 2013

Every electrical project starts with a circuit. Don't know what a circuit is? We're here to help.

How to Use a Breadboard

May 14, 2013

Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very first circuit.

Open Source!

All of our experiments and guides are licensed under the Creative Commons Attribution Share-Alike 4.0 Unported License. Feel free to remix and reuse our work. But please, share the love and give us attribution for our hard work!

To view a copy of this license visit this link, or write: Creative Commons, 171 Second Street, Suite 300, San Francisco, CA 94105, USA.

Introduction to MicroPython

Using MicroPython

MicroPython is just an interpreter, so it does not include a space to write and edit code. Luckily, there is an editor we can use to write our Python code. Before you get started, you'll need to download Mu. Mu is a simple code editor for beginners that runs on Windows, OSX, Linux and Raspberry Pi.

A major benefit of using MicroPython is the interactive REPL. REPL stands for Read-Evaluate-Print Loop, which is a very long way to say you can execute code live without compiling it first and then uploading it after.

The applications for Python are extensive, and the advantage to using Python over other programming languages include interacting with other languages and platforms, third-party modules, extensive support libraries, user-friendly data structures and, of course, it's open source.

Some known issues with using Mu and micro:bit currently are not being able to import third-party modules [1], not being able to use interrupts, and not having a decent way to map numbers of one range to another. Since importing third-party modules is not supported, we will be copying and pasting the source code in the current Mu MicroPython file. As with learning any new language, Python requires time, patience, self-study and a lot of examples! Keep at it, and we will be here to help you along the way.

MicroPython Project Files

To download all of the files needed to follow along with all of the experiments, click the button below from the GitHub repository..

Software Options

To use MicroPython with the micro:bit, there are a few different options.

Experiment 0: Hello, micro:bit!

Parts Needed

You will need the following parts:

  • 1x micro:bit
  • 1x micro-B USB Cable

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15

Hello World: A Programmer's First Program

A "Hello World" on the micro:bit is a little different. On most microcontrollers this program would be executed using a serial terminal. Instead of using a serial terminal, you can interact with your micro:bit using the built-in LED array. So, the "Hello World" for the micro:bit is to draw something using the LED array!

Let's first run the program from the REPL, and then we will build a .py script and upload it to the micro:bit. Open Mu, and make sure your micro:bit is connected to your computer with a USB cable.

USB Cable micro:bit

To open the REPL, click the icon, and you should see a second window appear at the bottom. Type help() and see what happens.

REPL Help

Click any of the images for a closer look.

From the REPL, type display.scroll("Hello World") and watch your micro:bit's 5x5 LED array.

language:python
display.scroll("Hello World")

Hello World! from REPL

Click any of the images for a closer look.

Now close the REPL by clicking the REPL icon!

Experiment 0: Hello World!

For the first MicroPython script, we are going to cover how to add comments, how to import a module, and how to create a loop that will run forever.

Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex0_0_helloWorld.py program.

language:python
# SparkFun Electronics
# Experiment 0.0
# Display "Hello World!" on your micro:bit

from microbit import *

while True:
    display.scroll("Hello World!")
    sleep(1000)

micropython Hello World

Click any of the images for a closer look.

At the top of the program (above), you'll see three lines of comments. Comments are created by using the # sign and one space. You can access modules by using from and import. These words tell the interpreter which classes to import from which modules. In this case, we are importing everything from micro:bit.

The line while True: creates a forever loop in Python so that the program can continue to run the example. The colon is how Python blocks code similar to the way Arduino (another type of text based coding language) uses a set of curly brackets. Everything indented under a colon will execute as a block of code. In this case, we display text and add a small one second delay. The delay is useful to add in programs to process data or initializing IC chips, or for users to reading or viewing data. Just make sure to not make the delay too big as this can make your program run slow from the long pauses.

Experiment 0.1: Displaying a Pre-Defined Image

Let's display an image next instead of text. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex0_1_displayImage.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 0.1
# Display an image

from microbit import *
while True:
    display.show(Image.DUCK)

Code set for displaying image

Click any of the images for a closer look.

When typing display.show(Image.), let the helpful info box show you what images come built in.

Suggested Text

Click any of the images for a closer look.

Experiment 0.2: Manually Displaying an Image

Try to code your own custom image! Below is an example of manually drawing a star. Note that you can control the brightness of an individual LED by adjusting the value between 0 to turn the LED OFF and 9to fully turn on the LED. Each row from the LED matrix is manually controlled inImage("").

language:python
# SparkFun Electronics
# Experiment 0.2
# Display a custom image

from microbit import *
while True:
    star = Image("00900:99599:05950:09590:90009")
    display.show(star)

Code for displaying your own image

Click any of the images for a closer look.

Experiment 1: Blinking an LED

Introduction

This is experiment 1 - blinking an LED. We get to the fun stuff: adding hardware and constructing circuits.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-B USB Cable
  • 1x LED
  • 1x 100Ω Resistor
  • 1x Jumper Wires

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
LED - Basic Red 5mm

LED - Basic Red 5mm

COM-09590
$0.45
Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14493
$1.25

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Light-Emitting Diodes (LEDs)

August 12, 2013

Learn the basics about LEDs as well as some more advanced topics to help you calculate requirements for projects containing many LEDs.

Resistors

April 1, 2013

A tutorial on all things resistors. What is a resistor, how do they behave in parallel/series, decoding the resistor color codes, and resistor applications.

Introducing the micro:bit Edge Connector

edge connector

To extend the functionality of the micro:bit beyond what is already on the board, we developed a breadboard adaptor. This adaptor board makes it much easier to use all of the pins available on the micro:bit edge connector in a more user-friendly way. We also broke out ground and VCC (3.3 volts) for your convenience.

The adapter board lines up with the pins of a breadboard. We recommend using a full-sized breadboard with this breakout to give you enough room to prototype circuits on either end of the breadboard.

Introducing the LED

LED image

A Light-Emitting Diode (LED) will only let current through in one direction. Think of an LED as a one-way street. When current flows through the LED, it lights up! When you are looking at the LED, you will notice that its legs are different lengths. The long leg, the "anode," is where current enters the LED. This pin should always be connected to the current source. The shorter leg, the "cathode," is the current’s exit. The short leg should always be connected to a pathway to ground.

LEDs are finicky when it comes to how much current you apply to them. Too much current can lead to a burnt-out LED. To restrict the amount of current that passes through the LED, we use a resistor in line with the power source and the LED's long leg; this is called a current-limiting resistor. With the micro:bit, you should use a 100 Ohm resistor. We have included a baggy of them in the kit just for this reason!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: Pay close attention to the LED. The negative side of the LED is the short leg, marked with a flat edge.

LED drawing

Components like resistors need to have their legs bent into 90° angles in order to correctly fit the breadboard sockets. You can also cut the legs shorter to make them easier to work with on the breadboard.

Bent resistor

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Running Your Script

Let's blink the LED. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex1_blinkLED.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 1.0
# Blinking an LED

from microbit import *

while True:
    pin0.write_digital(1)
    sleep(1000)
    pin0.write_digital(0)
    sleep(1000)

blinkLED code image

Code to Note

pin0.write_digital(1) and pin0.write_digital(0)

You'll see that is is not much different from the previous experiment except for the lines 8 and 10. pin0.write_digital(1) sends a HIGH value, ON or a voltage of 3.3V to pin 0 on the micro:bit. pin0.write_digital(0) sends LOW value, OFF or 0V to pin 0 of the micro:bit.

What You Should See

You should see your LED blink on and off at 1-second intervals. If it doesn't, make sure you have assembled the circuit correctly and verified and uploaded the code to your board, or see the Troubleshooting section. Change the number in the sleep() and play with the LED blink rate.

LED Lighting Up

Troubleshooting

LED Not Blinking

Make sure you have it wired correctly and the correct pin to ground. Remember, short pin to ground; long pin to signal.

Still No Success

A broken circuit is no fun. Send us an email, and we will get back to you as soon as we can: techsupport@sparkfun.com

Experiment 2: Reading a Potentiometer

Introduction

In this circuit you will work with a potentiometer. You will learn how to use a potentiometer to control the brightness of an LED by reading a sensor and storing its 0--1023 value as a variable, then using it as a brightness level for the LED.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-b USB Cable
  • 1x LED
  • 1x 100Ω Resistor
  • 7x Jumper Wires
  • 1x 10kΩ Potentiometer

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

Trimpot 10K Ohm with Knob

Trimpot 10K Ohm with Knob

COM-09806
$1.05
6
micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
LED - Basic Red 5mm

LED - Basic Red 5mm

COM-09590
$0.45
Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14493
$1.25

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Analog to Digital Conversion

February 7, 2013

The world is analog. Use analog to digital conversion to help digital devices interpret the world.

Introducing the Potentiometer

Potentiometer next to Quarter

A potentiometer is a resistance-based analog sensor that changes its internal resistance based on the rotation of its knob. The potentiometer has an internal voltage divider enabling you to read the change in voltage on the center pin with a microcontroller (the micro:bit). To hook up the potentiometer, attach the two outside pins to a supply voltage (5V in this circuit) and ground. It doesn’t matter which is connected where, as long as one is connected to power, and the other to ground. The center pin is then connected to an analog input pin so the micro:bit can measure the change in voltage. When you twist the knob, the sensor reading will change!

Note: The potentiometer included in the kit has three marks on it that will help you figure out which breadboard rows the pins are plugged into.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

alt text

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Running Your Script

Let's read a potentiometer and control the brightness of an LED. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex2_readPot.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 2.0
# Reading a Potentiometer

from microbit import *

while True:
    potVal = pin2.read_analog()
    pin0.write_analog(potVal)
    sleep(25)

code for reading a pot

Code to Note

pin2.read_analog()

In this program you are reading the voltage from the potentiometer, which is 0 to 3.3 volts on pin 2. The micro:bit reads that value as a 10-bit number, which is a value range from 0 to 1023 using the call pin2.read_analog(). We are saving that number to a variable called potVal.

pin0.write_analog()

As with the analog read, the analog write deals with a range of values, but instead of reading a pin as an input, the line pin0.write_analog() outputs an analog value to a pin. We see this as a brightness range with this LED, but it could be a tone from a buzzer, a motor speed, etc. We set our analog output to the variable we stored the potentiometer value in.

A “variable” is a placeholder for values that may change in your code. You can create a variable by simply typing a name and setting it equal to what you want. Python is a dynamically typed language. This means the type of variable is determined at runtime. So you do not need to worry about declaring your variable type.

What You Should See

You should twist the potentiometer. You will notice that the LED will get brighter or dimmer based on the position of the potentiometer. If you turn the potentiometer all the way one direction, it will be fully on, and the other end will be fully off.

LED Dimmer with Potentiometer

Troubleshooting

Sporadically Working

This is most likely due to a slightly dodgy connection with the potentiometer's pins. This can usually be conquered by holding the potentiometer down or moving the potentiometer circuit somewhere else on your breadboard.

Not Working

Make sure you haven’t accidentally connected the wiper (center pin), the resistive element in the potentiometer, to a wrong pin!

LED Not Lighting Up

LEDs will only work in one direction. Double check your connections.

Experiment 3: Reading a Photoresistor

Introduction

In Experiment 2, you got to use a potentiometer, which varies resistance based on the twisting of a knob and, in turn, changes the voltage being read by the analog input pin. In this circuit you’ll be using a photoresistor, which changes resistance based on how much light the sensor receives. You will read the light value of the room and have an LED turn on if it is dark and turn off if it is bright. That's right; you are going to build a night-light!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1X micro:bit Breakout with Headers
  • 1x micro-B USB Cable
  • 1x LED
  • 1x 100Ω Resistor
  • 7x Jumper Wires
  • 1x Photoresistor
  • 1x 10kΩ Resistor

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
Mini Photocell

Mini Photocell

SEN-09088
$1.60
7
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
LED - Basic Red 5mm

LED - Basic Red 5mm

COM-09590
$0.45
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

COM-11508
$0.95
Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14493
$1.25

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Resistors

April 1, 2013

A tutorial on all things resistors. What is a resistor, how do they behave in parallel/series, decoding the resistor color codes, and resistor applications.

Voltage Dividers

February 8, 2013

Turn a large voltage into a smaller one with voltage dividers. This tutorial covers: what a voltage divider circuit looks like and how it is used in the real world.

Introducing the Photoresistor

Photoresistor

The photoresistor changes its resistance based on the light to which it is exposed. To use this with the micro:bit, you will need to build a voltage divider with a 10k ohm resistor, as shown in the wiring diagram for this experiment. The micro:bit cannot read a change in resistance, only a change in voltage. A voltage divider allows you to translate a change in resistance to a corresponding voltage value.

The voltage divider enables the use of resistance-based sensors like the photoresistor in a voltage-based system. As you explore different sensors, you will find more resistance-based sensors that only have two pins like the photoresistor. To use them with your micro:bit, you will need to build a voltage divider like the one in this experiment. To learn more about resistors in general, check out our tutorial on resistors and also our tutorial on voltage dividers.

Note: Make sure you are using the 10k ohm resistor in your voltage divider with the sensors in this kit. Otherwise, you will get odd and inconsistent results.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Circuit Diagram

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Running Your Script

Let's read a photoresistor and turn on an LED when it reaches a certain value. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex3_readLDR.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 3.0
# Reading a Photoresistor

from microbit import *

calibrationVal = pin0.read_analog()
sleep(1000)

while True:
    lightVal = pin0.read_analog()
    if lightVal < calibrationVal-50:
        pin16.write_digital(1)
    else:
        pin16.write_digital(0)

code for readLDR

Code to Note

if and else

If the light value variable that is constantly being updated in the forever loop is less than the calibration value minus 50, it is dark and the LED should turn on. The (-50) portion of the if statement is a sensitivity value. The higher the value, the less sensitive the circuit will be; the lower the value, the more sensitive it will be to lighting conditions.

The if and else statements are a simple way to set the control flow of your forever loop. If the logical statement tied to the if statement is True, then it will execute the code indented under the colon. If that statement is False, it will skip to the next statement, which is else. In this case, if the statement is True (the room is dark), then the micro:bit will turn on the LED on pin 16; else (if the room is bright), it will turn the LED off using a write_digital() command covered earlier.

calibrationval is a calibration variable. Your micro:bit takes a single reading of the light sensor before entering the forever loop and uses this value to compare against the lightVal variable in the forever loop. This value doesn't change in the forever loop, as it is set before entering the forver loop. To update this value, you can press the RESET button on the back of your micro:bit or power cycle the board.

What You Should See

When the micro:bit runs the program, it will take a single reading from the light sensor and use that as a calibration value of the "normal" state of the room. When you place your hand over the light sensor or turn the lights off, the LED will turn on. If you turn the lights back on or uncover the light sensor, the LED will turn off.

Exp 3 Final Assembly

Troubleshooting

LED Remains Dark

You may have been leaning over the light sensor when the code started. Make sure the light sensor is reading the normal light in the room at startup. Try resetting the micro:bit.

Still Not Quite Working

Double-check your wiring of the signal pin; sometimes you miss a breadboard connection by a row.

Experiment 4: Driving an RGB LED

Introduction

You know what’s even more fun than a blinking LED? Changing colors with one LED! In this circuit you’ll learn how to use an RGB LED to create unique color combinations. Depending on how bright each diode is, nearly any color is possible!

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-b USB Cable
  • 1x Common Cathode RGB LED
  • 3x 100Ω Resistors
  • 5x Jumper Wires

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
LED - RGB Diffused Common Cathode

LED - RGB Diffused Common Cathode

COM-09264
$2.25
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Pulse Width Modulation

February 27, 2013

An introduction to the concept of Pulse Width Modulation.

Introducing the Red/Green/Blue (RGB) LED

RGB Diffused Common Cathode LED

The Red/Green/Blue (RGB) LED is three LEDs in one. The RGB has four pins with each of the three shorter pins controlling an individual color: red, green or blue. The longer pin of the RGB is the common ground pin. You can create a custom-colored LED by turning different colors on and off to combine them. For example, if you turn on the red pin and green pin, the RGB will light up as yellow.

But which pin is which color? Pick up the RGB so that the longest pin (common ground) is aligned to the left as shown in the graphic below. The pins are Red, Ground, Green and Blue --- starting from the far left.

RGB LED pinout

Note: When wiring the RGB, each colored pin still needs a current-limiting resistor in line with the micro:bit's I/O pin that you plan to use to control it, as with any standard LED.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Diagram

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

Let's drive an RGB LED. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex4_drivingRGB.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 4.0
# Driving an RGB LED

from microbit import *
from random import randint

redVal = randint(0, 255)
greenVal = 0
blueVal = 0

while True:
    if button_a.is_pressed():
        redVal = 0
        blueVal = 0
        greenVal = randint(0, 255)
        pin0.write_analog(redVal)
        pin1.write_analog(greenVal)
        pin2.write_analog(blueVal)
    elif button_b.is_pressed():
        redVal = 0
        blueVal = randint(0, 255)
        greenVal = 0
        pin0.write_analog(redVal)
        pin1.write_analog(greenVal)
        pin2.write_analog(blueVal)
    else:
        pin0.write_analog(redVal)
        pin1.write_analog(greenVal)
        pin2.write_analog(blueVal)

code image for drivingRGB

Code to Note

Using the random module

MicroPython comes with a random module to introduce a little unknown into your programs. There are a few ways you can use the random module beyond using it as a random number generator the way it is used in this experiment. To see the documentation, read the official docs on the random module.

In this experiment we are using random to generate a random number between 0 and 255

button_a.is_pressed() and button_b.is_pressed()

button_a and button_b represent the left and right buttons on the micro:bit respectively. There are three built-in functions that can be attached to button_a or button_b:

  • is_pressed() --- Will return True if the button specified is pressed. If the specified button is not pressed, it will return False.
  • was_pressed() --- Will return True or False depending on whether the specified button was pressed since start-up or since the last time this statement (method) was called.
  • get_pressed() --- Will return the number of times the specified button has been pressed since the device started or since the last time the statement (method) was used. Once the method is used, it will reset to zero.

elif

The elif statement lets you check for multiple expressions that might be True. In this experiment we want to do different things whether button A pressed is True or button B pressed is True.

What You Should See

You should see your LED turn on red. If you press the A button on the micro:bit, the color will change to green, and if you press the B button, the color will change to blue. Try modifying the code to mix all three colors and display a white.

Exp 4 RGB LED

Troubleshooting

LED Remains Dark or Shows Incorrect Color

With the four pins of the LED so close together, it’s sometimes easy to misplace one. Double check that each pin is where it should be.

Seeing Red

The red diode within the RGB LED may be a bit brighter than the other two. To make your colors more balanced, use a higher ohm resistor.

Experiment 5: Reading an SPDT Switch

Introduction

In this experiment you will use your first digital input: a switch. The SPDT (Single-Pole, Double-Throw) switch is a simple way to select between two options, especially when paired with an "if" state. You will use that switch to select which of the two LEDs will blink.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-B USB Cable
  • 2x LEDs (1 Red, 1 Yellow)
  • 2x 100Ω Resistors
  • 8x Jumper Wires
  • 1x SPDT Switch

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
Mini Power Switch - SPDT

Mini Power Switch - SPDT

COM-00102
$1.60
LED - Basic Red 5mm

LED - Basic Red 5mm

COM-09590
$0.45
Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14493
$1.25

Suggested Reading

Before continuing with this tutorial, we recommend you be somewhat familiar with the concepts in these tutorials:

Button and Switch Basics

May 7, 2013

A tutorial on electronics' most overlooked and underappreciated component: the switch! Here we explain the difference between momentary and maintained switches and what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Digital Logic

October 3, 2013

A primer on digital logic concepts in hardware and software.

Introducing the Single-Pole, Double-Throw (SPDT) Switch

image of single pole double throw switch

The Single-Pole, Double-Throw (SPDT) switch has a common pin in the middle and then two other pins that, depending on the location of the switch, are either connected to the common (center) pin or not. Reading a switch is similar to a button. You need to connect the common pin to a digital General Purpose Input/Output (GPIO) pin on your micro:bit and the other pins to 3.3V and ground. It doesn’t matter which pin is which. When you move the switch, the common pin will either be HIGH (connected to 3.3V) or LOW (connected to ground).

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

fritzing diagram for wiring hookup

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail you will need to jump between the upper end and lower end.

Run Your Script

Let's read a SPDT switch and control some LEDs. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex5_readSPDT.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 5.0
# Reading an SPDT Switch

from microbit import *

while True:
    if pin0.read_digital():
        pin15.write_digital(1)
        sleep(1000)
        pin15.write_digital(0)
        sleep(1000)
    else:
        pin16.write_digital(1)
        sleep(500)
        pin16.write_digital(0)
        sleep(500)

code image for readSPDT

Code to Note

pin0.read_digital()

Just as the write_digital() statement turns a pin on (1) or off (0), the read_digital() statement determines the state of a pin, which is either HIGH (1) or LOW (0). By building a circuit that connects 3.3V or ground to a pin, we can detect if a switch is thrown or a button is pressed.

What You Should See

Depending on the state of the switch, a different LED will blink. If you move the switch to connect the signal pin to 3.3V (HIGH) then the LED connected to pin P15 will blink. If you flip the switch and ground the signal pin, then the LED on pin P16 will start blinking, and LED 1 will turn off.

Experiment 5 Switch and LEDs

Troubleshooting

Light Not Turning On

The wires for the switch are right next to each other. Make sure that signal is in the center with voltage and ground on the outside pins. If you connect ground and voltage, your board will short out and shut down.

Make sure your power LED is on. If it is off, pull the signal wire and see if that changes anything. If you short circuit your micro:bit board, it will turn itself off to protect the circuitry.

Underwhelmed

No worries; these circuits are all super stripped-down to make playing with the components easy, but once you throw them together, the sky is the limit.

Experiment 6: Reading a Button Press

Introduction

Up until now, we’ve focused mostly on outputs. Now we’re going to go to the other end of the spectrum and play around with inputs. In Experiment 2, we used an analog input to read the potentiometer. In this experiment, we’ll be reading one of the most common and simple inputs --- a push button --- by using a digital input. We will use it to cycle through different colors on the RGB.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x Common Cathode RGB LED
  • 3x 100Ω Resistors
  • 8x Jumper Wires
  • 1x Push Button
  • 1x 10kΩ Resistor

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
Momentary Pushbutton Switch - 12mm Square

Momentary Pushbutton Switch - 12mm Square

COM-09190
$0.55
4
Resistor 10K Ohm 1/6th Watt PTH - 20 pack

Resistor 10K Ohm 1/6th Watt PTH - 20 pack

COM-11508
$0.95
Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14493
$1.25

Suggested Reading

Before continuing with this experiment, we recommend you be somewhat familiar with the concepts in these tutorials:

Button and Switch Basics

May 7, 2013

A tutorial on electronics' most overlooked and underappreciated component: the switch! Here we explain the difference between momentary and maintained switches and what all those acronyms (NO, NC, SPDT, SPST, ...) stand for.

Analog vs. Digital

July 18, 2013

This tutorial covers the concept of analog and digital signals, as they relate to electronics.

Introducing the Push Button

image of a push button

A momentary push button closes or completes the circuit only while it is being pressed. The button has four pins, which are broken out into two sets of two pins. When you press down on the button and get a nice "click," the button bridges the two sets of pins and allows current to flow through the circuit.

How do you know which pins are paired up? The buttons included in this kit will only fit across the breadboard ditch in one direction. Once you get the button pressed firmly into the breadboard (across the ditch), the pins are horizontally paired. The pins toward the top of the breadboard are connected, and the pins toward the button of the breadboard are connected.

Note: Not all buttons share this pin format. Please refer to the data sheet of your specific button to determine which pins are paired up.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Diagram: micro:bit SIK Exp  6

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Run Your Script

Let's read a button press and control an RGB LED. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex6_readButton.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 6.0
# Reading a button press

from microbit import *

led_pins = [pin0, pin1, pin2]
led_states = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
led_states_iter = iter(led_states)
RED = 0
GREEN = 1
BLUE = 2

while True:
    while pin16.read_digital() == 0:
        pass
    while pin16.read_digital() == 1:
        pass
    try:
        led_state = next(led_states_iter)
    except:
        led_states_iter = iter(led_states)

    pin0.write_analog(led_state[RED])
    pin1.write_analog(led_state[GREEN])
    pin2.write_analog(led_state[BLUE])

code image for readButton

Code to Note

Pins on the micro:bit are active-low, which means external buttons should be connected to the pin and to ground to trigger an event with a button. This cannot be changed in MicroPython the way it can be changed in MakeCode. We have also found that MicroPython has a very hard time with interrupts and can't seem to run more than one thread at a time. With MakeCode, it is possible to run multiple threads.

pass

Since interrupts are very difficult in MicroPython, we decided to use pass. pass is a way to handle external triggers from a while loop without impacting the while loop. In this case, the external trigger is whether or not the button has been pressed. It is a kind of cheat to using interrupts. We can continuously poll pin 16 on the micro:bit to see if the button has been pressed or not.

iter

The iter()_method creates an object that can be iterated or incremented one element at a time until a specified end. At the end of the iteration, an exception is raised: "StopIteration."

try and except

try and except allows a program to catch an unexpected (or expected in this case) error and handle the error however the programmer wants to. The error in this case would be how the iter function lets the program know it is past the last iterable value. The exception that is thrown by the iter method is "StopIteration." We are "trying" next iter until the exception is thrown. Once the exception is thrown, we exit from try and move onto except, which will start the iterator over again.

What You Should See

When you press the button, the RGB will turn on to a color. When you press it again, the color will change, and another press will change the color once again. Press it one more time, and it will turn off. Every time you press the button, it increments a variable, and then we check against it to set the color. If the variable goes over the value of 2, we reset it to 0, which is off.

Exp 6 Final Assembly

While the image shows a black momentary pushbutton, you can use any colored button as long as it is momentary pushbutton to cycle through the colors!

Troubleshooting

Light Not Turning On

The push button is square, and because of this it is easy to put it in the wrong way. Give it a 90-degree twist and see if it starts working.

Underwhelmed

No worries; these circuits are all super stripped-down to make playing with the components easy, but once you throw them together, the sky is the limit. Remember, though, that these are building blocks to the Iron Man suit.

Experiment 7: Reading the Temperature Sensor

Introduction

A temperature sensor is exactly what it sounds like --- a sensor used to measure ambient temperature. In this experiment you will read the raw 0--1023 value from the temperature sensor, calculate the actual temperature and then print it out over the LED array on your micro:bit.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-b USB Cable
  • 3x Jumper Wires
  • 1x TMP36 Temperature Sensor

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
Temperature Sensor - TMP36

Temperature Sensor - TMP36

SEN-10988
$1.60
18
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15

Introducing the TMP36 Temperature Sensor

image of temperature sensor

The TMP36 is a low-voltage precision centigrade temperature sensor. It provides a voltage output that is linearly proportional to the Celsius temperature. It also doesn’t require any external calibration to provide typical accuracies of ±1°C at +25°C and ±2°C over the −40°C to +125°C temperature range. The output voltage can easily convert to temperature using the scale factor of 10 mV/°C.

If you are looking at the flat face with text on it, the center pin is your signal pin, the left-hand pin is supply voltage (3.3V in this tutorial), and the right-hand pin connects to ground.

Pro Tip: The TMP36 looks a lot like a transistor. Put a dot of fingernail polish on the top of your TMP36 so it’s easy to find.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Please note: The temperature sensor can only be connected to a circuit in one direction. See below for the pin outs of the temperature sensor --- TMP36.

Wiring Diagram for the Experiment

fritzing hookup diagram

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

Let's read a temperature sensor. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex7_readTemp.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 7.0
# Reading a Temp Sensor

from microbit import *

while True:
    rawTemp = pin2.read_analog()
    degC = (((rawTemp*3.3)/(1023))-0.5)*100
    display.scroll(str(degC))
    sleep(1000)

code image for readTemp

Code to Note

str

We have already covered display.scroll() but we need to convert our number (temperature) to a string (type) before displaying it to the micro:bit 5x5 LED array. Type conversion in MicroPython is a snap with a simple str placed in front of the variable holding the temperature of type number.

CHALLENGE: How would you modify this code to get the temperature in degrees Fahrenheit?

What You Should See

When your micro:bit turns on, the temperature reading from the TMP36 temperature sensor will be displayed and scrolled across the LED array.

Exp 7 Final Assembly

Troubleshooting

Temperature Value is Unchanging

Try pinching the sensor with your fingers to heat it up or pressing a bag of ice against it to cool it down.

Temperature Reads Random 5-Digit Number

If you see an output with "65525", "65533", "65527", etc. on the LEDs, the issue might be due to a loose (or possibly shorted) connection between the 3.3V pin and the TMP36's voltage input pin. The analog pin will probably start reading random values or there is a slight current draw to the temperature sensor from the micro:bit. Make sure that you check your connections by ensuring that there are no loose connections or pins touching where they should not. If you are using alligator clips, make sure that the connection is secure as well and that there are no shorts (try sliding the sheath around the alligator clips for more insulation).

Temperature Sensor is Really Hot!

You have wired it backward! Unplug your micro:bit immediately, let the sensor cool down and double check your wiring. If you catch it soon enough, your sensor may not have been damaged and may still work.

Experiment 8: Using a Servo Motor

Introduction

This experiment is your introduction to the servo motor, which is a smart motor that you can tell to rotate to a specific angular location. You will program it to rotate to a series of locations, then sweep across its full range of motion, and then repeat.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-B USB Cable
  • 1x Servo
  • 3x Jumper Wires

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$9.95
13
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15

Suggested Reading

Before continuing with this experiment, we recommend you be familiar with the concepts in the following tutorial:

Pulse Width Modulation

February 27, 2013

An introduction to the concept of Pulse Width Modulation.

Hobby Servo Tutorial

May 26, 2016

Servos are motors that allow you to accurately control the rotation of the output shaft, opening up all kinds of possibilities for robotics and other projects.

Introducing the Servo Motor

image of a servo motor

Unlike the action of most motors that continuously rotate, a servo motor can rotate to and hold a specific angle until it is told to rotate to a different angle. You can control the angle of the servo by sending it a PWM (Pulse Width Modulation) pulse train; the PWM signal is mapped to a specific angle from 0 to 180 degrees.

Inside of the servo there is a gearbox connected to a motor that drives the shaft. There is also a potentiometer that gives feedback on the rotational position of the servo, which is then compared to the incoming PWM signal. The servo adjusts accordingly to match the two signals.

In this experiment, the servo is powered through 3.3 volts on the red wire and ground on the black wire; the white wire is connected to pin P0.

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Connect 3x jumper wires to the female 3-pin header on the servo. This will make it easier to breadboard the servo.

Wiring Diagram for the Experiment

Fritzing Diagram: Exp 8

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

Let's drive a servo. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex8_usingServo.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 8.0
# Using a servo motor

from microbit import *


class Servo:
    def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
        self.min_us = min_us
        self.max_us = max_us
        self.us = 0
        self.freq = freq
        self.angle = angle
        self.analog_period = 0
        self.pin = pin
        analog_period = round((1/self.freq) * 1000)  # hertz to miliseconds
        self.pin.set_analog_period(analog_period)

    def write_us(self, us):
        us = min(self.max_us, max(self.min_us, us))
        duty = round(us * 1024 * self.freq // 1000000)
        self.pin.write_analog(duty)
        sleep(100)
        self.pin.write_digital(0)  # turn the pin off

    def write_angle(self, degrees=None):
        if degrees is None:
            degrees = math.degrees(radians)
        degrees = degrees % 360
        total_range = self.max_us - self.min_us
        us = self.min_us + total_range * degrees // self.angle
        self.write_us(us)


Servo(pin0).write_angle(0)
while True:
    if button_a.is_pressed():
        for angle in range(0, 90, 5):
            Servo(pin0).write_angle(angle)
            sleep(200)
    if button_b.is_pressed():
        Servo(pin0).write_angle(0)
        sleep(1000)
        Servo(pin0).write_angle(90)
        sleep(1000)
        Servo(pin0).write_angle(0)
        sleep(1000)
    else:
        Servo(pin0).write_angle(180)

code image for usingServo

Code to Note

One of the major drawbacks to using MicroPython with the micro:bit is that you can't import third-party modules in Mu. Or at least, we haven't had any luck flashing two Python files in the editor to the micro:bit. This code seems long because we had to paste the Servo Class code into our script for ease of use [1]. Ignoring the Servo Class code, let's look at what's happening inside the forever loop.

range

The range function generates a list of numbers. In this experiment we are generating a list from 0--90 that increases by 5.

Servo(pin0).write_angle()

The Servo Class is called in statement with pin 0 as its argument. The .write_angle() function is how the servo is moved --- by the number specified in the parentheses mapped to degrees on the servo motor.

What You Should See

When powered up you should see the servo move to a single location (0 degrees) and then start to sweep to 180 degrees back and forth until you turn it off or tell it to go to a different angle.

Exp 8 and 10 Final Assembly

CHALLENGE: How would you modify this code to get the servo to sweep to 180 degrees on button A pressed?

Exp 8 and 10 Final Assembly

Troubleshooting

Servo Not Twisting

Even with colored wires, it is still shockingly easy to plug a servo in backward. This might be the case.

Still Not Working

A mistake we made a time or two was simply forgetting to connect the power (red and black wires) to 3.3 volts and ground (GND).

Experiment 9: Using a Buzzer

Introduction

In this experiment, we will again bridge the gap between the digital world and the analog world. We'll be using a piezo buzzer that makes a small "click" when you apply voltage to it (try it!). By itself that isn't terribly exciting, but if you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you've got music! This circuit and set of code blocks will create a simple sound machine.

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-b USB Cable
  • 1x Piezo Buzzer
  • 2x Momentary Push Buttons
  • 7x Jumper Wires

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
Mini Speaker - PC Mount 12mm 2.048kHz

Mini Speaker - PC Mount 12mm 2.048kHz

COM-07950
$2.10
5
Momentary Pushbutton Switch - 12mm Square

Momentary Pushbutton Switch - 12mm Square

COM-09190
$0.55
4

Introducing the Piezo Buzzer

Buzzer

The buzzer is a small component with a piece of metal in it that moves when you apply a voltage across it. This motion causes a small sound, or "click." If you turn the voltage on and off fast enough, you get different beeps, squeals, chirps and buzzes. You will use PWM to control the speed of turning the piezo on and off --- and, in turn, the audio frequency coming out of the buzzer. Adjusting the PWM enables you to get legitimate notes out of the buzzer.

Buzzer Dimensions

If you flip the buzzer over and look at the bottom, you will see that one pin has a (+) next to it. That pin gets connected to a signal from the P0 pin. The other pin should be connected to ground.

For users with a micro:bit v2, there is also a built-in piezo buzzer. We will be focusing on wiring an external piezo buzzer.

Piezo Buzzer on micro:bit v2

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Diagram: MicroPython micro:bit SIK Exp 9

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full-sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail, you will need to jump between the upper end and lower end.

Run Your Script

Let's drive a buzzer. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex9_usingBuzzer.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 9.0
# Using a buzzer

from microbit import *
import music

# disable built-in speaker on micro:bit v2 and output to external speaker from pin P0
speaker.off()

while True:
    if pin15.read_digital() == 1:
        music.play("C4:8")
    elif pin16.read_digital() == 1:
        music.play("D1:8")
    else:
        pass

alt text

Code to Note

speaker.off()

The `speaker.off() function disables the built-in speaker on the micro:bit v2 and outputs a signal to the external piezo buzzer from P0. For users that are using micro:bit v1 boards, simply comment out this function before compiling and downloading the program in the editor.

music

MicroPython has an awesome music and sound module. We spent hours generating tones and writing songs in the REPL. As you learn to compose your own music on the micro:bit we highly recommend using the REPL to become familiar with all the sounds --- plus the help() feature is nice when you want to see (hear) what you can do.

The music module has 21 melodies built in. To see a list, begin typing music.play(_... in the Mu editor, and the list should pop up.

To get an in-depth tutorial on the music module, click here.

music.play()

To play a tune you need to specify a note (A, C#, F), an octave (0--8) and a duration (how long the note will be played). For example, if the button on pin 15 is pressed, the note C in octave 4 will play for a duration of 8.

What You Should See

What you should see --- well, nothing! What you should hear --- each button has its own tune. Enjoy your sound machine and feel free to swap out the song and tunes of your choice. Add more buttons and play statements to make your custom piano!

Exp 9 Final Assembly

While the image shows black momentary pushbuttons, you can use any colored button as long as it is momentary pushbutton to trigger the sounds!

Try wiring a potentiometer between the buzzer and pin 0. Adding a potentiometer will adjust the volume. Adjust the code where it says speaker.off() to speaker.on() will also output sound to the built-in speaker.

Try it again but with a real speaker. At the press of a button you could play the funeral march, Happy Birthday or the Nyan Cat theme with much better audio!

Troubleshooting

No Sound

Given the size and shape of the piezo buzzer, it is easy to miss the right holes on the breadboard. Try double checking its placement.

Also, double check to make sure the push button is wired correctly. If you miswired it, then the circuit will never be completed, whether you press the button or not.

Experiment 10: Using the Accelerometer

Introduction

In this experiment you will look at combining the use of the accelerometer on the micro:bit to measure the orientation of the micro:bit and using it to control the angle of a servo.

Ready to shake, rattle and roll?

Parts Needed

You will need the following parts:

  • 1x Breadboard
  • 1x micro:bit
  • 1x micro:bit Breakout with Headers
  • 1x micro-B USB Cable
  • 1x Hobby Servo
  • 3x Jumper Wires

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
Breadboard - Self-Adhesive (White)

Breadboard - Self-Adhesive (White)

PRT-12002
$5.50
48
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Jumper Wires - Connected 6" (M/M, 20 pack)

Jumper Wires - Connected 6" (M/M, 20 pack)

PRT-12795
$2.10
2
Servo - Generic (Sub-Micro Size)

Servo - Generic (Sub-Micro Size)

ROB-09065
$9.95
13
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15

Introducing the Accelerometer

The accelerometer is a component that you won't find in the kit's bag of parts. Why? Because it is on the micro:bit itself! On the back of the micro:bit you can see a number of small chips. One of them is the accelerometer. The micro:bit has an onboard accelerometer that measures gravitational force. Depending on the version that you have, the accelerometer and compass can be on separate ICs or combined into a single IC.

v1.0 w/ Accelerometer on Sepearate IC v1.5 w/ Combined Accelerometer and Magnetometer
v1.0 w/ Accelerometer on Separate IC v1.5 w/ Combined Accelerometer and Magnetometer

An accelerometer is a sensor that measures the gravitational forces pulling on it in all three dimensions of the chip's X, Y and Z axes.

Triple Axis Accelerometer Visualization

Visualization of a Common Accelerometer (ADXL345) with Three Axes

Not only can an accelerometer measure the raw forces pulling on the chip and the object that the chip is sitting on, but it can also detect steps, shakes and other motions that have a specific pattern. On top of that, you can use an accelerometer to simply detect the orientation of the device. Did you ever wonder how your phone knows when you turn it from portrait to landscape? It is all because of the accelerometer in your phone!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Diagram: Exp 10

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Run Your Script

Let's read an accelerometer and control a servo. Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex10_usingAccel.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 10
# Using the Accelerometer

from microbit import *


class Servo:
    def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
        self.min_us = min_us
        self.max_us = max_us
        self.us = 0
        self.freq = freq
        self.angle = angle
        self.analog_period = 0
        self.pin = pin
        analog_period = round((1/self.freq) * 1000)  # hertz to miliseconds
        self.pin.set_analog_period(analog_period)

    def write_us(self, us):
        us = min(self.max_us, max(self.min_us, us))
        duty = round(us * 1024 * self.freq // 1000000)
        self.pin.write_analog(duty)
        sleep(100)
        self.pin.write_digital(0)  # turn the pin off

    def write_angle(self, degrees=None):
        if degrees is None:
            degrees = math.degrees(radians)
        degrees = degrees % 360
        total_range = self.max_us - self.min_us
        us = self.min_us + total_range * degrees // self.angle
        self.write_us(us)


Servo(pin0).write_angle(0)
while True:
    num = accelerometer.get_x()
    Servo(pin0).write_angle(num * 180 / 2048 + 90)

alt text

Code to Note

Ignoring the servo class code again [1], we've got some new stuff!

accelerometer.get_x()

The accelerometer module comes with five built-in functions and recognizes 11 gestures. To see the full documentation, click here. The accelerometer.get_x() statement will return the acceleration measurement on the x-axis as a number between -1024 and 1024, depending on the direction.

Since the value stored in num needs to translated to an angle between 0-180 from a range between -1024 and 1024 it needs to be scaled. Adding 90 to the scaled value sets a range of angles for the negative accelerometer values from 0-89, and positive accelerometer values from 90-180.

What You Should See

At the beginning of the program the servo should move to 0 degrees and then react to the orientation of the micro:bit. If you hold the micro:bit flat, the servo will be at 90 degrees. Then if you tilt the servo to the left, it will move less than 90 degrees toward the value of 0. If you move it to the right, the servo will move toward 180.

Exp 8 and 10 Final Assembly

Troubleshooting

This Seems Backward

You may be holding the micro:bit in a different orientation. Flip it around and try again!

Servo Isn't Working

Double check your wiring! Remember, red to 3.3 volts, black to ground, and white to signal.

Experiment 11: Using the Compass (Magnetometer)

Introduction

This experiment is just plain fun! Have you ever used a compass? Are you a little confused in terms of which direction to go? Fear not! We will build a digital compass that will keep you on track to the North Pole using the micro:bit's onboard compass chip!

Parts Needed

You will need the following parts:

  • 1x micro:bit
  • 1x Micro B USB Cable
  • 1x micro:bit Breakout (with Headers)
  • 1x micro-B USB Cable
  • 1x Breadboard
  • 4x Jumper Wires
  • 2x LEDs
  • 2x 100Ω Resistors

Didn't Get the SIK for micro:bit?

If you are conducting this experiment and didn't get the Inventor's Kit, we suggest using these parts:

micro:bit v2 Board

micro:bit v2 Board

DEV-17287
$16.50
7
SparkFun Qwiic micro:bit Breakout (with Headers)

SparkFun Qwiic micro:bit Breakout (with Headers)

BOB-16446
$6.25
2
Breadboard - Full-Size (Bare)

Breadboard - Full-Size (Bare)

PRT-12615
$6.50
32
USB Micro-B Cable - 6 Foot

USB Micro-B Cable - 6 Foot

CAB-10215
$5.50
15
Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

Jumper Wires Standard 7" M/M - 30 AWG (30 Pack)

PRT-11026
$2.45
20
LED - Basic Red 5mm

LED - Basic Red 5mm

COM-09590
$0.45
Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

Resistor 100 Ohm 1/4 Watt PTH - 20 pack (Thick Leads)

PRT-14493
$1.25

Introducing the Compass (Magnetometer)

In the previous experiment you learned about the accelerometer, which measured gravity. The compass, or technically the magnetometer, measures a magnetic field. Magnetic fields come in different sizes, but the biggest is the one produced by Earth itself, which is why compasses work.

The micro:bit has an onboard compass (a.k.a. a magnetometer) that can detect its orientation using Earth's magnetic field. Depending on the version that you have, the accelerometer and compass can be on separate ICs or combined into a single IC.

v1.0 w/ Magnetometer On Separate IC v1.5 w/ Combined Accelerometer and Magnetometer
v1.0 w/ Magnetometer On Separate IC v1.5 w/ Combined Accelerometer and Magnetometer

The magnetometer detects magnetic north and then represents your heading in degrees with north being 0 degrees, east being 90 degrees, south being 180 degrees and west being 270. Pretty cool! Now let's put this compass to good use!

Hardware Hookup

Ready to start hooking everything up? Check out the wiring diagram below to see how everything is connected.

Polarized Components Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.

Wiring Diagram for the Experiment

Fritzing Diagram: Exp 11

Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.

Note: The full sized breadboard power rails have a break down the middle. If you end up using the lower half of the power rail you will need to jump between the upper end and lower end.

Run Your Script

Let's read a magnetometer and light up a few LEDs . Type (or copy) the program into your Mu editor, or download all the programs from this GitHub Repository and open the Ex11_usingMag.py program. Save it, then click the Flash icon to program your micro:bit.

language:python
# SparkFun Electronics
# Experiment 11
# Using the Compass (Magnetometer)

from microbit import *

compass.calibrate()
while True:
    bearing = compass.heading()
    sleep(10)

    #bearing is the degrees
    if ( bearing > 10 and bearing < 180 ):
        pin0.write_digital(0)
        pin16.write_digital(1)
    #bearing is the degrees
    elif ( bearing > 180 and bearing < 350 ):
        pin0.write_digital(1)
        pin16.write_digital(0)
    #bearing is the degrees
    else:
        pin0.write_digital(1)
        pin16.write_digital(1)



code image for usingCompass.py

Code to Note

Let's take a look at the code in this experiment.

compass.heading()

The compass heading function returns the heading that you are facing if you are holding the micro:bit flat with the pins toward you. Zero degrees is north. We store this heading in a variable called bearing.

and

Much of the rest of this code is straightforward, but the logical and operator is used. This combines two logical statements into one statement that returns true when both of the other statements are true and only true.

What You Should See

When your code is loaded you will first see instructions on the micro:bit LED array. The instructions will ask you to tilt the micro:bit around until all of the LEDs on the micro:bit face have been lit up. Once this has been done, it will display a smiley face. This process is to calibrate the micro:bit's magnetometer with its surroundings. The LEDs will start to turn on --- one or the other, or both. While standing still, rotate in the direction of the LED that is on. When both LEDs are lit, you are facing generally north (if you are outside)! You now have a compass that helps you find north, or any other direction you choose if you change the code!

Exp 11 Final Assembly

Note: If you calibrate your micro:bit while inside and in a proximity to your computer or something that produces a larger magnetic field it will skew your micro:bits sense of direction. You will end up creating a metal detector rather than a compass!

Troubleshooting

Not Really North?

You may have a motor or magnet close by! The magnetometer is sensitive to all magnetic fields, including ones that may be produced by other electronics, metal, or even...a magnet.

LEDs Seem Backward

You might have your logical statement backward! Try flipping your greater than to less than, or the other way around.

Resources and Going Further

For more information about the micro:bit breakout board, check out the resources below:

MicroPython is a fun and exciting way to get started on your Python programming journey. Here are some more resources to help you along.

We produce a number of other kits and carrier boards that you can hook up to your micro:bit to help take your projects to the next level. Here is some further reading that may help you along in learning more about the world of electronics.

For more information on our micro:bit ecosystem, check out these tutorials:

micro:climate Kit Experiment Guide

A weather station kit that is built on top of the inexpensive, easy-to-use micro:bit and Microsoft MakeCode.

micro:bot Kit Experiment Guide

Get started with the moto:bit, a carrier board for the micro:bit that allows you to control motors, and create your own robot using this experiment guide for the micro:bot kit.

micro:arcade Kit Experiment Guide

We love games! We love writing games, building games and yes, even building game consoles. So we want to introduce to you the micro:arcade kit for the micro:bit!

micro:bit Breakout Board Hookup Guide

How to get started with the micro:bit breakout board.