Programming M.A.R.S. Rover in Microsoft Makecode

Makecode for 4tronix M.A.R.S. Rover

Installing the Extension

In the Makecode editor, select “Advanced” and then “Extensions”. Alternatively click on the gear icon and select “Extensions” from there

Then enter in the search bar: https://github.com/4tronix/MARS-Rover

Click on the extension and it will be loaded into your Makecode editor. You will now have a rocket ship icon, Rover, with several sub-sections

Calibrating the Servos

Before we start using the Rover we should calibrate the servos so that they run directly.

Load this project into your Makecode editor: https://makecode.microbit.org/_Mpt6xpCRF0EK by selecting “Import”, then “Import URL”

Alternatively, download it from https://4tronix.co.uk/rover/microbit-CalibrateServos.hex

This program goes round all the wheel servos and allows you to use the A and B buttons on the Microbit to set each servo to straight ahead position.

It indicates using the LEDs which servo is being calibrated.

When you are happy with each servo, press the A+B buttons together to store the setting and move onto the next servo. After setting all servos, simply switch off and start coding.

 

 

Drive:Bit Super Affordable Motor Controller for Microbit

Drive:Bit Motor Controller

Purchase Drive:Bit here

Drive:Bit has been created to provide a really affordable motor and robotics controller board for the BBC micro:bit. Even though we reduced the price as much as we could, we kept some great features which will make it an excellent board to build DIY buggies and the like

Connections

NB: Fit the Microbit into the connector with the LEDs on the Microbit facing the switch and indicator LED.

Connect your batteries to the 2-pin screw terminal, or the 2-pin header pins, on the left. The battery voltage should be in the range 6V to 10V, so use 4 x AA alkaline cells, or a 9V PP3 battery or similar. This input voltage is what is used to drive the motors and generate the 3.3V for the Microbit, so make sure that your motors can cope with the voltage you provide and that the voltage is kept high enough when the motors take a lot of current.

Connect your motors to the 2-pin screw terminals (or 2-pin male headers). Motor 1 is on the left, labelled M1. Motor 2 is on the right, labelled M2. The current to the motors is limited by the circuitry so it won’t damage the DriveBit if you try and take too much current. However, if things aren’t working, switch off and check for short circuits. Better safe than sorry!

In the centre of the DriveBit is a group of pins, 4 x 3. These are GVS (Ground, Voltage, Signal) pins that allow you to connect 3.3V devices (inputs or outputs) directly to the Microbit pins 0, 1, 2 and 8. Small, micro, servos such as SG90 can be plugged in directly – although they are 5V devices they will generally work at 3.3V.

Other pins are available on the top of the board as pads. You will have to solder wires in there, or you could add a (male or female) header yourself.

Programming Drive:Bit with Makecode

There is a Makecode extension available which makes it trivial to control the motors or set the LED to any colour or flashing and colour. The 4 GVS pins are general purpose so use other Makecode libraries to drive what you connect to these pins.

In Makecode editor go to Advanced and Extensions, then search for DriveBit

Driving Motors:

Setting the Status LED

 

Using Drive:Bit with MicroPython

For micro Python, you can drive the motors and the onboard status LED very simply. The pins used are:
Motor 1: Pin 12 and Pin 13
Motor 2: Pin 14 and Pin 15
LED: Pin 16

To drive forward, Set Pin 12 and Pin 14 to the speed you want, from 0 to 1023. And set Pin 13 and Pin 15 to 0. Eg. to drive at speed 600

pin12.write_analog (600)
pin13.write_analog (0)
pin14.write_analog (600)
pin15.write_analog (0)

To drive backwards, set Pin 12 and Pin 14 to zero, and set Pin 13 and Pin 15 to the speed you want, from 0 to 1023. eg to reverse at speed 600

pin12.write_analog (0)
pin13.write_analog (600)
pin14.write_analog (0)
pin15.write_analog (600)

To stop the motors, set both pins of each motor to 0. This will coast to a stop

pin12.write_analog (0)
pin13.write_analog (0)
pin14.write_analog (0)
pin15.write_analog (0)

To brake the motors quickly, set both to 1023

pin12.write_analog (1023)
pin13.write_analog (1023)
pin14.write_analog (1023)
pin15.write_analog (1023)

To drive the LED, you will need to import and use the neopixel library. This example sets the LED to Red

import neopixel
np = neopixel.NeoPixel(pin16, 1)
np[0] = (255, 0, 0)
np.show()

  • Line 1 imports the neopixel library
  • Line 2 sets up the array of LEDs that the library will use. We only have 1 LED
  • Line 3 sets element 0 (our only LED) to Red=255, Green=0, Blue=0
  • Line 4 copies the array of LED data to the LED itself

 

M.A.R.S. Rover Assembly

Assembly of 4tronix M.A.R.S. Rover Kit

Click on any photo to enlarge

The 4tronix Mars Rover is loosely based on the Curiosity and Mars 2020 rovers from NASA. It uses the same rocker arm, bogey and differential arm mechanism.

Purchase M.A.R.S. Rover from here

Coding for the M.A.R.S. Rover here

Some stats on the 4tronix Mars Rover

  • 6 Motors. 80 rpm 6V, N20 micro gear motors
  • 4 Servos. MG90S metal gear analog micro servos
  • Total number of special PCBs: 30
  • Number of different PCB designs: 11
  • Length: 200mm
  • Width: 185mm
  • Height without Mast and Microbit: 95mm
  • Height with Mast: 170mm

Kit Contents

The kit is packed in 10 bags, which should be assembled in order as follows

  1. Side pack. PCBs and screws to assemble both side pieces of the main body
  2. Brains (Top) Pack. This PCB houses all the electronics and together with the side pieces (1) forms the structural body of the 4tronix Mars Rover
  3. Rocker Pack. These 2 rocker arms are pivoted on the screws fitted into each side piece. Each rocker arm carries a single servo for a front corner wheel assembly
  4. Bogey Pack. These two rear bogeys carry the centre and rear wheels for each side. The rear corner wheels are steered with a servo
  5. Servo Pack. This contains 4 metal gear micro servos together with screws to fix them into the Rockers and Bogeys
  6. Differential Arm Pack: The differential arm and couplers joins the two Rockers in such a way that it tries to keep the main body level (side to side) as one side or the other traverses uneven terrain. In earlier NASA Mars Rovers, this arm was replaced by a differential gear train, but the arm was found to be simpler and less prone to failures.
  7. Corner Wheels Pack. Each corner wheel is steered by its own servo. This pack contains the PCBs and screws needed to connect all four of the motor mounts to the servos
  8. Motors Pack. This includes the 6 motors, each ready-wired with a JST connector lead which plugs into the underneath of the main brains board. Plastic mounting brackets and associated screws are also included
  9. Wheels Pack: Six wheels. Just push them onto the motors. You must enusre that the D-shaped axle is aligned with the D-shaped hole in the wheel
  10. Mast Pack. Includes another servo, the mast base and a plug-in mast head with an ultrasonic sensor and some LEDs.

Assembly

Step 0

Check you have all the bags described above. There is also a spares bag, a spare servo, a screwdriver and a wrench. The screwdriver has both a flat blade and a philips blade end. Pull out the metal part and insert it the other way round to change ends.

Step 1: Assemble the Sides

You should have two sides pieces (left and right), four aluminium brackets, eight 8mm M3 screws and two long 16mm M3 screws. Photo above shows 2 brackets fitted and two brackets ready to fit.

Screw the brackets into the side pieces from the inside as shown above. Make sure that the vertical screw holes in each brackets are next to the top surface of each side.

Then screw the long screw from the inside, through the PCB and through the fitted nut. .Make sure all screws are tight as once it is assembled it will be very hard to get at them again

Step 2: Fit the Brains/Top to the Sides

You should have the Brains PCB and eight M3, 6mm screws

The sides should be fitted as shown above with the rocker mounting screw nearest the front (the end with the servo hole in the top/brains PCB)

Step 3: Fit the Rocker Arms

You should have two rocker arms (left and right) with servo mounts fitted, two M3 nyloc nuts and 4 M3 washers

Place a washer onto the rocker pivot screw, then place the rocker arm, then a second washer and finally the M3 nyloc nut. Tighten up the nut as far as it will go, then back it off the tiniest bit until the arm moves freely. If you loosen the nut too much the arm will wobble, so get it as tight as possible without binding.

The servo carrier on each side is at the front of the rover, facing outwards as shown above.

Step 4: Fit the Bogeys

You have two bogeys (left and right) with servo and motor carriers attached, two M3, 10mm screws, 4 washers and two nyloc nuts.

Fit the screw from the inside, through the rocker arm, then a washer, then the bogey, then a second washer and finally the nyloc nut. As with the rocker arms, do the nyloc nut up tightly then back it off slightly so the bogey moves freely.

The bogeys also have the servo carriers facing outwards in each rear corner of the rover.

Step 5: Fit the Steering Servos

You have four servos and eight 6mm, M2.5 screws.

Mount each servo with the output shaft nearest the centre of the rover as shown above. Screw from underneath the servo mounting PCB into the holes on the side of each servo, as shown below. Keep hold of the servo arms and servo shaft screws, ready for Step 7.

Step 6: Fit the Differential Arm

You should have the differential arm PCB, a long screw, 2 washers and a nyloc nut and 2 push-rods with 4 screw on snap links.

Screw the long screw from underneath, through the main board and into the fitted nut. Do up tightly.

Place a washer over the long screw and onto the fitted nut, then the differential arm, then the second washer and finally the nyloc nut. As with the rocker arms and bogeys, do up the nyloc nut tightly then slacken it off slightly

Finally adjust the pushrods and snap links by screwing in and out until the distance between the clip points is about 53mm. Then clip firmly into the top of each rocker arm and the ends of the differential arm.

When you have fitted the wheels (later) you can adjust the length of the pushrods to ensure that the body of the Rover sits level.

Step 7: Fit the Corner Wheel Mountings

You should have four top pieces with 4mm nuts attached and eight 6mm black screws.

Also included is the Zero Servo – a little magic PCB that centres your servos without hassle.

You will also need the four cross-shaped servo arms and servo shaft screws from the servo packs. Do not use the longer screws in the servo packs. If the soldered nuts still have the orange kaptan tape on, you will need to peel it off.

Fit the cross-shaped  servo arms to the top pieces with the nuts attached. The arms fit on the opposite side to the nuts and with the hole that accepts the servo shaft facing outwards. Note that the arms are not symmetrical – so the holes will only line  up properly one way round – the longer end goes towards the straight edge of the mounting PCB. You can use a pair of side-cutters (or nail clips?) to chop off the protruding ends of the servo arms.

IMPORTANT: it is important that the motors are mounted so they are pointing outwards at as close to 90 degrees as possible when the servos are set to 0 degrees. Use a ServoZero (included) connected to power by a USB cable and plug each servo in turn into it to set to the zero position. We can fine tune the position later in software, but it is important to get it close mechanically.

Use the little servo shaft screws from the servo packs to fit each motor mounting securely.

Step 8: Fit the Motors

You should have 6 motors with JST leads attached, 6 mounting brackets, 20 M2 screws and 12 M2 nuts. You will also have the 4 lower motor mount PCBs

Mount the centre motors by fitting the nuts into the plastic brackets, then screwing through from underneath into the nuts. See photo above.

The corner motors are mounted by first fitting them to the lower motor PCBs from Pack 7 using 2 screws and 2 nuts for each.

Then screw the resulting assembly onto the 2 fitted 4mm nuts on the PCBs you assembled in step 7.

With all six motors fitted, attach the JST leads to the connectors underneath the main board. It doesn’t matter which connector you use as long as the left side connects to left motors and the right side connects to right motors.

You can use this opportunity to connect all the servo leads as well. These need to be connected to the servo connector nearest to them. So use 9, 11, 13 and 15.

You can wrap the spare lead around the servos to tidy the cables up a little. An alternative method that I use is to put the cables down the side of the battery holders underneath and hold them in with a peice of foam cut from the packing in the box.

Step 9: Fit the Wheels

The six wheels simply push on, but be careful to line up the D-shaped hole in the wheels with the D-shaped axle. Only push the wheel when holding the motor, not when hold the body.

It looks better (I think) if the wheels are on “backwards” with the spokes showing

Step 10: Fit the Mast

The mast houses an ultrasonic distance sensor and 2 White LEDs (not controllable). It is fitted onto a steerable servo and can be removed simply by unplugging it.

This pack contains the servo, the mast base PCB, the mast head PCB, two M2.5 screws to secure the servo and 4 short self-tapping screws to secure the servo horn to the mast base

Fit the servo by screwing the M2.5 screws through the top PCB into the holes on the side of the servo. Connect the servo lead to position SV0 underneath.

Fit the cross-shaped servo horn from the servo bag to the bottom of the mast base PCB using the 4 small self tapping screws.

Fit it so that the connector is pointing forwards when the servo is at its centre position. Use the small shaft mounting screw in the servo bag to fix it firmly to the top of the servo shaft.

Then plug in the mast head and plug the 3-wire lead from the mast base to position P13 on the top of the main board. Ensure the Brown wire is next to G on both boards.

Complete!

Now for some coding using Microsoft Makecode:

Makecode extension is from https://github.com/4tronix/MARS-Rover

In Makecode, click on Advanced, then Extensions. Enter the URL above into the search bar.

 

Pi2Go Mk2 Programming

Programming the Pi2Go Mk 2

Preparing your Raspberry Pi

Before you can install the Pi2Go Mk 2 software, you will need to ensure that your Raspberry Pi is up and running and connected to the internet. You will need to be able to see the desktop or console (either using direct connections, or SSH or VNS over the network).

Setting up a Raspberry Pi is not covered here. It is best to get the information from the source at Raspberry Pi

You will also need to enable SPI and I2C. Do this from raspi-config

sudo raspi-config

Select interfaces and enable both SPI and I2C. Then reboot.

Installing the Pi2Go Mk2 Software

First you will need to prepare your Pi for the Smart RGB LEDs (fully compatible with neopixels). The best way we’ve found to do this is run Pimoroni’s curl script.
With your Pi connected to the internet, run (you don’t need to install the resources and examples):

curl -sS https://get.pimoroni.com/unicornhat | bash

Download the Python library module and example software for Pi2Go Mk2 with

wget https://4tronix.co.uk/pi2go2.sh -O pi2go2.sh

bash pi2go2.sh

This installs the following:

  • ipd.desktop in home/pi/.config/autostart which will start the IP Display on boot. This will silently fail if the optional IP Display is not plugged into either port.
  • Creates a folder home/pi/pi2go2 for all the example files and library module pi2go2.py (the main library module)
  • motorTest.py to demonstrate driving the motors. Must be run in a terminal, not from an IDE like Idle or Thonny. Use LXTerminal for this
  • stepTest.py to demonstrate running motors controlled by the wheel sensors. Must be run in a terminal, not from an IDE like Idle or Thonny. Use LXTerminal for this
  • adc.py shows the light sensor values and raw battery voltage
  • ledTest.py flashes all LEDs through Red, Green, Blue and White. This must be run using sudo. ie: sudo python3 ledTest.py
  • rainbow.py sets the LEDs to rainbow colours (static, but flashes every 10 seconds). This must be run using sudo. ie: sudo python3 rainbow.py
  • lineTest.py shows the value of the line sensors
  • lineFollower.py is very basic line follower program
  • sonarTest.py shows the distance in cm for an obstacle using the optional ultrasonic breakout in either or both expansion slots
  • ipd03.py this is the program run on boot up to display the IP address of the Pi to make it easy to connect to using VNC or SSH

Using the Pi2go2.py Library Module

To use this module, you must first import it into your program using

import pi2go2

Then, before using any other functions you should call the init ( ) function to initialise all the variables used by the library. The init ( ) function has an optional parameter which is the default brightness of the LEDs. If omitted, this defaults to 40. So the following call will initialise the library and set the default brightness to 100:

pi2go2.init (100)

Hot Tip:
As a special case, if you set the brightness to zero, then the LEDs are not initialised. As this would require use of the sudo command, it can be beneficial to call init (0) so that your program can be run without using sudo.

When your program has finished, it is good practice to close down everything tidily by calling:

pi2go2.cleanup ( )

Motor Functions

  • stop ( ): Stops both motors – coast slowly to a halt
  • brake ( ): Stops both motors – brakes quickly
  • forward (speed): Sets both motors to move forward at speed. 0 <= speed <= 100
  • reverse (speed): Sets both motors to reverse at speed. 0 <= speed <= 100
  • spinLeft (speed): Sets motors to turn opposite directions at speed. 0 <= speed <= 100
  • spinRight (speed): Sets motors to turn opposite directions at speed. 0 <= speed <= 100
  • turnForward (leftSpeed, rightSpeed): Moves forwards in an arc by setting different speeds. 0 <= leftSpeed,rightSpeed <= 100
  • turnreverse (leftSpeed, rightSpeed): Moves backwards in an arc by setting different speeds. 0 <= leftSpeed,rightSpeed <= 100

 

Wheel Sensor Functions

  • stepForward (speed, steps): Moves forwards specified number of steps, then stops
  • stepReverse (speed, steps): Reverses specified number of steps, then stops
  • stepSpinL (speed, steps): Spins left specified number of steps, then stops
  • stepSpinR (speed, steps): Spins right specified number of steps, then stops

 

RGB LED Functions

  • setColor (color): Sets all LEDs to color – requires show()
  • setPixel (ID, color): Sets pixel ID to color – requires show()
  • show ( ): Updates the LEDs with state of LED array
  • clear ( ): Clears all LEDs to off – requires show()
  • rainbow ( ): Sets the LEDs to rainbow colors – requires show()
  • fromRGB (red, green, blue): Creates a color value from R, G and B values
  • toRGB (color): Converts a color value to separate R, G and B
  • wheel (pos): Generates rainbow colors across 0-255 positions

IR Sensor Functions

  • irLeft ( ): Returns state of Left IR Obstacle sensor
  • irRight ( ): Returns state of Right IR Obstacle sensor
  • irAll ( ): Returns true if either of the Obstacle sensors are triggered
  • irLeftLine ( ): Returns state of Left IR Line sensor
  • irRightLine ( ): Returns state of Right IR Line sensor

UltraSonic Function

  • getDistance (sonar = 0). Returns the distance in cm to the nearest reflecting object. 0 == no object. Sonar 0 is the front connector, Sonar=1 is the side connector. If you don’t include the parameter it defaults to 0 (front)

    Analog and Light Sensor Functions

  • getLight (Sensor). Returns the value 0..1023 for the selected sensor, 0 <= Sensor <= 3
  • getLightFL ( ). Returns the value 0..1023 for Front-Left light sensor
  • getLightFR ( ). Returns the value 0..1023 for Front-Right light sensor
  • getLightBL ( ). Returns the value 0..1023 for Back-Left light sensor
  • getLightBR ( ). Returns the value 0..1023 for Back-Right light sensor
  • getBattery ( ). Returns the voltage of the battery pack (>7.2V is good, less is bad)

    Switch Function

  • getSwitch ( ). Returns the value of the tact switch: True == pressed

Pi2Go Mk 2 Home Page

Links

Overview

The Pi2Go Mk2 is the evolution of the very popular original Pi2Go, first shipped in April 2015. The major changes are:

  • Improved assembly method, particularly the motor mounts
  • No wires for attaching the battery packs
  • Better quality wheels with high grip tyres
  • Wheel sensors built into both wheels
  • Programmatic access to the raw battery voltage
  • Improved analog light sensors – one in each corner
  • 10 individually addressable Smart RGB LEDs
  • 2 edge connectors compatible with Pimoroni’s Breakout Garden with full access to I2C signals and individual GPIO signals
  • Improved motor controller allowing higher speeds and optional braking on stop
  • Now with 4WD option

 

Specification

  • Requires 6 x AA rechargeable battery cells (not included)
  • Supports all versions of 40-pin Raspberry Pi
    (NB. the Raspberry Pi 4 consumes a lot of power and it is recommended to use one of the optional 7 x AA, or 2 x 18650 battery boards)
  • Motor controller: DRV8833
  • Analog input (light sensors and battery) MCP3008
  • Switching 5V power supply using TPS5430
  • 10 x SK6812-3535 Smart RGB LEDs (compatible with neopixels) – on battery board
  • On/Off switch with Blue indicator LED – on battery board
  • 2 x TCRT5000 infra-red obstacle sensors (front corners)
  • 4 x SFH3710 light sensors (all 4 corners)
  • 2 x TCRT5000 infra-red line follower sensors
  • 6mm tact switch for programmatic use
  • 4 x servo connections – direct from GPIO pins, with 5V and Gnd signals
  • 2 x optical wheel sensors with 20 slot encoder wheels (ie. 20 pulses per revolution)
  • 2 slots for breakout boards, including ultrasonic distance sensor and IP Display. These slots are compatible with Pimoroni’s Breakout Garden range.
  • Overall size with wheels attached: 148 x 118 x 98mm (length x width x height)
  • Weight (excluding Raspberry Pi & batteries): 282g

 

GPIO Connections

(Broadcom numbering)

  • Left Motor: 26, 19
  • Right Motor: 21, 16
  • Smart RGB LEDs: 18
  • Left Obstacle Sensor: 22
  • Right Obstacle Sensor: 17
  • Left Line Sensor: 23
  • Right Line Sensor: 27
  • Front ultrasonic (or general I/O): 20
  • Side ultrasonic (or general I/O): 4
  • Tact switch: 15
  • Left wheel sensor: 5
  • Right wheel sensor: 6
  • Servos: 12, 13, 24, 25

 

MiniBit

MiniBit Entry-Level Robot for Microbit

Purchase here

Overview

MiniBit is a ready-assembled simple and inexpensive robot for the BBC micro:bit.

It has the following features:

  • Ready-assembled*. Just push on the wheels
  • Edge connector to easily insert the Microbit
  • Micro metal gear motors with fully-enclosed gearbox (no grit or fluff can enter)
  • Wire-free battery holder for 3 x AA batteries
  • 4 x Smart RGB LEDs (neopixel compatible)
  • Integrated Pen holder for 10mm diameter pens (eg. Sharpie felt tips)
  • Robust On/Off switch with Blue indicator LED
  • Wide chunky wheels with lots of grip
  • Metal ball front caster
  • Connector for optional ultrasonic sensor or I2C breakouts (fully compatible with Pimoroni’s Breakout Garden range)
  • The Microbit pins 0, 1, 2, Gnd and 3V are available for use with croc clips etc.
  • Lots of mounting holes to create your own “body” for the robot or additional sensors etc.
  • Makecode extension and micropython examples available

* Wheels need pushing on and optional pen-holder needs screwing in if purchased

Assembly Instructions

  1. Push on the wheels
  2. If you have the pen holder, then use 2 screws to screw the two pillars into the main board from the bottom, then use the remaining 2 screws to screw the top holder into the pillars
  3. Please use Alkaline batteries. Rechargeable batteries do not provide sufficient voltage.

 

Coding Your MiniBit

Microsoft MakeCode

Click any image to enlarge.

To load the extension, select Advanced, then Extensions. Then enter “Minibit” into the search box and press Enter. If that doesn’t find it (there are sometimes earch glitches) you can enter the full URL into the search box: “https://github.com/4tronix/MiniBit”

Once loaded, you will have a MiniBit menu item with 4 sub-folders:

Motor Blocks

The first command “Drive at speed 600” will set both motors to speed 600. If you do nothing more, the MinBit will continue going forward forever.

The speed value can be from -1023 (full speed reverse) to 1023 (full speed forward). Setting the speed to 0 will stop the motors

There is also a block for spinning – left motor and right motor turn at the same speed but in opposite directions.

Both the drive and spin blocks have a paired block that will drive (or spin) for a selected amopunt of time and then stop

There are two ways of stopping. Coasting to a stop or braking. If you set the speed to 0 or use the “stop with no brake” command, then it will stop gently over the coourse of a second or so 9depending on initial speed). If you use the “stop with brake” block (or the drive/spin for a time block) then it will stop almost immediately.

Finally, you can drive each motor individually. For instance if you set the left motor to drive at 600 and the right motor to drive at 1000, then it will perform an arc towards the left

LED Blocks

You can use these blocks to set and clear one or all the LEDs.

Note that the MiniBit defaults to automatically updating the LEDs whenever any change is made see the “more…” section to learn how and why to change this behaviour

The LEDs on the MiniBit are labelled from 0 to 3. Use these numbers in the Makecode blocks to change the colour. eg setting LED 1 to Purple could be done like this:

The default brightness level is 40. This is plenty bright enough for most uses, saves damaging eyes, and reduces battery consumption. If required you can change the brightness from 0 up to 255

Sensor Blocks

Only one sensor in here; the ultrasonic distance sensor. You can get the values to the nearest object in cm, inches or microseconds

More Blocks

These are the advanced usage blocks. Most students will not need to use them.

  • Set update mode is used to switch between automatic LED updates or manual LED updates. The default is for automatic updates: every change to the LEDs results in all the LEDs being written to with the updated values. This is easy to understand, but it does mean that when making a lot of changes it can slow things down considerably. If doing that, it is best to use Manual update mode, make all the changes required, then use the show LED changes block to make all the updates in one go.
  • Rotate LEDs block will move the colour in LED 0 to LED 1, LED1 to LED2, LED2 to LED3 and LED3 to LED0. If done repeatedly, with a delay between each one, it will show the lED colours rotating around all the 4 LEDs.
  • Shift LEDs block will move LED0 to LED1, LED1 to LED2 and LED2 to LED3. It will blank LED0. So all the colours will disappear one at a time from 0 to 3
  • You can also create your own colours and replace the fixed list of colours in any command using the convert from red, green, blue block. For example, to set LED0 to a blue-green colour:

 

Programming in microPython

Driving Motors

The motors use 2 pins each to determine the speed and direction. In microPython we use write_analog ( ) to set the first pin to a value between 0 and 1023 and the second pin to 0 in order to go forward. To reverse, we swap the pins so that the first pin is set to 0 and the second pin is set to the value.

On the MiniBit the left motor uses pins 12 and 8, and the right motor uses pins 16 and 14.

So to move the left motor forwards at speed 600:

pin12.write_analog(600)
pin8.write_digital(0)

And to move the right motor in reverse at speed 450:

pin16.write_digital(0)
pin14.write_analog(450)

To stop with no brake, use write_digital ( ) to set both pins to 0. To stop with brake, set both pins to 1.
eg. stop left motor with coasting and right motor with brake:

pin12.write_digital(0)
pin8.write_digital(0)

pin16.write_digital(1)
pin14.write_digital(1)

So a complete, but fairly useless, program to drive the motors for 2 seconds and then stop quickly, would look like this:

from microbit import *
pin12.write_analog(600)
pin8.write_digital(0)
pin16.write_analog(600)
pin14.write_digital(0)
sleep(2000)
pin12.write_analog(0) # temporary fix for python bug
pin12.write_digital(1)

pin8.write_digital(1)
pin16.write_analog(0) # temporary fix for python bug
pin16.write_digital(1)

pin14.write_digital(1)

Note the 2 lines that write_analog(0) before swapping a pin from analog to digital. These are required until a fix is obtained for the python PWM driver continually updating the pin type to analog

Lighting the LEDs

This uses the standard neopixel code, with the LEDs connected to Pin 13.

At the top of your program add import neopixel then:

leds = neopixel.NeoPixel(13, 4)

leds is then an array of all 4 LEDs. leds[0] refers to the LED 0 and leds[3] refers to LED3. Each element of the array is a set of 3 numbers representing the Red, Green and Blue values (each 0..255) for that LED. So to set LED2 to Blue:

leds[2] = (0, 0, 255)

All this does is update the array. To show the new value of the array, we need to call the show ( ) function as follows:

leds.show ( )

 

Reading the Ultrasonic Distance Sensor

The ultrasonic sensor breakout is on pin15.

The concept is simple: send an ultrasonic pulse out, then time how long it takes to return. Using the speed of sound and some maths, we can then work out the distance. The following complete program has 2 parts to it: a function sonar ( ) which returns the distance to the object, and the main code in a loop which continually prints the distance. We also need to import the utime library:

from microbit import *
from utime import ticks_us, sleep_us

def sonar():
    pin15.write_digital(1) # Send 10us Ping pulse
    sleep_us(10)
    pin15.write_digital(0)
    pin15.set_pull(pin15, NO_PULL)
while pin15.read_digital() == 0: # ensure Ping pulse has cleared

        pass
    start = ticks_us() # define starting time
    while pin15.read_digital() == 1: # wait for Echo pulse to return
        pass
    end = ticks_us() # define ending time
    echo = end-start
    distance = int(0.01715 * echo) # Calculate cm distance
    return distance

while True:
    display.scroll(sonar())
    sleep(1000)

 

 

Scooter for Raspberry Pi Zero

Scooter Robot for Raspberry Pi Zero

Purchase Scooter

Assembly

Step 1 – Check you have all the parts

  • Main board with attached battery holder
  • 2 x wheels
  • 2 x 16mm pillars
  • 4 x screws
  • Female header

Step 2 – Remove the Battery Holder

Unscrew the battery holder, taking careful note of which way it is fitted

 

Step 3 – Fit the Raspberry Pi Zero

NB. You need to have a Pi Zero with the headers fitted. Model Zero WH is recommended

Screw the 16mm pillars onto the main board

Push the included female header into the low-profile header on the main board

Fit the Pi Zero to the header, with the Pi Zero sitting over the motors as shown below

Screw the Pi Zero onto the headers so it doesn’t fall off in use

 

Step 4 – Complete the Assembly

Refit the battery holder

Push on the wheels

Add batteries

Start coding…

Coding for the Scooter

Install the software

First you will need to prepare your Pi for the Smart RGB LEDs (fully compatible with neopixels). The best way we’ve found to do this is run Pimoroni’s curl script.
With your Pi connected to the internet, run (you don’t need to install the resources and examples):

curl -sS https://get.pimoroni.com/unicornhat | bash

Then install the Scooter software:

wget https://4tronix.co.uk/scooter.sh -O scooter.sh

bash scooter.sh

This installs the following files:

  • scooter.py the main library module
  • motorTest.py Use the arrow keys to control the motors. Use . and , to speed up and slow down after next arrow press. Press space bar to stop slowly and ‘b’ to brake quickly
  • ledTest.py Sets the Smart RGB LEDs to Red, Green, Blue, White in turn. Run with sudo python ledTest.py
  • lineTest.py shows the states of the line follower sensors
  • sonarTest.py gives the distance in cm to an obstacle using the optional HC-SR04P
  • avoider.py is a simple obstacle avoider. Run with sudo python avoider.py
  • lineFollower.py is a simple line follower. This runs the Scooter backwards and is best with lines printed from RobotSquare.

 

 

 

Pi2Go Mk2 Assembly

Assembly Instructions for Pi2Go Mk2

Click any image to enlarge

Step 1 – Check the Contents

Check you have:

  • Main Board
  • Battery Board
  • Caster Board
  • 2 Wheels
  • 2 Motors
  • 2 Motor Fixings Bags
  • Bag with mechanical parts (caster, encoder disks, headers)
  • Fixings Bag with screws and spacers

Fixings bag contains:

  • 4 x 5mm, M3, Male-Female pillars
  • 4 x 11mm, M2.5 Male-Female pillars
  • 4 x 19mm, M2.5 Female-Female pillars
  • 2 x 24mm, M3, Female-Female pillars
  • 4 x 4mm, M3 screws
  • 4 x 8mm, M3 screws
  • 8 x 6mm, M2.5 screws

 

Step 2 – Fit the Raspberry Pi Mountings

You will need 4 x 19mm, M2.5 pillars and 4 x 6mm, M2.5 screws.

Fit the 4 pillars to the main board as shown below

 

Step 3 – Prepare the Motor Mounts

Screw 2 of the 5mm, M3 pillars into the top of each motor mount. Ensure they are fitted tightly

 

Step 4 – Fit the Motor Mounts to the Motors

Pass one of the long screws from the outside of the motor (the side without the wires), through the motor and through the motor mount. Then loosely fit one of the nuts. It will sit at a strange angle as shown below

Then pivot the mount on the long nut, so that it pushes the wires out of the way and allows you to put the second long screw in. Then tighten up both nuts.

Repeat for the second motor, but fit the mount the other way up.

You should now have a left-hand and a right-hand motor assembly as shown above

Step 5 – Fit the Motor Assemblies to the Main Board

First, attach an encoder wheel to the inside shaft of each motor. Just push it on so that it is flush with the end of the shaft. It may take some pushing to get it on, and when it is on it will be a bit floppy. This is normal

Now use the 4mm, M3 screws, 2 for each motor, to screw through the main board into the pillars that you fitted into each motor mount in step 3

 

Step 6 – Assemble the Front Caster board

Use 2 of the 8mm, M3 screws to screw through the caster, through the caster PCB and into the 24mm, M3 pillars. Ensure the header pins are on the opposite side to the caster, and the same side as the pillars.

 

Step 7 – Fit the Caster Board to the Main Board

First push the extended 6-pin header into the header on the bottom of the main board, then plug the assembled caster board into the 6-pin header as shown below

Finally screw the 2 remaining 8mm, M3 screws through the main board and into the top of the pillars from the caster board. Tighten up well.

 

Step 8 – Fit the Raspberry Pi

You can use a Model A, A+, B or B+.

NB: To use a Raspberry Pi Zero, use the “Zero Spacer” PCB that is included with Pi2Go Mk2 since 1st September 2019. Kits shipped prior to that date do not include that spacer so you would have to use washers or similar to make up the extra 1.6mm height.

Push the 40-pin header onto the header on the main board

Then push the Raspberry Pi, upside down, into the 40-pin header, ensuring that all the pins line up and the mounting holes on the Raspberry Pi match the pillars

Screw the 11mm, M2.5 Male-Female pillars in well to hold the Pi firmly

 

Step 9 – Fit the Battery Board

Standard 6 x AA battery board shown. Fitting the other types is the same

Making sure that the LEDs marked 0 through 7 are at the front, use the 6mm, M2.5 screws to fix the battery board tightly to the 4 pillars.
Note that these pillars all carry power and/or signals, so it is important that they are all screwed in well. Failure to attach screws or pillars properly will result in failure of the Pi2Go.

 

Step 10 – Add the Wheels

Push on the wheels

And the build is complete!

Now go to the Programming Pi2Go Mk2 article to get it going

 

 

PiBug Assembly and Coding

PiBug

Click on any image to enlarge

A barebones, but sturdy, 2WD buggy for the Raspberry Pi, that uses the Pi itself as the chassis for the robot.

Purchase PiBug Here

Assembling the PiBug

Step 0 – Check you have all the parts

  1. Main board
  2. Caster board
  3. Battery board
  4. Battery holder
  5. Castor Pack containing:
    1. Castor ball and housing
    2. Screws: M3, 6mm X 2
    3. Nuts: M3 X 2
  6. Fixings Pack containing:
    1. 22mm F-F pillars X 2
    2. 22mm M-F pillars X 2
    3. 30mm Pillars with holes X 2
    4. 25mm F-F pillars X 2
    5. 9mm M-F pillars X 8
    6. 6mm M2.5 screws X 6 (2 for the caster board)
    7. 30mm M2.5 screws X 4
  7. Motors X 2
  8. Wheels X 2

Step 1 – Attach the Castor to the Castor board

Put the M3 nuts in the holes in the castor housing, then use the 6mm M3 screws to fit the housing tightly to the castor board as shown, with the castor on the bottom and the large 4tronix logo on the top.

Step 2 – Assemble the Motor Mounts

  1. Screw a 22mm Male-Female pillar into a 22mm Female-Female pillar tightly, making a 44mm female-female spacer (remember: 22mm is not the same as 25mm)
  2. Repeat to create a second 44mm spacer
  3. Thread the 30mm screws through the holes in the motor and through the holes in the side of the 30mm pillars, then screw into the 44mm spacers
  4. Important: The 30mm pillars with holes have one end rounded for about 1mm. This is the bottom, the other end is the top that fits to the Raspberry Pi. The rounded end is tapped for M3, and the hex end is tapped for M2.5. Ensure you have these the correct way up
  5. Ensure that the motors shafts are facing outwards as shown in the photo

Step 3 – Fit Motor mounts to Raspberry Pi

You can use either Model A or Model B varieties of Pi. You can’t use a Zero (at least not without some ingenuity…)

  1. In this step we will use 4 of the 9mm pillars
  2. Screw the threaded end of the 9mm pillars through the 2 holes in the SD card end of the Raspberry Pi and into the top of the 30mm pillars of the motor mount assembly
  3. Ensure all screws are tightly fastened

Step 4 – Fit the Castor assembly to Raspberry Pi

  1. Use 2 of the 6mm M2.5 screws to attach the 25mm pillars to the top of the castor board
  2. Use the 2 more of the 9mm pillars and screw through the holes in the Pi into the top of the 25mm pillars as shown

Step 5 – Fit the PiBug Main Board

  1. Push the PiBug main board onto the GPIO connector of the Pi. Ensure all the pins are lined up properly and that the holes on the PiBug board line up with the 9mm pillars
  2. Use the threaded ends of the 4 remaining 9mm male-female pillars to fit the PiBug main board into position.

Step 6 – Fit the Battery Holder Board

Use the 4 remaining 6mm, M2.5 screws to fit the battery holder PCB as shown, with the snap connectors at the USB/ethernet end of the Raspberry Pi

Step 7 – Connecting it up

  1. Connect the JST leads from the motors into the appropriate motor connector on the PiBug board
  2. Fit 6 AA rechargeable batteries into the battery holder and then plug it into the connectors on the battery board.
  3. Note that it will work with alkaline batteries, but when the batteries get low it may suddenly reset the Pi when changing motor direction. This behaviour is better with rechargeable batteries.
  4. We recommend that you use a velcro strap or similar to hold the battery pack in place in case of accidents

Step 8 – Fitting the Optional Line Sensor Board

Use the servo leads to connect the line sensors from the caster board to the male header on the PiBug main board. Ensure the correct orientation of the cable: Brown wire should be on the robot’s right side of the castor board (labelled ‘G’) and on the bottom of the header on the PiBug board (labelled Gnd). Use the leftmost and rightmost positions for the cables

Step 9 – Fitting the Optional Ultrasonic Distance Sensor

  1. Use a HC-SR04P which is 3.3V compatible. Do not use the older HC-SR04.
  2. Remove the black plastic spacer, so that it can push all the way down.
  3. Plug it through the 4 holes in the battery board and push it all the way down (see photo above)
  4. The sensor is now connected to pin 20 on the Raspberry Pi

NB. We have also sold the HC-SR04+ for this purpose. it doesn’t need modifying by removing the spacer, but it is a little shorter and may need holding in to keep a good connection.

You have now completed the buggy and all you need to do is code it!

Coding PiBug

Pins used:

Left motor: #19, #26

Right motor: #16, #21

Ultrasonic: #20

Line sensors: #04, #27

Tact switch: #13

There are also 2 spare GVS style connectors which you can use for what you want on #17 and #18

A PiBug library module and example code is available by running the following commands in a terminal window on your Pi

  • wget https://4tronix.co.uk/pibug.sh -O pibug.sh
  • bash pibug.sh

 

 

Programming Robobit Buggy in Makecode

Programming Robobit Buggy

The Microbit Makecode Package supports all versions of the Robobit. Go to https://makecode.microbit.org/ or download the PC app from here 

Select Advanced or click on the gear icon, then select Extensions. Enter Robobit in the search box and search.

After it has loaded you will have an extra tool in 4tronix Orange with the Taxi icon, called Robobit

If you click on the Robobit tool, there are 3 subfolders for the Motors, the Sensors and the LedBar. There is also a single top-level block to allow you to select your model of Robobit – this should be used at the very start as shown below. In fact it can be the only thing in the start block

Now you are ready to start programming…

Programming the Motors

It’s a robot – you want it to move. So let’s see what we need to do.

The motors are individually controllable. So if you want, you can set different speeds for the left and right motors. But to start simply, let’s just drive forwards and backwards.

Forwards is represented by speeds from 0 to 1023. Backwards is speeds from -1023 to 0.

In both cases, 1023 is the fastest and 0 is dead stop. You will find that speeds below 200-300 may not be able to move the robot very much (it depends on battery levels, how “free” the motors are, etc)

The following code simple drives forwards at speed 600 (both motors at the same speed) for 1 second, stops for a second, then reverses and stops again. It repeats this forever

Yes, we have a moving robot!

NB. You may find, especially when the motors are new, that they go at different speeds and it doesn’t travel in straight lines. This is normal. The motors have a 10% speed tolerance, so can always be different speeds, but when they are new they can be especially stiff and even more different. Run the motors at full spoeed for a few minutes to free them up.

 

More Complex Motor Control

We can try and move in a square, or other shape. Great if you’re on a piece of paper and using the pen (Pen holders are designed for Sharpie felt tip pens – other pens are available)

Drive forwards for a bit, turn for a bit and do this 4 times. If you get the speed and times correct then a square can be formed. You will have to experiment with the speeds and times

The code above (click to enlarge) will do a four-sided figure and then stop. You will have to adjust the timings and/or speed of the spin to get it to accurately draw a square.

Of course, this software is tedious. It does the same thing 4 times. It would be better to use a loop function like this:

Here, we are using the “repeat nn times” block from the “Loops” toolbox

 

Now Let’s Flash some LEDs

It’s always fun to light LEDs and especially fun if you can control them individually with different brightness and colours.

The Robobit Mk3 and the Mk2 with LedBar have a row of 6 LEDs across the front as well as one in each front corner for a total of 8.

Scanner Feature

The Makecode package has a unique “Larsson Scanner” feature built-in which enables you to very easily scan the centre 6 LEDs back and forth at your choice speed and colour. Let’s do this to start with:

From the LedBar section of Robobit, select the “start scan…” block and insert it into the program after setting the required Robobit model. Here we are using a Mk2 Robobit with a LedBar attachment.

This code will immediately start the centre 6 LEDs scanning using various intensities of Red, with a delay of 100ms between changes, just like the Knight Rider KITT car!

Standard LED Programming

Normally when using the LEDs you will set on or more LEDs to a particular colour depending what you want the program to display. To do this, you need to understand how to work with individualy LEDs.

There are blocks you can use to set individual LEDs (or pixels), or all the LEDs at the same time. You can select colours using the names of colours (eg. Red, Yellow, Green, etc) or you can specify your own colour in terms of Red, Green and Blue components. All these blocks set the memory in the Microbit for the LEDs, but they do NOT update the LEDs with this memory information. To do that, you must use the most important block of all:

After doing this, all the changes you have made will be shown on the LEDs.

The other thing to remember is that the 8 LEDs are numbered from the left at 0 to the right at 7. So to flash the leftmost LED in Orange, we could do this:

This will set the LED at position 0 to orange, then wait for half a second, then set the LED to black (this is the same as OFF), then wait another half a second. Then this keeps repeating forever. Notice that each time we update the LED information, we than “show the LedBar changes”.

 

Using Sensors

Depending on your Robobit model and options fitted you may have an Ultrasonic Distance sensor and/or line following sensors. For the Robobit Mk3, these are both included as standard. For the Mk2, they can be purchased as options.

The Robobit Makecode extension includes blocks for using these easily.

Line Following Sensors

There are 2 of these mounted underneath the buggy, close to the front caster. They both use the same hardware sensor (TCRT5000) but the integrated ones on the Mk3 use 4tronix electronics specifically designed for this application whereas the Mk2 uses generic modules which have a trimmer on. Turn this until the LED turns off when it goes over a black line. You will find that the integrated units perform better.

The key thing to remember is that the Robobit buggy and the motors have a lot of interia when moving and cannot stop very quickly, so you must design your line follower program to move slowly (there are clever things that can be done, but we won’t look at that now). The Mk2 will have to go slower than the Mk3 because of the difference in sensitivity of the sensors.

To create a track to follow, you can use black electrical tape, or a permanent black marker. The surface needs to be reflective and the tape or marker pen needs to be not reflective. I prefer to print the tracks using track tiles from RobotSquare as these work excellently.

The simplest algorithm will be to check each sensor. If it is over a line, then turn the buggy that way, otherwise carry straight on. Keep checking in a loop like this:

Note that we are using speeds of less than 400. For a Mk1 or Mk2 you will probably have to go even slower.

This is a very basic algorithm and will have problems with junctions on the track etc. it also won’t do very well in a speed trial.

 

Ultrasonic Distance Sensor

These little sensors work like bats, by sending out an ultrasound ping and waiting for the echo to come back. The time for the echo to come back, together with the speed of sound, gives us an idea of the distance. Do not expect ultimate accuracy from these sensors.

You can choose to get the distance back in different units: centimetres, inches or microseconds. These examples all use centimetres (cm).

Obstacle Avoider

This simple program drives forwards until it detects an obstacle, then spins and reverse to avoid it before setting off again.

The first block checks if the robot is within 20cm of an object. If it is then it reverses at speed 500 for half a second, before turning left for 400ms. If it is not less than 20cm from an object it just drives straight on at speed 600.

 

Follow Me Program

This fun little program drives forwards until it gets close to an object and then stops. Then if the object (eg. your leg) gets further away, it will start moving again to follow you. However, if your leg gets closer then it will back away trying to keep the same distance from you:

In this one, we have created a variable called Distance so that we can check it against 2 values without reading the sensor again. Here we reverse the robot if it less than 20cm away and go forwards if it is more than 30cm away. Between 20cm and 30cm the robot will stay still.