Recently I got the chance to give a bit of an introduction to python and physical computing on the Raspberry Pi to some kids so I thought a robot would be a fun thing to use as a demonstration. The aim was to get a working autonomous robot as simply as possible. Here’s the full write-up.

Hardware and Software setup

See my github page for details of the hardware, and python code to download:

Since I wanted to be able to use the robot outside, away from my router, I also configured the wifi to act as its own hotspot, as per my instructions here.

Walkthrough of python code

The code modules are comprised of the Motor Hat modules written by UKonline2000, which is designed to work with the motor control board. The file provides another layer of abstraction and simply allows you to call the functions to go straight or turn for a specified period of time. The file contains the main code loop, and the first iteration of the control script is very simple:

while True:
    if (distance < 30):

The distance is continually check at the start of each loop, using the getdistance() function, which uses the HC-SR04 ultrasonic sensor. If the distance to any object in front is less than 30cm, the robot will turn right for 0.22 seconds (approx 90 degrees at the speed set in Otherwise the robot will move forward for 0.1 seconds. This means the robot can explore anywhere (by going forward), but won’t crash into anything.

In an enclosed space, the robot continually run around inside it without bumping into the edges… in theory. In actually fact because the sensor is mounted head on, if the robot is facing towards the edges at an angle, it does not ‘see’ it:

The plan for the next iteration of the code is for the robot to “look” around to ensure it can see obstacles nearby and not just directly in front, and to find the longest straight run, and then go in that direction.