Using a microbit to control a servo motor

Subtitle: Making things move a microbit at a time

In this post I explain how I set up and operated a small servo motor that runs directly from the same 2xAAA battery pack that powers my microbit. I then explain how to operate a servo motor that requires a 5V power supply from the same microbit, using a transistor as a voltage level converter for the control signal.

Introduction

I set up a small servo motor for a project to make an automated guinea pig feeder. Details on how to use this are here. Naturally, mistakes were made. I will detail the hardware setup, explain the control signals for the servo and show where the software can be found.

Hardware: SG51R servo motor

I used a Tower Pro SG51R servo motor, which runs from the same 2xAAA battery pack as the microbit. The battery pack, microbit and servo motor can be seen in the photo below. I slotted the microbit into a Kitronik edge connector.

2xAAA battery pack, microbit in a Kitronik edge connector and a SG51R servo motor

I got my SG51R servo motor from the Pi Hut here.

Why use this servo motor?

The SG51R works using a 2xAAA battery pack as the power supply, while many other servo motors require a higher voltage than 2xAAA batteries produce. This means it can run direct from the same battery pack used to power your microbit.

The manufacturer’s website says that this servo motor requires 4.8V to operate. However, it works fine with the 2.4V or so that we get from the 2xAAA rechargeable battery supply I use to power the microbit. This is great, as it means I don’t need to use a different voltage supply to power the servo motors with.

The servo has three wires for power and control. The black wire is for ground, the red wire for the voltage supply and the orange wire is the control signal.

The wires from the Kitronik edge connector to the servo motor connector can be seen in the photo below. I used D0 as the pin to output the servo motor control pulses on. The labels on the microbit are guides as how to use the microbit for the guinea pig feeder project.

The photo below shows how the wires from the microbit connect to the servo motor plug. Black is ground, red is positive voltage, yellow is the signal, from pin D0 on the microbit.

Wires from the microbit on the left, servo motor connector on the right

A servo typically responds to a control signal of a pulse between 1 ms and 2 ms long within a 20ms period. 180° needs a 1 ms pulse.

So what does that look like? The software I wrote to drive the servo motor is at the end of this article. I put an oscilloscope onto the signal pin. Here’s what it looks like:

Servo motor controller pulses

We see a positive pulse every 20 ms. Remember that these pulses go from ground to the battery voltage (about 2.4 V in this plot). We will revisit this polarity when we talk about driving a 5 V servo motor later in this post. The width of this pulse sets the angle of the servo motor. The pulse must occur within the same 20 ms window, just how much of this window it takes up changes.

From the data sheet for the SG51R:

This servo is pulse controlled. This means that supplying a pulse will move it to a particular angle. In this case 0° is a 1.5 ms pulse, 90° a 2 ms pulse and -90° is a 1ms pulse. This may not be set by your controller by default or give you the full range of movement as such you may wish to try up to 2.25 ms and as low as 0.75ms. Be aware that if you go to far you can break the servo.

Using my ‘scope, I could see that the servo motor responds to pulses with a width from 0.57 ms to 2.58 ms. Remember that the window that these pulses occur in remains as 20 ms wide. Just the width of the control pulse changes to take up more or less of this 20 ms.

Software

Initially I carefully crafted beautifully structured micropython code in classes. Then ran out of memory, so ripped out all of the classes and bludgeoned the code to fit into the memory of the microbit.

I did, of course, find example software elsewhere on the ‘net to get started and apologise that I can’t remember which site I found this on to give proper credit.

The code can be found in the file called feeder.py on my GitHub site at: https://github.com/hardwaremonkey/microbit_projects

5V servo motor MG90D

Maybe you need a more powerful servo motor for your application. In this case, you will probably need one that requires a higher voltage than we get from the battery pack for the microbit. This section explains how to control a servo motor that is running from a separate power supply using a battery-powered microbit.

The mg90d is a servo motor that requires a higher voltage than the microbit can supply to operate. I ran it at 5V from a power supply. So how do we set up our microbit to control this?

I used a 2n2222 transistor to interface the microbit with the servo motor control wire. The control signal from the microbit goes to the base of the transistor. There is a 1K Ohm current limiting resistor in between this signal from the microbit and the base of the transistor. The signal going to the base of the transistor switches the transistor on and off.

The collector of the transistor connects to the 5V power supply through a 100 Ohm resistor.

Remember: We are only using the transistor to change the voltage level of the control signal. The voltage for the servo motor comes directly from the +5V power supply.

When the control signal from the microbit goes high, the transistor turns on. When the control signal goes low, the transistor turns off.

Find the wiring diagram below. The images come from Fritzing, though I made the diagram in Inkscape.

Circuit layout showing how to power and control a 5V servo using a microbit and a 2N222 npn transistor

There is one catch with this circuit – the control signals become inverted. You might ask – why not tap the signal from the emitter of the transistor, not the collector, then the signal would not be inverted. However, doing this produces an output signal going to the servo motor of lower voltage than the signal coming into the base of the transistor. Which defeats the object. There is about a 0.6V drop between the base and emitter of a typical bipolar transistor.

The simple answer is to invert the control signal coming from the microbit. I did this. See the oscilloscope grab below, showing the inverted control signal from the microbit in yellow and the non-inverted control signal going to the servo motor in blue. Note the different voltage levels. The signal from the microbit is around 2.4 V in amplitude and the signal going to the servo is about 5 V in amplitude.

Inverted controller signal from microbit is yellow, signal from transistor emitter to servo is blue

I put the micropython code needed to generate both a non-inverted and an inverted pulse below so you can see the simple trick needed to invert the pulse.

   def set_ms_pulse(self, ms_on):
        # pin.write_analog(1023) is constant on pulse
        # (1023 * ms_on / 20) gives a pulse of length ms_on
        self.pin.write_analog(1023 * ms_on / 20)

    def set_ms_pulse_invert(self, ms_on):
        ''' Gives inverted logic servo control pulse. '''
        self.pin.write_analog(1023 - 1023 * (ms_on / 20))

This worked to operate the 5V servo motor. The transistor allows us to drive the servo motor using the output of a battery powered microbit.

Another component that allows us to drive a device requiring a voltage that is not compatible the part that generates the control signal is an opto isolator. This is a story for another day.

As always, comments are welcome.

BBC micro:bit guinea pig timed feeder instructions

This blog post is the instructions on how to use a timed servo motor circuit that I lashed up as part of a guinea pig feeder for a friend.

The hardware details can be found here: here

Software is on my GitHub site here

The need

A friend wanted something to open a box of food to feed his guinea pigs. The box needs to open after an adjustable time.

I can think of no more noble cause to focus on than feeding our furry friends.

After a period of procrastination and confusion I supplied the hardware and software detailed in this post. The mechanical components that the device will operate are up to my friend to make. He is a highly experienced mechanical engineer. I am but a lowly electronics tech.

Between the two of us, the guinea pigs will be fed!

Description

The microbit counts down for a preset amount of time. The remaining time is indicated on the LEDs on the microbit. At the end of the pre-set time, the servo motor lever moves 90 degrees. The two positions of the servo motor are shown in the pictures below.

The timer is adjusted using the A and B buttons as detailed in the Instructions section below.

Servo motor position while the timer is in operation
Servo motor position once the timer completes the countdown

Instructions for use

The A button adds 12 minutes to the timer. An extra LED will light up for each press of the button. The B button decrements 12 buttons from the timer. An LED will turn off for each press of the button. The photograph below shows two lit LEDs on the microbit, indicating 24 minutes or less are left on the timer.

The two lit LEDs indicate that 24 minutes are left until the servo motor is activated

The last timer setting is recorded to the memory on the microbit. When the board is reset, it will start counting down from this time. So, if you set the timer to 2 hours (10 LEDs lit), on resetting, you will see 10 LEDs lit up and the board will take 2 hours to trigger the servo motor.

The reset button on the back of the board restarts the board. Please see the photograph below which shows the position of this button.

Underside of the microbit with the rest button indicated, next to the battery connector

Hardware description

The components of the system are shown in the picture below. On the left is a AAA battery pack containing 2 x AAA batteries. I use battery packs with a switch, which I get from eBay. The microbit is in the centre, slotted into a kitronik microbit edge connector. This edge connector allows the signal pins of the microbit to be connected to the servo motor using female to male jumper cables . The cables are designed for the 0.1″ pins and sockets found on the edge connector and the cable connected to the servo motor.

AAA. battery pack, microbit, servo motor

The full assembly including cabling is shown in the photo below.

AAA battery pack (right), microbit and edge connector board (centre), servo motor (top), connectors (right)

A close up photo showing how the cables from the edge connector and the servo motor connector are connected is shown below. The black/brown wires are ground, the red wires are the battery voltage and the yellow wire is the PIN0 signal line.

Pins from cables connected to the Kitroniks edge connector on the left, sockets connected to the servo motor on the right

The photo below shows how the cables connect to the pins on the Kitronik edge connector.

Cables connected to the Kitronik edge connector. Yellow goes to 0, black to 0V, red to 3V.

BBC micro:bit wrist holders

With my handshake project, a microbit and AAA battery pack need to be worn on the wrist. They can be vigorously shaken. I don’t want the equipment flying off! So what can I use that will hold the microbit and batteries safely in place and is comfortable and safe to wear?

I tried a couple of armband holders aimed at iPods recently. Both of them are suitable for housing a BBC microbit and a AAA battery pack. Prior to this, I used a wrist holder that I made myself.

The advantages of repurposing an iPod arm band holder instead of making one yourself are:

  • Saves you the time of making one.
  • The clear plastic cover makes it easy to clean.

Please find photographs of the armband holders I tried out as wrist holders containing a microbit and AAA battery holder below. First a top-tip!

Velcro tabs to secure armband straps

Whichever armband you re-purpose to be a wrist holder, as the wrist is narrower than your arm, the end of the strap will no longer stick down. The end will flap free. As this end of the strap has the hook velcro on it and the rest of the strap is the loop kind, the strap will no longer stick down to itself. You need to make some double sided hook velcro tabs. See the photo below.

Double sided hook velcro tabs

These are lengths of sticky back hook velcro, stuck back to back. Place them on the loop velcro to enable the strap to stick to itself when used on the wrist.

TuneBelt Armband for iPod touch 4G

The TuneBelt iPod touch 4G armband holder can be used to hold a microbit and AAA battery pack as shown in the photo below. Use some double sided velcro hook ‘gender bender’ strips to allow the strap to stick to itself when used on the wrist.

iPod touch 4G arm band in use as a microbit and AAA battery pack wrist holder
TuneBelt iPod touch 4G used as a microbit and AAA battery pack holder, front view

arm band in use as a microbit and AAA battery pack wrist holder

TuneBelt Sport Armband iPod touch 4G box
 

igagdgitz iPod classic armband holder

Larger than the iPod touch 4G holder. Costs about twice as much – about £10 from eBay. The build uses thicker neoprene. The rear panel folds down to allow easy installation and removal of the microbit and battery holder. This is made from a decent thickness of neoprene and is held securely in place with velcro on three sides.

The strap is longer and bulkier than the iPod 4G holder . If you know you are going to use this arm band as a wrist holder, it would be worth trimming the strap down. Then you would rely on the velcro double-sided tabs to stick the strap down unless you sewed some hook velcro on to replace the tab that you had cut off when shortening the strap.

iPod classic arm band in use as a microbit and AAA battery pack wrist holder
igadgitz iPod classic holder, front view, containing BBC microbit and AAA battery holder. There are two velcro tabs near the plastic to enable the strap to latch onto itself when worn on the wrist.

 
Rear view, showing fold down flap which allows acccess to the interior

Powering the BBC micro:bit with a 5V power bank

I had an interesting question to a blog post I made about running a DC motor from a microbit. The blog post is here. I am pleased that anybody reads my blogs.

Doesn’t applying 5V to the microbit board exceed the voltage spec?

When we connect the board to our laptops or PCs, we apply 5V to the board through the USB connector. Sometimes I run the board from a USB power bank. This supplies 5V to the microbit. The advantage of using the power bank over AAA batteries is that I can use the power bank to also run e.g. a DC motor. So far I have not cooked off a microbit doing this.

But I still only measure 3.2V on the pads on the board edge connector.

Why is this?

Let’s look at the board circuit schematics. Please find a screengrab showing the USB connector on the left and the microcontroller on the microbit on the right.

BBC micro:bit schematic fragment, showing USB connector and the microcontroller.

Let’s zoom in on the connector:

Schematic showing the USB connector.

The 5V input voltage on the USB connector is given the net label VBUS_IF. This label reappears next to the little number 5 – which means this is where the track connects to on the PCB. The zener diode to the left of the number 5 and the 10 Ohm resistor R31 to the right combine to protect the board in the case of reverse polarity – if somehow the voltage is applied to the USB connector backwards, the current flows to ground, not into the microcontroller.

The capacitor C31 and C33 are there to act as little charge stores for the microcontroller for when it needs a sudden ‘oomph’ of charge that the USB power supply cannot supply quickly enough. These are called decoupling capacitors.

The +5V signal is renamed VBUS_IF_2 to the right of R31. Lets look at where this goes into the microcontroller. I labelled the net VBUS_IF_2:

So our +5V USB voltage connects to the microcontroller on a dedicated pin VREGIN. This is the input to a regulator inside of the microcontroller. The output of this regulator is a DC voltage called +3.3V_IF. This output supplies the +3.3V seen elsewhere in the board and on the board edge connector pads.

Now, if the input to VREGIN is below 3.3V, we are not going to see 3.3V on the output pads. In fact, I see 3.2V with an input of 5V, so there is a 0.1V drop somewhere on the board.

So, in summary, we can apply 5V through the USB connector.

One last schematic fragment. This shows the battery connector and where this supply connects with the voltage generated by the internal regulator on the microcontroller:

Microbit schematic showing the battery connector and how it connects to the board voltage tracks.

The battery voltage goes through a low drop BAT60A schottky diode labelled D2. This then connects to V_TGT. This is the main voltage rail for powering most of the board components, such as the magnetometer and accelerometer. This is also the rail that connects to the board edge connector on the pad labelled ‘3V’.

Both the output from the microcontroller regulator, labelled 3.3V_IF and the voltage from the battery labelled VBAT connect to this rail through BAT60A schottky diodes. The diodes mean that the battery voltage and the regulator output voltages are isolated from each other, but either can produce V_TGT.

What if both a battery and a USB connector are connected? Whichever is the higher of VBAT or 3.3V_IF, minus a small voltage drop created by the BAT60A diode, will produce V_TGT. The voltage drop across the diode is around 0.1-0.2V according to the datasheet for the BAT60A.

It would be dangerous to the board to apply 5V to the battery connector. I am not about to try this. The battery connector bypasses the regulator in the microcontroller, so applying a high voltage to this connector applies the same high voltage to the components on the microbit board, minus a small drop across the BAT60A diode. Many of these are not rated to work at 5V.

The board is designed to take 5V only through the USB connector.

Running handShake in administrator mode to operate Grid 3

Sensory Software’s Grid 3 is a popular communication software package, running in Windows. Naturally, I would like handShake to be able to operate this software through the software keystrokes that handShake generates.  To get Grid 3 to respond to a software keystroke, I have to ‘elevate’ the base.py script which runs on the communication device to run as an Administrator.

There is a second solution. I can use a Freetronics Leostick USB dongle as a pretend keyboard and have this generate keystrokes that appear as coming from a physical keyboard. I did this for a while, but this adds a layer of complexity and expense to the project. The simplest solution is to run handShake as an Administrator when using Grid 3, or other software that requires software keystrokes to come from an elevated source.

I tested out adding the functionality for handShake to detect when Grid3 was running, then automatically try to elevate the base.py script to run in Administrator mode. I got this running. Then removed the functionality. Why? Security. Software running as Administrator can damage your system if incorrectly or maliciously written.

Now handShake detects if Grid 3 is running and advises that this requires the software to be restarted as an Administrator, but does not try to automate this restart. The decision is left to the user.

The Grid 3 software is detected using the code shown below. The code looks through the titles of the windows for any that match the ones in the list called ADMIN_SOFTWARE. At the moment there is only one title to check for – ‘grid’. This is the title for a window running Grid3. As I find other packages that demand that my script runs as Administrator to have the ability to interact with it, then I will add their titles to the ADMIN_SOFTWARE list.

ADMIN_SOFTWARE = ['grid']

def target_admin_sware(software=ADMIN_SOFTWARE):
    ''' Check if target software requires this script to run as Administrator. '''
    toplist, winlist = [], []
    logging.info('Looking for software that requires elevation to Aministrator: {}'
        .format(ADMIN_SOFTWARE))
    def _enum_cb(hwnd, results):
        winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
    win32gui.EnumWindows(_enum_cb, toplist)
    for sware in software:
        # winlist is a list of tuples (window_id, window title)
        for hwnd, title in winlist:
            if sware in title.lower():
                logging.info('found software requiring Administrator mode {}'
                    .format(title))
                return True
    return False

Running handShake as Administrator is a choice that the user makes and implements if he or she deems necessary.  As all of the code is on the project GitHub site, the code can be reviewed to check that it is safe to run as an Administrator.

One of the advantages of open source projects is that they are open to this kind of scrutiny to find security flaws.

For interest, I detail the code I added and then removed from the base.py script to enable it to detect if it is running as an administrator and if not, request to be restarted as an Administrator.

I added the option to run the script as an Administrator from the command line using the click library.

click.command()

@click.option('-a', '--admin', default=False, 
    help='Run as administrator. Required for Grid 3.')

@click.option('-k', '--keystroke', default='F1',
     help='Keystroke to send. Default is F1.')

def main(admin, keystroke):
    logging.info('software keystroke is {}'.format(keystroke))
    logging.debug('admin flag is {}'.format(admin))
    if is_admin():
        logging.info('running as administrator')
    else:
        logging.info('not running as administrator')
        if admin:
            logging.info("restarting as administrator")
            elevate()
    service_microbit(keystroke) 

To test if the script is running as an administrator I added this method:

def is_admin():
    ''' Is the script running as an Administrator? '''
    try:
        return windll.shell32.IsUserAnAdmin()
    except:
        return False

Connecting the BBC micro:bit to Windows and adding code to it

This page details how to connect the BBC micro:bit to Windows then install a pre-written program to it. This guide was written to support some of my ‘how-to’ guides for assistive technology devices I made using the BBC micro:bit.

Author: Matthew Oppenheim

email: matt.oppenheim@gmail.com

GitHub site: https://github.com/hardwaremonkey

Summary

Connect the microbit using a micro USB cable from the microbit to the Windows device. You do not need a battery pack for the microbit. The microbit is powered from the USB connection.

  • Install the driver for the microbit if you are not using Windows 10.
  • Connect the microbit using a USB cable to the device with the communication software on it.

To install software, drag and drop the file, which ends with .hex, into the MICROBIT folder.

Connecting a microbit to a Windows machine

Connect your microbit to your Windows machine using a USB cable.

BBC microbit board connected using a micro USB cable to the Windows device. A battery pack is not needed.

Windows 10 should automatically detect the microbit. If you are using an earlier version of Windows, you will need to install the driver for the microbit.

If File Explorer shows that the microbit is attached, you are done. Success. The screenshot of File Explorer below shows that the microbit is connected as a drive called ‘MICROBIT’. A new microbit has a demo program installed which will scroll all kinds of things across the LEDs.

If the microbit does not automatically connect, download and run the microbit driver installer.

microbit showing as successfully connected in File Explorer.

How to install the microbit driver if the microbit is not detected

Windows 10 should recognise the microbit, but in testing, this was not found to always be the case. The driver can be manually installed using the instructions in this section.

I found that Windows 7 would find and download the driver for the microbit on its own when left for about 5 minutes. The microbit needs to be connected with the USB cable first.

If for any reason the driver is not found and installed by Windows automatically, then the driver can be downloaded and installed manually.

The name of the driver installation file is:

mbedWinSerial_16466.exe

A newer version may be available.

Get this file by clicking on the ‘Download current driver’ link on this page: https://os.mbed.com/handbook/Windows-serial-configuration

The microbit needs to be plugged in before the serial driver installer is run.

Follow the instructions on the webpage to install the driver. Once installed, the microbit should show up as a connected drive, as shown in the screenshot above.

Installing code on to the micro:bit

The micro:bit is programmed by placing .hex files onto it. This can be done by dragging and dropping these files onto the MICROBIT folder from File Explorer. For instance, if you are trying to install a file called ubit_flash.hex, the file called ubit_flash.hex needs to be dragged and dropped into the MICROBIT folder as shown in the screenshot below.

Drag and drop the file ubit_flash.hex to the MICROBIT folder.

Wait about 10 seconds for the microbit to start to program. The light on the back of the microbit will then flash for about 10 seconds as it loads the new program.

The code will remain stored on the microbit and run whenever it is powered. The microbit can be left unpowered and the code will stay on the device for when you next connect it to the Windows device.

As the microbits are being distributed to all 11-12 year-olds in the UK, if you get stuck installing code on to the microbit and live in the UK, find a friendly 11-12 year-old to help you out.

Problems

Microbit is connected, but the software tells you that no microbit is found

If a microbit is plugged in and you still get the message that there is no microbit connected, then the microbit driver is not installed. Look at ‘Installing the microbit driver’.

Switching a 5V DC motor with a microbit.

This post shows how to use a BBC microbit to control a 5V fan or DC motor using a FET switch. The circuit shows how we can use a transistor to control a device that needs more current than the microbit can supply.

This project uses a 5V voltage from a USB power bank.

Only connect 5V to the USB connector on the microbit – not the battery connector or the edge connector.

A demo showcasing the microbit’s sensor technologies was set up in the office I’m lucky enough to loiter in when not working offshore. One of the demos showed how the microbit can detect temperature. When the microbit is heated up above a certain temperature with a hairdryer, the microbit turns on a  fan to cool itself down. The fan is turned off the fan when the microbit detects that the temperature has fallen below a pre-set threshold. I don’t have much use for a hairdryer nowadays (baldy matt), but I lashed up a little circuit to enable a fan to turn on when a pin on the microbit goes high. I passed this over to the rest of the team who were setting up the demo to add the temperature sensing code.

The problem is that the fan operates at 5V and needs a fair whack of current compared with what we can squeeze out of a microbit pin. The microbit operates from a 3V battery pack. So how do we use the microbit to turn on a device that operates at 5V and enable enough current for the fan?

Short answer, we use a transistor switch and a 5V USB power bank. In this case, I used an N-channel FET, specifically a 2N7000. There are other types of transistor that can be used and different arrangements of circuitry, but this is one of the simplest and most reliable setups for this example.

As we are using a 5V power bank for the fan, we can use the same 5V power bank to connect with the micro USB connector on the microbit. I am using a 5V USB power bank.

Only connect 5V to the USB connector on the microbit – not the battery connector or the edge connector.

I created a blog post about how the microbit is powered from the USB port and battery packs here.

We could use independent 5V and 3V battery packs, so long as the grounds on the battery packs are connected. Being able to have separate battery packs for the microcontroller and the device being powered is an important idea which allows us to switch e.g. 12V devices using the microbit, where you couldn’t share the same power supply between the microbit and the device. The device being powered is often called a ‘load’, as it loads the power supply.

BBC micro:bit using a FET to control a fan motor.

A drawing of the circuit can be seen above. I used Fritzing and Inkscape to draw this. The three pins of the transistor are called ‘source’, ‘gate’ and ‘drain’. The source and drain are named as they are the source and drain for the charge carriers inside the transistor that allow the current – in this case electrons. The gate, is well, a gate, that enables a current through the transistor when it is held at a higher voltage than the drain

The source of the transistor is connected to the negative of the battery pack, as this supplies the electrons that are the charge carrier in this type of transistor. This negative pin on the battery pack is also connected to the ground of the microbit through the USB connector. The drain on the transistor is connected to the negative pin on the DC motor. The positive pin of the motor is connected to the positive pin on the battery. The positive pin on the battery is also connected to the microbit through the USB connector, as the battery pack supplies +5V, which is the same as USB supplies.

Here’s a photo of the device in real life. The blue oblong is a 5V rechargeable USB power pack. The fan is on in the photo. The transistor can be seen as the tiny black think on the breadboard. A green clip connects pad 0 on the microbit to the gate of the transistor. The wiring connecting all the pins between the USB connectors is hidden underneath the connectors as about the only area I am in any way tidy is with wiring.

So how does this the transistor switch work? Many people better than myself have written on this. I’d recommend having a play on the excellent Falstad circuit simulator. Go to ‘circuits’ ‘MOSFETS’ ‘switch’ and click on the little open switch symbol to close it. Watch the flow of charge (the current). I modified and labelled the example circuit to show how the microbit circuit is laid out and put a screen grab below. In the Falstad simulation, the switch connects to the gate pin on the FET to a 3V power rail. This represents pin 0 on the microbit. Pin 0 going high is simulated by closing the switch and connecting the gate of the FET to 3V. Pin 0 going low is simulated by opening the switch and having the gate of the FET go to 0V.

When the gate is connected high, the FET switch is on and allows a current from the drain to the source. When it is not high, the FET will not allow charge to flow. The 5 Ohm resistor represents the load on the circuit, in my case the fan. I don’t know what the resistance of the fan is, but 5 Ohm is good enough for the simulation.

The battery pack is simulated by the +5V power rail which connects to the positive side of the 5 Ohm resistor. So, using a switch from a lower voltage rail, we can control the current supplied by a higher voltage supply. This idea is used in industrial controllers to allow little microcontrollers to operate machinery that runs at a far higher voltage than the microcontroller and used far more current than a microcontroller can supply from its output pins. I put the Falstad code at the bottom of this page. You can copy and paste it into Falstad. Go to ‘File’ ‘Import from text’ and paste in the code.

Falstad simulator FET switch layout.

The +ve on the fan motor is connected to the battery pack’s +ve rail. The -ve on the fan motor is connected to the drain on the FET. When a high voltage is applied to the gate on the FET (3V from the microbit pad 0), the semiconductors inside the FET are put in a state that allows a current through the drain to the source. As the source is connected to ground, there is now a current from the battery through the fan and to ground. So with the gate voltage high, the circuit is complete and the fan can operate. When the gate voltage is not high (pulled to ground by pad 0 on the microbit), the FET’s semiconductors are in a state that will not allow a current through the FET and the fan, so the fan does not operate.

I wrote some micropython code to test it all out. Please find this below. Button A toggles pad 0 on the edge connector high and low. Note that when the microbit is powered on, I set the pad to a known state, in this case low. You should always configure the state of pins that are being used to control devices to a known state at power up. Sometimes when you start up a microcontroller, the pins will go to a state you didn’t anticipate whatever the data sheet says, which could cause whatever you are controlling to turn on or off when you didn’t expect it to. How do you think I found this out?

Here’s the micropython code I used to test the circuit with.

''' Toggle pin0 on button A press. '''

from microbit import *

TOGGLE = False


def display_leds(toggle_flag):
    if toggle_flag:
        display.show(Image.TARGET)
    else:
        display.show(Image.ASLEEP)


def setup():
    write_pin0(0)
    display.show(Image.ASLEEP)



def write_pin0(toggle_flag):
    if toggle_flag:
        pin0.write_digital(1)
    else:
        pin0.write_digital(0)

setup()
while True:
    if button_a.was_pressed():
        TOGGLE = not TOGGLE
        write_pin0(TOGGLE)
        display_leds(TOGGLE)

Here’s the Falstad simulator code. Copy and paste it into the box you get when you click on ‘File’ ‘Import from text’ in Falstad.

$ 1 0.000005 10.634267539816555 50 5 50
s 288 224 288 304 0 0 false
w 288 128 400 128 0
r 400 128 400 288 0 5
w 400 320 400 336 0
f 288 304 400 304 0 1.5 0.02
R 288 128 240 128 0 0 40 5 0 0 0.5
g 400 336 400 352 0
x 432 213 465 216 4 24 fan
x 416 310 534 313 4 24 2n700\sFET
x 139 195 281 198 4 24 microbit\spin\s0
x -7 284 267 287 4 24 switch\sclosed\s\q\spin\s0\shigh
x -6 258 242 261 4 24 switch\sopen\s\q\spin\s0\slow
x 121 112 251 115 4 24 battery\spack
R 272 208 224 208 0 0 40 3 0 0 0.5
w 272 208 288 208 0
w 288 208 288 224 0

Real time accelerometer display from three BBC Micro:bits

How to plot real-time sensor data from three BBC Micro:bits.

Please find a video showing this in action below. On the screen to the right of the juggling clown, you can see the accelerometer data. Each BBC Micro:bit has a three-axis accelerometer in it. I get the averaged acceleration value from all three axes from each Micro:bit. On the screen, three are three traces, one for each Micro:bit. As the boards are juggled, the accelerometer values are sent by radio to a receiver Micro:bit connected to the computer. This Micro:bit acts as a bridge between the juggled Micro:bits and the computer. The accelerometer data is plotted real time using a Python script, using the pyqtgraph library.

Using udev to remove the need for sudo with the BBC Micro:bit

A comment on this post hinted that there is a way to remove the need to use ‘sudo’ when interacting with the BBC Micro:bit on Linux. So I left a comment asking how to do this, which the author kindly answered:

The way to make sure there is no need for root permissions to access USB device (like connected MicroBit) is by creating a file into `/etc/udev/rules.d/` directory with proper config. For Microbit this could be like this:

SUBSYSTEM=="usb", ATTR{idVendor}=="0d28", ATTR{idProduct}=="0204", MODE="0666"
and then restarting udev system with:
sudo udevadm control --reload-rules

So I created the file /etc/udev/rules.d/microbit.rules with the above code and it works!

I fired up pyocd to enable command line programming of the BBC Micro:bit without needing to use sudo. See this page for more details on programming the BBC Micro:bit from the command line and using pyocd to help with this.