Skip to content

Using micro:bit with Matlab and Simulink

Daniel Gallichan edited this page Feb 23, 2023 · 6 revisions

Using USB serial communication from Matlab to pass on to the microbit

This is the best method I've found so far to easily allow Matlab to 'talk' to a remote microbit - you can have a local microbit connected via USB which Matlab can communicate with over the serial connection, and then this local microbit can use the microbit radio to talk to the remote one. I used this to pass on basic radio control via Matlab of the bitbot:

It is worth noting that when using the serial communication method, it can be difficult to identify which 'COM' port (on Windows) or 'usbmodem' folder (on Mac) the microbit is actually using. The 'serialRadioControl.m' example above contains code which asks the user to unplug and re-plug their microbit - and rechecks the list of connections to work out which one the microbit must be. This seems to work well on Windows, but I haven't had the chance to test it on a Mac yet.

Using USB serial communication to log data from the micro:bit

MATLAB isn't really optimised for 'real-time' processing - but nowadays on a normal computer it can keep up with data rates via serial that are quite reasonable (maybe around 50Hz for 3 parameters) - but the live data plotting might start to get laggy. You can test this yourself with a microbit by using:

Using with Simulink

If you want to use the Microbit with Simulink, you need to install the Simulink Coder support package for Microbit (which also requires: Simulink, Simulink Coder, Matlab Coder). This package also includes a 'microbit' Matlab object, which can be useful for communicating directly with a connected microbit from within Matlab - but that can also be achieved directly using USB-serial commands if preferred.

Using the 'microbit' MATLAB object

With the Simulink support package installed, you should also be able to connect to a USB-connected microbit by typing simply

m = microbit

in the Matlab command window. The functions you then have available are:

  • clearLED
  • configurePin
  • device
  • read
  • readAcceleration
  • readDigitalPin
  • readMagneticField
  • readVoltage
  • scanI2CBus
  • showPins
  • writeDigitalPin
  • writeLED
  • writePWMDutyCycle
  • writePWMVoltage

It is worth noting that 'radio' (and/or bluetooth) features are currently (R2021a) missing from this list - meaning that this method doesn't allow easy remote communication with other microbits.

This page still needs completing with more info on Matlab and Simulink!