MicroPython — external sensors and actuators

Lesson 9 of 17 · MicroPython and the micro:bit
Safety when connecting:
the micro:bit works at 3 V. Do not power motors, pumps or strips with many LEDs directly from a pin – use a driver or a separate power supply. Connect parts while the micro:bit is unplugged from USB.

Besides the built-in sensors (accelerometer, compass, temperature), the micro:bit can be connected to external sensors and actuators. This makes more serious projects possible and is an introduction to electronics.


In this lesson we will get to know:

  • digital and analog inputs
  • working with distance sensors
  • servo motors and other actuators

GPIO pins on the micro:bit


The micro:bit has GPIO pins (P0, P1, P2…) through which it communicates with external components.

Pins can be:

  • inputs — reading sensors
  • outputs — controlling actuators

✔ Reference: MicroPython pin documentation


Example: reading a sensor as an analog value


Many sensors (for example a potentiometer, a light sensor, a moisture sensor) return an analog value.



from microbit import *

while True:
    value = pin0.read_analog()
    display.scroll(value)
    sleep(500)

The function read_analog() returns a value from 0 to 1023.


A distance sensor (ultrasonic)


An ultrasonic sensor measures distance using sound waves. It is often used in robotics and smart systems.


The basic idea:

  • one pin sends a pulse (TRIG)
  • another pin receives the echo (ECHO)

✔ This sensor is often covered in more detail in higher grades, but it is important to understand the concept.


✔ MakeCode simulation: https://makecode.microbit.org


Actuators — a servo motor


Actuators are devices that do something:

  • they start a motor
  • they switch on an LED
  • they make a sound

A servo motor is controlled with a PWM signal.



from microbit import *

while True:
    pin1.write_analog(30)
    sleep(1000)
    pin1.write_analog(120)
    sleep(1000)

By changing the value we change the angle of the servo.


Combining sensors and actuators


The most interesting projects happen when:

  • a sensor measures the state of the surroundings
  • the program makes a decision
  • an actuator reacts

An example idea:

  • if the temperature is high → switch on a motor
  • if the distance is small → sound an alarm

Mini task


Connect one sensor (for example a potentiometer or a push button) and write a program that:

  • reads the value of the sensor
  • switches an actuator on or off depending on the value

You do not need a real component — think algorithmically.


The link with the next lessons


We will use this knowledge in:

  • mini projects
  • algorithms and decision logic
  • connecting to a computer (Processing / serial)


The difference: a digital and an analog signal


A digital signal has only two values:

  • 0 (off)
  • 1 (on)

An analog signal has a range of values:

  • 0 – 1023 (micro:bit)

A graphical explanation

A digital signal:

1  ────────      ────────
0          ──────
     time →

An analog signal:

1023 |        /\
 800 |       /  \
 500 |      /    \
 200 |_____/      \____
     0___________________
           time →

Example — controlling the brightness of an LED with a potentiometer



from microbit import *

while True:
    value = pin0.read_analog()

    # Scaling from 0–1023 to 0–9 (LED brightness)
    brightness = value * 9 // 1023

    display.set_pixel(2, 2, brightness)
    sleep(100)

The more you turn the potentiometer — the brighter the LED shines.


Mini project — A parking sensor


The idea:

  • The sensor measures the distance
  • If an obstacle is close → switch on an alarm

Since we do not have real ultrasonic code in this version, we will simulate the distance with an analog input.


from microbit import *

while True:
    distance = pin0.read_analog()  # simulation

    if distance < 300:
        display.show(Image.SKULL)
    else:
        display.show(Image.YES)

    sleep(200)

Mini project — An automatic barrier


If an object comes close — the barrier goes up.


from microbit import *

while True:
    value = pin0.read_analog()

    if value < 400:
        pin1.write_analog(120)  # barrier up
    else:
        pin1.write_analog(30)   # barrier down

    sleep(200)

Mini project — A smart fan


If the temperature is high — switch on the motor.


from microbit import *

while True:
    t = temperature()

    if t > 28:
        pin1.write_digital(1)
    else:
        pin1.write_digital(0)

    sleep(500)

How does a smart system work?

SENSOR (measures data)
        ↓
PROGRAM (makes a decision)
        ↓
ACTUATOR (reacts)

Example:

Temperature = 30°C
        ↓
Is it > 28 ?
        ↓
YES
        ↓
Switch on the fan

Challenge — A guard robot


If the sensor detects movement or something close:

  • Show an alarm
  • Move the servo

from microbit import *

while True:
    value = pin0.read_analog()

    if value < 300:
        display.show("!")
        pin1.write_analog(120)
    else:
        display.clear()
        pin1.write_analog(30)

    sleep(200)

Hidden mini quiz — sensors and actuators

Check whether you understand working with the accelerometer, the compass, temperature and GPIO pins.

Open the quiz

Mini quiz: sensors and actuators

1. Which function measures the tilt along the X axis?




2. What value does temperature() return?




3. What does the value 90° mean for the compass sensor?




4. Which function reads an analog value from a pin?




5. If we write:


if light < 400:
    pin1.write_digital(1)

What happens?




6. What do actuators do?








Tasks for independent work


Task 1

Make a system where:

  • If the light is weak → switch on an LED
  • If the light is strong → switch off the LED

Task 2

Make a system with three levels:

  • low
  • medium
  • high

Task 3 (advanced)

Combine the temperature and a distance sensor:

  • If the temperature is > 30°C and an object is close → alarm

Task 4 (challenge)

Make mini traffic lights with a servo motor and a sensor.

Hidden advanced quiz — combined conditions and sensor logic

This quiz checks whether you understand AND / OR conditions, several sensors at the same time, decision logic and analysing MicroPython code.

Open the advanced quiz

Advanced quiz: logic and sensors

1. What does the following code do?


light = pin0.read_analog()
t = temperature()

if light < 400 and t > 25:
    display.show("H")



2. Which condition switches on the alarm if movement is detected OR the temperature is too high?




3. What will the program show?


heading = compass.heading()

if heading > 170 and heading < 190:
    display.show(Image.ARROW_S)



4. Analyse the code:


if light < 400:
    if motion < 300:
        display.show("A")



5. What will happen if:


night_mode = True

if night_mode and motion < 300:
    display.show("!")



6. Where is the logical mistake?


if light < 400 or light > 200:
    display.show("X")







Mini project — A smart house


In this project the micro:bit becomes a small controller of a "smart house". The system uses several sensors and controls several actuators.

  • A light sensor (analog input)
  • A temperature sensor (built in)
  • A motion sensor (PIR, a digital input on P8)
  • An LED or a relay (light)
  • A servo motor (door / window)
  • A sound alarm

The logic of the system

IF it is dark → switch on the light
IF the temperature is high → switch on the ventilation
IF movement is detected → activate the alarm

The basic version of the program


from microbit import *

while True:

    # 1. The light sensor (analog input)
    light = pin0.read_analog()

    if light < 400:
        pin1.write_digital(1)   # switch on the light
    else:
        pin1.write_digital(0)   # switch off the light

    # 2. Temperature → ventilation (servo)
    t = temperature()

    if t > 28:
        pin2.write_analog(120)  # window open
    else:
        pin2.write_analog(30)   # window closed

    # 3. Movement → alarm (a PIR sensor on pin P8: 1 = movement)
    motion = pin8.read_digital()

    if motion == 1:
        display.show("!")
    else:
        display.clear()

    sleep(300)

Important — the structure of a smart system

        SENSORS
   (light, temp, motion)
             ↓
        DECISION (if)
             ↓
        ACTUATORS
  (LED, servo, alarm)

Extended version — Night mode

We add an operating mode with button A:

  • Night mode → the alarm is active
  • Day mode → the alarm is off

night_mode = False

while True:

    if button_a.was_pressed():
        night_mode = not night_mode

    motion = pin0.read_analog()

    if night_mode and motion < 300:
        display.show(Image.SKULL)
    else:
        display.clear()

    sleep(200)

A visual explanation of the system

          [Light] -----\
          [Temp]  -----→  micro:bit  →  [LED]
          [Motion] ----/              →  [Servo]
                                        →  [Alarm]

Advanced version — Energy efficiency

Add a condition:

  • If it is day → the light never switches on
  • If it is night and someone is in the room → switch on the light

This introduces compound conditions (AND, OR).

A challenge for students

Task 1

Add a display of the system status on the LED screen:

  • L — light on
  • V — ventilation on
  • A — alarm active

Task 2

Add a counter of how many times the alarm has been activated.

Task 3 (advanced)

Combine temperature and light:

  • If it is warm and sunny → close the window
  • If it is cold and dark → switch on the heating (simulation)

Organising the lesson

  • Work in groups (3–4 students)
  • Each group gets one part of the system
  • At the end the systems are combined

What do the students learn?

  • Working with several sensors at the same time
  • Compound conditions (AND / OR)
  • Project and system thinking
  • The basics of IoT logic
  • Modelling real systems

Related: the same topic in other lessons

The same sensors and actuators on other microcontrollers: