Wednesday, 23 September 2020

Arduino Development using VSCode

The Arduino IDE provides a means to write code for microcontrollers, with library management, compilation and uploading of your code. But the code development environment is lacking many of the features of a modern IDE. Enter VSCode to the rescue! Providing syntax checking, auto-indentation (with clean up), and code completion via the IntelliSense feature. VSCode is free and provides a capable development environment which supports multiple languages, remote code development over SSH and many other capabilities via a comprehensive library of extensions. In this article, we will be looking at options to use it to develop code for Arduino (and Arduino supported boards).

Before starting with VSCode, you need to install the Arduino Desktop IDE (at time of writing this was v1.8.13). You can download it from The VSCode extensions use the Arduino IDE under the hood, so you need this to be working with your boards.  Check that example sketches can be compiled and deployed onto your board using  the Arduino IDE. 

Now we can set up VSCode. You can download the editor from

We will be writing C/C++ code for Arduino, so we need to install the extension to add support for this language. 

Down the lefthand side of the VSCode window is a vertical toolbar. Click on the Extensions button to open the extensions manager. 

Find and install the C/C++ extension:

There are two options to add support for Arduino development. The more obvious looking one is the Arduino extension. I was able to get this working with some configuration required, but a number of features did not work for me. I could not open the Serial Monitor, Teensy boards were not supported and I found the IntelliSense feature reported problems in my code which were not problems for the Arduino compiler. I did learn a few tricks to make things workable and I have detailed these at the end of this article if you want to use this extension. But I found things worked better for me using the alternative option, the PlatformIO IDE extension. You probably don't want to install both as the IntelliSense feature configurations of each are not compatible.

PlatformIO IDE

The PlatformIO IDE extension provides support for more boards (including the Teensy family). You will need to convert any .ino files into .cpp files in your projects to work with this extension. But aside from that I found it very easy to set up and most of the configuration was automatic.

To get started with the PlatformIO IDE, I suggest you follow their quickstart guide. That is what I did, and there is little point in me repeating that information here. See 

Once I had built a basic blink sketch following the quickstart guide, I successfully imported an existing Arduino project from the extension home page, ticking the option to use the Arduino libraries already installed on my computer. This created a copy of the project under my <user>/Documents/PlatformIO/Projects directory, with the configuration set up to include libraries from the existing Arduino IDE installation on my computer. You select the board you want to compile for in the import dialog. I already had the Teensyduino packages installed, and found the Teensy boards listed in the board picker. The IDE warned me that I should change the .ino file to a .cpp file in order for IntelliSense to work. I just renamed this file through the VSCode explorer pane and I was able to compile and upload it to my Teensy 3.2 board.

One additional configuration change I made was in the platformio.ini file under my project. I added a build_cache_dir line as follows in my ini file. You can point this to any folder you like outside your project. By doing this, libraries compiled as part of your sketch will not need recompiling every time you rebuild. So after the first build, subsequent builds will only need to recompile classes with code changes, so will be much faster.

; Set a path to a cache folder
build_cache_dir = C:/temp/PlatformIO_buildcache

You can also add additional library paths in this file. I was working on a project which uses a library I am also developing on my computer. So I added a path to my library code in development after the path to the Arduino libraries (note the syntax ~ to refer to your user home directory):

platform = teensy
board = teensy31
framework = arduino
lib_extra_dirs = 

That was all I needed to do to get up and running. I found this worked better for me than the Arduino extension, but if you want to use that instead, read on.

Arduino Extension

If you want to use the Arduino extension instead of PlatformIO (maybe you want to work on projects with .ino files for example), then install that extension instead.

This adds several Arduino commands to the command palette. With this installed, when you open an Arduino sketch (.ino) file in VSCode you should see a custom footer bar with clickable options to select the connected board, COM port and Programmer (if you are using one). Click on the <select board> item and the board manager should open (you can also open it via the Command Palette). I found the <select PORT> command was not working, so I had to set it manually in the arduino.json file. Open this file from the .vscode folder in your workspace, and add the COM port line as follows (setting the correct numbered COM port matching the one you used to program your board from the Arduino IDE).


You should now be able to verify sketches and upload them to your board using the Arduino commands.

Open Command Palette (Ctrl + Shift + P), and type 'Arduino' to filter the commands list in the command picker. You will see 'Arduino: Verify' and 'Arduino: Upload' commands. Note these also have keyboard shortcuts displayed. e.g. You can compile and Upload the open sketch using Ctrl + Alt + U.

The first time you do this for a project, you will be asked which .ino file is the main one (if you have more than one in the sketch). Once you select this it is added into the arduino.json configuration file (so you know where to go to change it if you change the main file later).

You may see a warning at the start of the compiler output, saying 'Output path is not specified. Unable to reuse previously compiled files. Upload could be slow. See README.'. This means that each time you make a code change and go to upload again, the compiler has the recompile the entire project including all libraries, which can take a long time. To allow it to reuse the output from a previous compile and only recompile the files which have been changed, you need to define and output folder in the arduino.json file. This folder should not be under the project folder. You can add the following line to set the output to a folder named ArduinoOutput located alongside your project. Alternatively give a full path to a folder, maybe in your temp directory.


This should get you to the point where you can open, edit, compile and upload sketches to your boards. But you may notice the code IDE still shows lots of errors in the code because the VSCode IntelliSense feature does not know where all the Arduino libraries are located. We need to add these to the workspace include paths:

Using the command palette, run the command: C/C++: Edit Configurations (UI)

This will open the UI to edit your C/C++ configuration. You can edit your win32 configuration, or create a new one. I decided to create a new one named 'arduino'.

In the 'Include Path' field, make sure all 3 of these paths are added in addition to the workspaceFolder item:

C:/Program Files (x86)/Arduino/hardware/arduino/avr/libraries/**

That last one assumes you installed the Arduino IDE into the default location under C:\Program Files (x86)\Arduino. If you installed to a different location then change it as appropriate. Note the use of the userprofile environment variable to make the configuration work on any computer. These configuration files can be checked into source control so that your projects can be checked out and run quickly on different computers regardless of the logged in username.

My complete arduino configuration section looked like this:

            "includePath": [
                "C:/Program Files (x86)/Arduino/hardware/arduino/avr/libraries/**"
            "defines": [
            "compilerPath""C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin\\gcc.exe",

Finally, open the command palette again and run the command C/C++: Select a configuration, and select the 'arduino' configuration. This should clear most of the reported 'problems' in the code IDE, and IntelliSense code completion suggestions should now be working. There are some exceptions to this however.

The Arduino IDE appears to treat all .ino files in a project directory as being part of the main .ino file. So any code split across different .ino files will be compiled by the Arduino IDE as if that code was all in one big file. However the VSCode IntelliSense environment does not do this. One way to avoid this problem is to only have a single .ino file in your project, and use the extension .cpp for any other code files. You will then have to add #include statements as required to include these .cpp files in other files which reference them, and you will no longer be able to access globals defined in the main .ino file from code in the .cpp files. It will make you write better code, forcing references to be passed to objects rather than being accessible everywhere via globals. But you may find projects published by others do not work with the IntelliSense feature in VSCode.

In some cases, libraries will have been written to be compatible with both Arduino and Windows/Linux C/C++ programs. These can cause problems because the VSCode IntelliSense environment does not realise it is running in an Arduino environment. So it tries to check the code against windows libraries which will not be on your Arduino project path. You can make it behave like an Arduino environment by adding the following line to the start of your main sketch .ino file:

#define ARDUINO 100

But I suggest commenting out the line before compiling as the Arduino IDE will set it's own define, which may be different to this. Better to just live with these reported include errors since they will not apply when the Arduino IDE compiles the code.

Some data types in my project were flagged as not defined by default in standard C/C++. These included:

  • byte
  • boolean
  • uint8_t/uint16_t/uint_32_t
If you want to avoid these being flagged as errors by IntelliSense then you can use bool in place of boolean, uint8_t in place of byte. Then to make IntelliSense aware of the uint types, I added the following #if defines which I use in code designed to be compatible with both Arduino and non-Arduino environments:

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#elif defined(ARDUINO)
#include "WProgram.h"
#include <stdint.h>
#include <stdio.h>

I am not sure how much of this was really needed, as the IntelliSense appeared somewhat temperamental about which errors it reported. Sometimes if would just be complaining that included libraries referenced header files it could not find, but then it would suddenly report most of my file contained errors.

I was unable to get the serial monitor working under the Arduino extension. When I clicked the icon in the footer toolbar to open it, I saw the following error: .vscode\extensions\vsciot-vscode.vscode-arduino-0.3.2\out\node_modules\usb-detection\build\Release\detection.node is not a valid Win32 application.

I uninstalled the Arduino extension after I discovered the PlatformIO IDE extension, which appears to be working much better for me. If you have more success then please share in the comments.

Thursday, 14 March 2019

A Complete Rebuild in Acrylic

It was always my plan to make my competition robot in transparent laser cut acrylic, so that the insides could be seen. Plus it just looks so nice! Having learned the art of designing and building a laser cut robot using 3 mm plywood I was now ready to re-cut the refined design in acrylic. The main modification I made was to shorten the legs by 15 mm. I had realised from driving my prototype that it really did not need such high ground clearance as the small wheels could not climb over anything but small obstacles. It was also a little unstable. I could get it to lift some of the wheels off the ground doing sharp turns at speed!

I added some engraving to various parts and also added holes for threading all the motor and servo wires through the legs. I had drilled these holes by hand on the wooden model. Now I knew where I wanted them I added them to the CAD model so these could be laser cut on the acrylic parts. I had already designed an acrylic mount for my main display and had this mounted on the wooden chassis.

With so many parts to cut I wanted to make optimum use of my acrylic sheet material. So I used an online SVG nesting tool to layout the parts. I prepared an SVG file of all the parts in Inkscape, including a containing rectangle required by the nesting tool to limit the area and shape to fit the parts into. I uploaded this to which generated a cutting layout for me to download.

An optimised parts layout for laser cutting

The complete set of laser cut acrylic parts ready to assemble

First I assembled the 4 steering legs. One snag I ran into is the inconsistency in thickness of acrylic sheets. A 3 mm sheet can vary in thickness between around 2.8 mm and 3.2 mm. This is due to the surface tension on the sheet when it is being cast, which results in a curved top surface dipping down towards the middle of the sheet. The sheet sizes you typically buy are cut from this larger cast sheet. Depending on which part of the cast sheet your piece was cut from you get different thicknesses across your piece. Some of my sheets exceeded 3 mm thickness towards one end, so some of my parts did not slot together as all my slots are cut at 3 mm wide. I had to re-cut a few parts with slightly wider slots. But I did not want to make all my slots wider by default, particularly the motor mounting plates which wobbled too much when the slots were not a tight fit. This an area which could do with some more refinement so that the rigidity of the motor mounts is not so dependent on tight tolerances. In the process of assembly I accidentally snapped one part in half and cracked another by over tightening the bolts holding the parts together. Acrylic is a much more brittle material than plywood and is easy to crack, especially around rectangular holes with sharp internal corners. I later modified some of my parts to increase the width of material around the outside edges of the slots from 3 mm to 4 mm to increase the strength of some parts. After re-cutting (plus a few spares) I had two completed Rocker Bogie arms.

The Rocker Bogie arms remade in acrylic with cable routing holes

As I assembled my robot using the new parts, I tried to extensively photo-document every step of the process. My plan is to write up a full build guide and possibly release a kit of parts for others to build their own rover from my design.

Some of the many photographs I took to document the assembly process

Another problem which came from switching to acrylic was that the plates did not grip each other like the plywood had. Some of my chassis body side plates were not staying together at the ends furthest from the bolts holding them in place. I had to add some additional T-slots and bolts to hold everything firmly together. I had designed a new front plate to mount a Pixy2 camera on, and this was not held on with anything more than the friction of the tabs in the slots. This would need more refinement for the competition as it was also going to be holding my Pi Noon attachment and I did not want that falling off mid-battle. For for now I could push it on and it looked good enough for me to shoot some photos. I set up my filming lights to provide some nice back lighting and took a few photos to try and capture the beauty of the acrylic design.

My final photo submitted for the Pi Wars 2019 program

Wednesday, 13 March 2019

Another Redesign: Electronics Cartridge

One problem I identified with my robot chassis design was that I could not access any of the electronics without taking the whole thing apart. It was not possible to remove the SD Card from the Raspberry Pi without unscrewing the Pi either. One option for the SD Card access which Brian Corteil suggested was to boot the Pi from a USB thumb drive instead. I had not realised this was possible, but some testing with various tiny sized USB memory sticks showed this worked very well (at least with the Pi 3b). But I was still concerned that if I had any wiring problems on competition day it would be difficult to access the internals to fix things.

The idea I had to solve this was to redesign my chassis so that all the electronics were mounted on a plug-in cartridge which could be pulled out of the chassis to easily access everything. This also allowed me to design a second tier to mount breakout boards on above the Raspberry Pi.

CAD model of my electronics cartridge

Having a 2 tier electronics tray posed some problems with how to route the ribbon cable which connects the touch screen display to the Pi. I went through a few iterations before building a prototype cartridge. If I routed the ribbon cable straight up through the upper tier then it limited the space to arrange the breakout boards on that tier. I ended up with a design where the ribbon cable was folded to change the orientation through 90 degrees from the Pi to the display. The fold was contained on the lower tier, which required the height of the lower tier to be higher than originally planned. Space was tight for the upper tier, and I did not take into account the height of the Du Pont connectors used to attach all the wires to the breakout boards. Another redesign of my entire chassis was required to allow another 5mm of head room. I modelled just one Du Pont connector with a wire bending over coming from it (you can see it in the CAD model above) to check I had the required headroom for the wiring.

Redesigned chassis with the electronics cartridge inserted

It all looked great in CAD, but when I came to assemble it I realised I needed a lot longer cables to provide enough slack to actually slide out the cartridge from the chassis. My ribbon cable was not long enough and 40 way ribbon cables seemed very expensive when I looked online at the usual electronics suppliers. Then I remembered somebody had pointed out that IDE hard disk cables in older PCs were just this type of cable. I checked my box of parts for modding PCs and found I had several. They all had 3 connectors, but I simply cut one off close to the middle connector to give a suitable length ribbon cable. All my other Du Pont connector leads I was making myself from a reel of ribbon cable, so I made these long enough to provide some slack.

The reality was that all this extra cable took up a lot of room, and the cartridge was very tightly packed when assembled. It was very hard to slide out due to the cables all catching on bolts, and in hindsight I could have done with another 10mm of head room in the chassis. But I can just about slide it out with a lot of cable wrangling if required to plug in a new lead. I later extended the i2c breakout to a second bus board near the front of the chassis so that I could easily plug and unplug additional ic2 devices mounted on the front of the robot without needing to remove the cartridge.

The assembled electronics cartridge with the multiple folds in the long ribbon cable. Most of the i2c device cables are missing here, apart from one connecting to the PWM breakout used to drive the servos and motor power. The 4 servo cables are also missing here.

Shown with the chassis front and front-side panels removed. The cables completely pack out the space in the cartridge.

Tuesday, 12 March 2019

Robot Software Design

I went for a modular design for my robot software. Python is very modular in structure, with each module importing the modules (or code libraries) it requires. I designed my robot software along the following lines.

Each module does a specific job, and is accessed through a few simple functions which describe the operation being performed. For example the Sensors module contains a function readDistance(sensor) which returns the distance measured by one of the TOF (time of flight) sensors. The parameter (sensor) specifies which sensor (by number) to read. The module also provides the required methods to configure and initialise the sensors, and the i2c multiplexer board they are connected to. So all the complexity of switching i2c buses, turning on sensors and reading them is wrapped up in a module with a very simple code interface.

Another advantage of a modular approach is that you can put all the code which is specific to a set of hardware (e.g. motor controllers) in a single module. The module then presents an interface with simple methods like setMotorSpeed(motor, speed). If you need to change the motor controllers used in your robot, or want to reuse the code on another robot with a similar arrangement of twin motors then you only need to replace this one module and the rest of the code can be reused without changes.

The hardware interface module is called from a module which represents the movement capabilities of the robot. In this case my robot has steerable wheels, and multiple motors wired up in two groups. So the movement control of the robot is wrapped up and controlled through a few simple functions:

  • setLeftMotorPower(speed)
  • setRightMotorPower(speed)
  • setSteering(angle)
  • setSpotTurn(angle)

The LED Matrices module handles setting up and connecting a pair of rgb 5x5 LED matrix breakouts, and displaying patterns on them. A series of patterns are stored in the module and can be called by name. There is also a frame buffer which allows series of patterns to be queued up to show on the LEDs one after the other. Methods can be added to queue up patterns by name. e.g. showBlueEyes() or eyesBlink(). Animations cycle through the frames in the buffer for each display when a nextFrame() method is called.

The main program module handles output onto the main display screen. It also contains all the event handler functions for controller input. A separate module handles detecting different game controllers and mapping their buttons, sticks, hats and triggers to the same named events. So a range of game controllers can be used on the robot and they will all call the same code when their 'triangle button' is pressed.

The main module also contains the code for reacting to touchscreen input to display and navigate through graphical menus, and the main program loop which takes actions based on the mode the robot is in. In this main loop, sensors reading calls can be made, there is the call to display the next frame on the LED matrices, and trigger calls to any event handlers for the connected game controller.

Developing all the code for menus, modes and linking controller input to the robot can be very time consuming when trying to test on the robot itself. But by having the modular structure we can create a virtual copy of our robot, or Digital Twin. By writing a mock copy of each module which interfaces to the actual hardware we can work on the code without the robot being present at all. I did a lot of the coding on a laptop using Raspbian x86 running in a VirtualBox VM. Coding anytime, anywhere. Only the laptop was needed to write, debug and test much of the code.

Just 3 modules (coloured blue above) needed mock versions to the written for the robot to be virtualised. Each of these mock modules has the same name and functions in it as the real version. But the code inside the functions captures the display object from pygame and renders a representation of itself onto the display.

Digital Twin: A virtual representation of the robot
(Background Mars image from Hubble Space Telescope. Credit: NASA)

The mock hardware interface module renders the shape of the robot, and shows the motor speeds and steering leg angles. The mock sensors module generates randomly varying distance readings and renders yellow triangles to indicate the sensor values. The rgb LED matrix mock module renders a representation of each LED matrix onto the screen. I also added an option to display numerical information to aid debugging and diagnosing problems. You can see the virtual robot running in this video clip I posted on Twitter:

The graphical representation of the digital twin of my robot and the sensor output was so useful for debugging issues that I moved it from the mock module into the main robot module. All the graphics slow down the main loop so that it does impair the responsiveness of the robot. So I made it possible to switch on and off via the controller. In normal running the display shows a static graphic of a solar panel, as you can see in this video clip.

(Post Pi Wars 2019 competition I published the full source code for my digital twin robot on github. You can play with my virtual robot using the code on the 'mock' branch. Full instructions and code here: )

Monday, 11 March 2019

First Fully Drive-able Build of my Mars Rover

My first prototype body to mount my rocker bogie arms onto made me realise I needed to better balance the weight of my robot over the main pivot axis. I also needed better clearance between the body and the steering legs. Then there was the challenge of where to put the rest of the electronics and the battery. I decided the battery was the thing to provide the weight to counter balance the body, and being a heavier item should also be located closer to the ground to make the robot more stable. So I drafted a design where the rear of the body was tapered giving less width. Enough to accommodate the battery but narrow enough to give sufficient clearance for the rear steering legs.

Early redesign of main body with narrower rear end

In attempting to wire up all the motors, and with the steering servo cables also needing routing into the chassis body, my robot was suddenly looking rather messy. I had deliberately made my prototypes from 3mm ply so they could be modified easily to iterate on the design. I explored ways to route the motor wires by getting out the drill.

Iterative design: wire routing!

Somebody commented on one of my Twitter posts asking where I planned to mount the Pi Noon attachment required for two of the challenges. This was not something I had considered up to this point. The challenge rules stated the attachment point had to be on the front of the robot, in the middle. My robot design at this point had nothing but thin air in that position! I wondered about making some sort of brace which attached to the two front rocker arms to hold it. This would lock the rocker (but the event would have a flat surface so not a big issue). Then I realised it was also needed for the Spirit of Curiosity challenge and this was expected to have terrain of varying difficulty. This was the challenge my robot was built for, and my robot was based on the namesake Mars rover of this challenge. I needed another plan. Looking at pictures of the real Mars Curiosity rover I realised that the rocker arm linking bar was positioned forwards of the main pivot axis, rather than behind as on my rover. I swapped mine to the same (you can see this difference between the original animated CAD model and the actual plywood first prototype in my earlier post).

Redesigned chassis shape with battery compartment and room for breakout electronics

Looking at my remodelled chassis it suddenly struck me that the back looked awfully like a front now, and what I had always imagined as the front was looking much more like the back (complete with USB and ethernet 'exhaust' ports). This now gave me a front panel to attach the Pi Noon attachment to as well. I extended the new front end to bring it level with the end of the rocker arms, and so my final rover shape was decided.

The new completed chassis built and ready for some road testing

Checking the A4 footprint of my new design

Finally I had something I could road test. The closest thing I had to some martian terrain was a load of rocks and fossils collected on family trips to the Jurassic coast.

Overall I was very pleased with how well my robot handled. It was very easy to control. The grip on steeper slopes was not enough, but I think for the Pi Wars challenges it will be sufficient. It was a little top heavy and prone to toppling over on more challenging obstacles. Here are some of the out-takes.

Monday, 18 February 2019

Pi Wars Robot Electrical Design

The fundamental components I needed for my raspberry Pi based robot were a Raspberry Pi board, a servo driver board and dual motor controllers. On top of this there would be various sensors and a camera. I decided early on I wanted some sort of display and buttons to control a menu system on the display to set the various modes of the robot for different challenges. The display I chose was the HyperPixel 4.0 touch screen display which Pimoroni had just released. This would give me a beautiful full colour display and the touch screen would enable me to use the screen itself to select menu items.

The next decision was how to power the robot. I had learned from other people of the problems with using a power source for the Pi shared with the motors. If the motors draw too much power then the supply to the Pi can dip, causing reboots or crashes. One way to avoid these problems is to provide a completely separate power supplies to the Pi and to the motors/servos. But this is not necessary provided the power supply can provide enough power for all components at their full loads. I decided to use a high discharge current LiPo battery. I planned to use UBECs (Universal Battery Eliminator Circuit) to eliminate the need for different battery voltages. I could supply 5V to the Raspberry Pi using one UBEC, and 6V to my motors and servos using a second UBEC. I already had experience using the cheap Hobbywing 3A 6V/5V switch mode UBEC for robots. These are readily available online (try eBay). I tend to buy 10 at a time from China so I have a stock of them in my parts box ready for projects.

Early prototype wiring to test the servo and motor drivers, powered by a LiPo battery and two UBECs

For the motor drivers, you need to choose some which can supply the voltage your motors require and handle the maximum current which the motors can pull. My robot was using 6V rated micro metal gearmotors with 1:50 ratio gear boxes. According to the listing on the Pimoroni website these have a stall current of 770mA. Stall current is the current the motors will draw if they are fully powered and the shaft is prevented from turning. Typically this can happen if the robot is trying to drive up too steep a slope or into an obstacle which prevents it moving, so all motors could draw this current at the same time. My design had them wired up as 2 pairs of 3 motors in parallel, so I needed a 6V supply to the motors and a maximum stall current of 3 x 770mA = 2.3A. I already had a pair of Adafruit DRV8871 motor driver breakout boards, capable of supplying up to 3.6A per board. The UBEC circuit can supply a steady 3A at 6V so I would need a UBEC per motor driver. I built a test circuit for a single motor and found it did not work. Reading the specifications of the motor driver board again I realised if needed a minimum of 6.5V input voltage. So my UBEC regulating the voltage down to 6V would not work.

Some discussions on Twitter led me to the decision to drive the motors directly off the battery voltage. This could be as high as 8.2V when fully charged, but seeing as the software would limit the motor power using PWM anyway I could set a limit to prevent the motors getting the full power of the battery. They would still be getting peaks of more than 6V during the on-cycle of the PWM signal, but the motors are not such sensitive components that this should be a problem, and I had been advised that these motors could be over-driven safely at these voltages. At a higher voltage I would have more speed, more torque but also a higher stall current. But I would not need a UBEC per motor driver now. The driver boards I had can supply up to 45V to motors, and up to 3.6A so this should work fine.

Next I looked up the HyperPixel touch screen board on the excellent website to find out which GPIO pins it used on the Raspberry Pi. The answer turned out to be all of them! But it did break out the software i2c bus so I still had the option to control i2c hardware from a Pi using this screen. I was already planning to drive the servos using an Adafruit 16 channel 12 bit PWM servo driver board which is an i2c device, so that should work. But I had no GPIO outputs available on the Pi to drive the motor driver boards. I discussed some options with Brian Corteil of Coretec Robotics at one of the monthly robot club sessions he organises at Cambridge Makespace. These included the following:
  • Use an Arduino to provide some additional PWM outputs
  • Use a second Raspberry Pi to connect sensors and drive the motors
  • Use an i2c GPIO extender breakout board
Then it occurred to me that what I needed to drive my motors were digital PWM outputs, and this is exactly what the 16 channel PWM board I was planning to use to drive my steering servos had in abundance. I built a test circuit on a breadboard to experiment with this. I made a mistake thinking I would drive the servos at 6V, because while the motor driver boards can drive motors at up to 45V, the logic inputs to the board are only rated up to 5.5V. My 6V PWM output damaged one of the boards and I had to replace it. My steering servos were plenty fast enough and strong enough using a 5V supply, so I switched the UBEC supplying power to the servos back to 5V.

The last piece of the puzzle was how to drive multiple laser time of flight distance sensors over i2c when the boards I had chosen (the VL53L1X breakout by Pimoroni) had a fixed address. I read it is possible to switch this address on power up, but this presumably required powering up each sensor board in turn, and that would require more digital outputs which I did not have. An easier solution was to use an i2c board which provides switchable i2c buses, and I chose the TCA9548A I2C MULTIPLEXER from Adafruit.

To connect up all my i2c devices, and supply power to the Raspberry Pi, I made a small power and i2c bus breakout board using strip-board. I built this with 5 pin connectors to match the Adafruit PWM board and Pimoroni range of i2c breakouts which all have 5 pin headers including an interrupt line.

i2c and power bus board

The UBEC supplying power to the Pi and screen was connected to this, and power supplied over the i2c V+ and GND lines to all components. You can see the complete wiring diagram below.

The electrical design for my robot (click to see larger version)

In order to mount the display on top of the robot, I soldered up a right angle GPIO connector using a Pimoroni Pico HAT Hacker board which enabled me to connect the display to the Raspberry Pi using a ribbon cable. I soldered a second 4 wire ribbon cable onto this connector to supply power to both the Pi and the display, and to connect the software i2c bus to my breakout bus board. I was relieved when I connected this all up and saw it working as intended.

Working display and Pi powered via the i2c bus and power breakout board

The next challenge was going to be how to fit all this electrical hardware and connecting wiring into my robot chassis.

Saturday, 16 February 2019

Designing the Main Chassis and Complete Rocker Bogie Assembly

Having built a pair of working prototype rocker bogie wheel assemblies, I turned my attention to the main body of the rover. Initially I just used a simple box shape, keeping the front of the chassis well back from the front steerable wheels to avoid collisions. The rear of the chassis had to overlap the area where the rear steerable wheels servo links came under the body in order to fit the top pivot for the linking bar assembly. But I now had a basic chassis design which enabled me to complete my CAD model and see a working mechanical model of the full rocker bogie suspension.

A rendered animation of the rocker bogie suspension

To avoid the rear wheel steering links colliding with the underside of the body, I modified the box so that the bottom was shorter than the total length of the body. This gave the servo steering links more clearance where they passed under the body. I made the front section of the body just long enough to fit in the Raspberry Pi 3 plus two additional support pillars to provide a second pair of holes for the main pivot bolts to pass through. This gave a more rigid main pivot axis assembly than if the bolts just passed through one piece of 3mm sheet material on each side.

I mounted the Raspberry Pi 3 board in the box, with the USB and Ethernet ports poking through a cut out. This was technically the first Raspberry Pi case I had ever designed. The rear of the box still needed to extend far enough back to support the linking bar assembly on the top. To allow this, the base of the box stepped up to a lesser depth at the rear.

The body design with a step up on the underside at the rear 
to allow the steering links to pass underneath the chassis

At this stage I was still pondering over how to build the linking bar assembly. I had modelled a bracket to hold the horizontal linking bar, which I was going to have to 3D print. I also needed to solve how to attach fittings to the ends of the cylindrical bar to link to the rocker arms. At about this time, somebody posted a picture of the NASA Mars Curiosity rover in a lab in reply to one of my progress posts on Twitter.

 Image Credit: NASA/JPL-Caltech

Up to this point I had not realised how large the real Mars Curiosity rover was! But I also noticed the linking bar was a flat bar, not a metal rod as I had modelled based on the JPL educational scale model project which inspired me to design a Pi Wars sized version of my own. That looked a lot easier to build. The picture also gave me another revelation. I did not need to mount the bar on the back of my rover. It could go in front of the main pivot axis of the body. This gave me more room as the body already extended further out in that direction to accommodate the Raspberry Pi. It also better distributed the weight of the body between the horizontal pivot axis and the top mounting point for the linking bar.

I now had a complete design worth building a prototype of. I laser cut it all from 3mm plywood because this was cheaper than plastic, easier to modify with small tools after cutting the pieces and I could re-purpose all the off-cuts and waste pieces as kindling to light the fire at home.

My first prototype, almost fully assembled (one rocker bogie arm is attached here)

This first mechanical prototype enabled me to verify that the design worked in practice. It also allowed me to test how much motion was possible in the rocker bogie arms before the rear steering legs collided with the underside of the chassis. I was not sure there was enough range of movement, and it also made me realise the weight was not well balanced around the main pivot axis of the chassis. I needed to think about how to solve these problems, and also work out how to fit all the electronics and a power source into the body.