Friday, 20 March 2026

The "Hug Avoider": A Coding Journey from Blocks to MicroPython

This project journey follows the evolution of a simple social-distancing idea into a fully realized "Hug Avoider" wearable. Written from my perspective, it’s designed to take you from basic block coding into the professional-grade world of MicroPython.



As a maker and educator, I’m always on the hunt for "low floor, high ceiling" projects—those that are easy enough for a beginner to start in an afternoon but deep enough to keep an experienced coder engaged.

I embarked on a multi-stage project using the 4tronix EggBit. What started as a simple social-distancing experiment turned into a  transition from blocks to text-based code. Whether you're a teacher, a parent of a young coder, or a fellow maker, here is the full evolution of the "Hug Avoider."


The Hardware: Meet the EggBit

The foundation of this project is the 4tronix EggBit. It’s a "cute," egg-shaped expansion board for the BBC micro:bit, designed specifically to be wearable.

[INSERT IMAGE: The 4tronix EggBit board showing the front face and sensor mounting]

It breaks out the micro:bit’s pins into a few key components:

  • HC-SR04P Ultrasonic Sensor: These act as the "eyes."

  • LED strip: Perfect for mood lighting or status indicators.

  • A Piezo Buzzer: For audible alerts.

  • Lanyard Hole: Essential for making it a true wearable!

For the makers and "under-the-hood" tinkerers, here is the breakdown of how the EggBit maps to the micro:bit’s pins. This is essential if you plan on writing custom libraries or branching out from the standard extensions.

ComponentHardware Modelmicro:bit PinNotes
Distance SensorHC-SR04P (3V version)

Pin 13 (Trigger)


Pin 14 (Echo)

Uses standard ultrasonic pulse-timing logic.
LED StripAddressable RGB LEDsPin 8Compatible with the neopixel library.
BuzzerPassive PiezoPin 15Can play tones, melodies, or custom frequencies.
Ee
Power3V DCBattery ConnectorPowered via the micro:bit’s battery pack or USB.

Maker Tip: If you're looking to pick one up, you can grab a single EggBit here, or if you're running a classroom or a club, they offer a Three-Pack Special to save a bit of budget.


Phase 1: The "Low Floor" (MakeCode Blocks)

To get the project off the ground, I started with Microsoft MakeCode. This is the perfect entry point for students. Using the dedicated EggBit extension, you can get a "social distancing" alarm running in minutes.

The logic is straightforward: If the ultrasonic sensor detects an object closer than 50cm, the LED strip turns red and the buzzer sounds a warning.


In my Hug Avoider 2 post, I explored how this visual feedback makes the abstract concept of "distance" tangible. It’s a great way to talk about personal space while learning basic "If-Then-Else" logic.


Phase 2: Pulling Back the Curtain (MicroPython)

While blocks are great, they hide the "magic." To really understand how sensors communicate with a computer, I decided to rewrite the project in MicroPython.

For this, I highly recommend using the official MicroPython editor for the micro:bit, which makes flashing your code directly to the board a breeze.

In Hug Avoider 3, we moved away from the "Get Distance" block and wrote our own function see in Phase 3 This is a fantastic STEM lesson in physics and math. 


Phase 3: Handling Real-World Bugs

No project is complete without troubleshooting. In the final phase, I ran into a common maker hurdle: sensor reliability.

When using MicroPython, the timing doesn't need to be precise. If the sound pulse doesn't hit a solid surface (like hitting a soft, sound-absorbing sweater), 

In Hug Avoider 4, I refined the code to include "timeouts" . I found that adding a tiny space utime.sleep_ms(10) between pings . I also added a bit of personality by using the micro:bit’s 5x5 LED matrix to display an "angry" face when someone enters the personal space zone. You will need to use https://python.microbit.org/v/3 to program and download to the microbit, the speech is a bit hard to make out :-) but still fun.

from microbit import *
from machine import time_pulse_us
import neopixel, speech

sonar =pin15
sonar.write_digital(0)
fireled=neopixel.NeoPixel(pin13,9)

def rainbow():
    fireled[0] = (255, 0, 40)
    fireled[1]=  (255,165,0)
    #block=yellow
    fireled[2] = (255,255,0)
    #block=green
    fireled[3] = (0,255,0)
    #block=blue
    fireled [4] = (0,0,255)
    # block=indigo
    fireled[5] = (75,0,130)
    # block=violet
    fireled[6] = (138,43,178)
    #block=purple
    fireled[7] = (255,0,255)
    fireled.show()

def blank_it():
    for j in range(8):
        fireled[j] = (63, 0, 0)
    fireled.show()

def howfar():
    sonar.write_digital(1)
    sonar.write_digital(0)

    timeus=time_pulse_us(sonar,1)
    echo=timeus/1000000
    dist=(echo/2)*34300
    sleep(100)
    return dist

def startingMessage():
    mess1 = [
    "This is the hug avoide",
    "please keep back",
]
# Take from https://microbit-micropython.readthedocs.io/en/latest/tutorials/speech.html
    for line in mess1:
        speech.say(line, speed=120, pitch=100, throat=100, mouth=200)
        sleep(500)

def buttonplay():
    if pin12.read_digital()==1:
        #Red Button
        blank_it()
    if pin8.read_digital()==1:
        #Green button
        startingMessage()
    if pin14.read_digital()==1:
        #Yellow button
        rainbow()
    if pin16.read_digital()==1:
        #Blue button
        display.show(Image.ASLEEP)
  
while True:
    buttonplay()
    dist=howfar()
    if dist>30:
        pin2.write_digital(1)
        pin0.write_digital(0)
        display.show(Image.HAPPY)
    else:
        pin2.write_digital(1)
        pin0.write_digital(1)
        blank_it()
        speech.say("back away please", speed=120, pitch=100, throat=100, mouth=200)
        display.show(Image.ANGRY

Why This Project Wins for STEM

This journey from a simple "anti-hug" device to a refined Python-powered wearable covers the entire engineering design process:

  • For Teachers: It’s a perfect curriculum arc. Start with blocks in the junior years and move to the Python distance formula as they progress.

  • For Parents: It’s an affordable, tactile project. Seeing a child wear something they actually coded is the ultimate "lightbulb" moment.

  • For Makers: It’s a great lesson in the limitations of hardware and how to write "defensive" code that doesn't crash when sensors behave unexpectedly.


If you're ready to dive deeper into the code or the specific hardware challenges I faced, check out the original posts here:

  1. The EggBit Hardware Intro

  2. MakeCode Logic & The First Build

  3. Entering the World of Python

  4. Final Refinements & MicroPython Optimization

Happy making—and keep your distance!

All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Thursday, 12 March 2026

DIY Data Science with microbits

DIY Data Science: A Complete Guide to Data Logging with the Micro:bit V1

Whether you are a STEM teacher looking for a classroom lab solution, a parent seeking a weekend project, or a maker building an environmental monitor, the Micro:bit V1 is a hidden gem for data logging.

While the newer V2 has built-in logging memory, the V1 is incredibly capable when paired with a computer. By using the Serial (USB) Connection and Radio Communication, you can turn these pocket-sized boards into useful sensors.

The Equipment List

To get started, you will need:

  • For Local Logging:

    • 1x Micro:bit V1.

    • 1x Micro-USB cable (high quality, data-capable).

    • A computer with a Chrome-based browser (to use the WebUSB feature in MakeCode).

  • For Remote Logging:

    • 2x Micro:bit V1s.

    • 1x Battery pack (2xAAA) for the "Remote" Micro:bit.

    • 1x Micro-USB cable for the "Receiver" Micro:bit.

  • Optional (For Experiments):

    • A strong magnet (to test the Compass/Magnetometer (see later in this post).

    • A flashlight (to test Light Level).

    • An ice pack or hair dryer (to test the Temperature sensor).



Method 1: The "Direct Link" (Local Logging)

The simplest way to log data is to keep your Micro:bit tethered to your computer. The Micro:bit senses the environment and "talks" back to the computer through the USB cable using Serial Communication.

The Setup:

  1. Code it: In MakeCode, go to Advanced > Serial. Use the serial write value "label" = [sensor] block.

  2. Flash it: Connect your Micro:bit via USB and download the code.

  3. View it: A purple "Show Data Device" button will appear under the simulator. Click it to see a live scrolling graph of your data!

  4. Save it: Use the "Export" button in the top right to download your data as a CSV file, which can be opened in Excel or Google Sheets for analysis.



Method 2: The "Messenger" (Remote Logging)


What if you want to measure something 20 feet away from your laptop? We can use two Micro:bits: a Sender and a Receiver.

1. The Sender (The Remote "Probe")

This Micro:bit is powered by a battery pack and placed wherever the "action" is.

  • The Logic: It reads a sensor and broadcasts it over the radio.

  • Key Blocks: radio set group [number] and radio send value "name" = [value].

2. The Receiver (The Data Bridge)

This Micro:bit stays plugged into your computer via USB. It acts as a translator, listening for radio signals and passing them to the PC.

  • The Logic: "When I hear a radio message, write that value to the Serial (USB) port."

  • Key Blocks: on radio received name valueserial write value [name] = [value].



Project Spotlight: Detecting and Logging Magnetism

One of the most exciting uses for this setup is exploring invisible forces. By using the built-in magnetometer (compass sensor), you can track the strength of magnetic fields as a magnet moves closer or further away.

For a specific step-by-step on setting up this experiment, check out our deep dive: Detecting and Logging Magnetism with the Micro:bit V1.


Teacher & Parent Pro-Tip: The "CSV" Advantage

The real magic happens when students export their data. Instead of just looking at a screen, they can:

  • Calculate the Average, Min, and Max in Excel.

  • Create charts for a science event or just for interest.


Conclusion

The Micro:bit V1 may be the "older" model, but for data logging, it remains a powerhouse. By teaching kids how to move data from a sensor to a radio, then to a cable, and finally into a spreadsheet, you are teaching them the fundamentals of the Internet of Things (IoT) and data capture.


For more detailed technical steps and code snippets, visit the original guides:

 



All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Thursday, 5 March 2026

Detecting and logging magnetism with a microbit

Producing a data logger using the microbit to detect and log changes in the magnetic field.

Traces

The micro:bit includes a built-in compass that can also be used as a magnetic field detector. With a small amount of code, we can use this sensor to measure changes in the magnetic field and log the data to a computer.

If you are new to this idea, a useful introduction is the video from Mr Morrison below, which explains the basic concept.





The video demonstrates how the micro:bit can detect magnetic fields and display the readings on the device itself. Let’s extend that idea by turning the micro:bit into a data logger that continuously records magnetic field changes.


Coding and Sending data to a Computer

Instead of displaying the magnetic readings directly on the micro:bit’s LEDs, we can send the data through the USB cable to a computer.

The MakeCode editor already provides blocks that allow data to be sent using the serial connection. By placing the magnetic measurement inside a command that continuously sends serial data, we can stream the readings to the computer.

In the example code, two values are transmitted:

  • X-axis magnetic field

  • Y-axis magnetic field

These correspond to two directions in which the magnetic field can change. Each measurement is sent repeatedly through the USB cable so the computer can record it.

From a coding perspective, this modification is very simple: instead of showing the value on the device, we send it through the serial interface.


Code needed


After downloading the program to the micro:bit, keep the USB cable connected, as this is how the data is transmitted.

Once the program starts running, the MakeCode interface should display a “Show Data Device” button similar to the one shown below.

On the Computer ready for data logging


Clicking this button opens a data viewer that shows the incoming magnetic readings in real time.

Data logging in action

Example: rocking the magnets
The graph above shows data recorded when a small set of circular magnets was rolled towards the micro:bit and then allowed to rock back and forth.

The rocking motion produces a clear oscillating pattern in both the X and Y magnetic field graphs. As the magnets move, the magnetic field detected by the sensor changes direction and strength, producing the wave-like traces you can see.

It’s a simple experiment, but it demonstrates how the micro:bit can be used as a low-cost scientific data logger for investigating magnetic fields and motion.


Doing it in python!

Using the same makecode editor (the same editor as above for the blocks) click on the Python tab after code has been produced and it should now change to:

def on_forever():
    serial.write_value("x"input.magnetic_force(Dimension.X))
    serial.write_value("y"input.magnetic_force(Dimension.Y))
basic.forever(on_forever)

After it is downloaded; running it is exactly the same as running the blocks version earlier - here is an example of it in action


Running using Python



Have fun - I am :-)




All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Monday, 23 February 2026

What does Gen AI 'think' of this blog?


Ok, no surprise that I enjoy playing with Generative AI :-) A few of the recent posts are around this. Here is the question, though: what does Generative AI pick out from the blog when asked?

Using the Gemini and the following two prompts:
Prompt 1: Go to the following blog https://robotsandphysicalcomputing.blogspot.com/ read it in and summarises it as a 400 word blog post to go on the blog and urls will not count in the word limit

Prompt 2:Embed urls to make it easier for the reader to access the posts

The result

Exploring the Intersection of Code and Hardware: A Look at "Robots and Physical Computing"

Welcome to a comprehensive overview of Robots and Physical Computing, a dedicated space where the digital realm directly meets the physical world. Authored by Dr. Scott Turner, this blog operates on a delightfully simple yet profound premise: getting computers to interact with their physical environment is incredibly fun. It serves as an ongoing digital notebook that documents personal experiments, educational coding projects, and hands-on building experiences in the ever-expanding field of physical computing.

For educators, hobbyists, and STEM advocates, the blog is an absolute treasure trove of accessible, step-by-step tutorials. The core philosophy here centers on lowering the barrier to entry for coding and electronics. By heavily featuring user-friendly platforms like the micro:bit, TinkerCad, and various smart electronics kits, the blog demystifies the often-intimidating world of hardware design. Whether you are looking to integrate physical computing into a university computing curriculum or just tinkering on your workbench over the weekend, the content is consistently geared toward practical and immediate application.

A quick dive into the most recent posts perfectly highlights the blog’s dynamic range. In early 2025, the focus successfully bridged simulated environments with smart technology. For instance, a recent tutorial explores how to build a TinkerCad microbit traffic light simulator (note: exact URL path based on blog archives). This post beautifully illustrates how free, online CAD systems can be leveraged to prototype electronic circuits and test neural networks before you ever touch a physical wire. Similarly, a review of the Elecfreaks micro:bit Smart Home kit walks readers through creating a voice-activated light solution, demonstrating how simple code and accessible sensors can mimic real-world smart building technology.

Interestingly, the blog also seamlessly ventures beyond traditional hardware. A late 2024 post explores producing AI-generated cartoon strips, proving that the blog's scope continuously evolves alongside modern technology trends. Additionally, practical data applications remain a recurring theme, as seen in the detailed tutorials on setting up remote data logging systems using older V1 micro:bits and local Microbit V1 datalogging to monitor environmental conditions.

Ultimately, Robots and Physical Computing is much more than just a technical guide; it is a celebration of curiosity and maker culture. It encourages readers to pick up a microcontroller, write a few lines of block code, and watch an LED light up or a motor spin. If you are eager to bridge the gap between software and hardware, delving into this blog’s rich archives will undoubtedly spark your next great project.


Not bad as a summary! Little more gushing than I would have written.


Next task: summarise this as an image. Still using Gemini (and automatically Nano Banna) the following prompts were used
Prompt 1:Use the text produce an image that encapsulates what was summarised and make the image downloadable

Prompt 2: Compress the image so it is suited to the web and allow it to be downloaded

The result, in my opinion, was good and can be seen as the image at the top of the post.

This is just a bit of fun and normal service with Physical Computing will be resumed soon.



All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

The "Hug Avoider": A Coding Journey from Blocks to MicroPython

This project journey follows the evolution of a simple social-distancing idea into a fully realized "Hug Avoider" wearable. Writte...