## Coding BBC Micro:bit using MicroPython

I have previously used the excellent Introduction the Computer Science course and have recently discovered that there is a MicroPython version, maintained by Carl Lyman. I wanted to cover the ACARA Digital Technologies Knowledge and Understanding: *Investigate the role of hardware and software in managing, controlling and securing the movement of and access to data in networked digital systems* (ACTDIK034). For this, I found another excellent resource: Networking with Microbit.

I have mashed all these resources together, to pitch at a year 9 class in 2020. I will only see this class for 140 minutes a week, so I have compressed quite a lot. If I have an extra 70 mins, then I would have included all innovation mini-projects and completed the Networking book. If you have the time, I would add these in. The assessment is an exam, because I do projects all the rest of the year and I need them to be prepared for exams in 11-12. Hopefully, you can figure out where I have mapped the exit ticket questions in by the WALTS.

Enjoy!

Microbit with MicroPython, PDF or OneNote

These and more goodies can be accessed here: https://www.throughtheclassroomdoor.com/dt-resources/

## PID Controlled Line Follower Robot

In most of the Robotics competitions that I have been involved with, there is a need to follow a line. There are many strategies that can be employed to follow a line, but Proportional-Integral-Derivative (PID) control is the most effective. It can also be the most disengaging because of the mathematics involved.

**Proportional Control**

A good place to start is with Proportional Control and build from there. Proportional Control is where change made to the steering is proportional to, or directly related to, the robot’s distance from the edge of the line or the Target Path.

We control the Bot by changing the value for the turn ratio (or steering value) as the Bot moves forward in a forever loop. The turn ratio is calculated by:

turnRatio = error * gainValue

The error is the difference between where we want the robot to be and where it actually is: targetValue – colourSensor reading

The targetValue is the threshold value on the Target Path. We calculate this by averaging the reading from the colour sensor over white and the reading over the black. ie. targetValue = white reading + black reading / 2.

The gainValue determines how quickly the robot reacts to changes in the error value. A smaller gainValue makes the robot move slowly, which means that it might not react quickly enough for tight turns, but results in less side-to-side motion when the line is fairly straight. A larger gainValue means a quicker reaction but can cause jerkier motion. Selecting the gainValue is called tuning the controller and usually involves some trial and error.

This gives us:

turnRatio = (targetValue – colourSensor) * gainValue

**Psuedocode**

on start

targetValue = 40

gainValue = 0.7

Repeat forever

turnRatio = (targetValue – colourSensor) * gainValue

Steer motors D + A TurnRatio speed 25

**Proportional-Integral-Derivative (PID) controlled Bot**

Now we are going to fine tune by incorporating the gain or response to Integral (total errors) and Derivative (rate of) errors. This Proportional-Integral-Derivative (PID) control.

The **Proportional** part measures the deviation from the Target Path (error), so our turnRatio = (target reflected light – actual reflected light) x Kp. The Kp is a fine tuning value or gain (or how quickly the robot reacts to changes in the Error value) that we can arrive at with some experimentation.

The **Derivative** is the rate of errors (deviations from the Target Path) and, therefore, we can predict what the next error will be and can fix the steering proactively : derivative = error – last error

The **Integral** is the sum of all the error (deviations from the Target Path) values and can help determine if the steering fixes from the derivative have helped keep the bot on the Target Path. Looking at the sum of all past errors can detect when steering corrections are not working: integral = integral + errors

Proportional [Error] = How bad is the situation now?

Integral = Have my past fixes helped fix things?

Derivative = How is the situation changing?

PID control = combine the error, integral and derivative values to decide how to steer the robot

The fine tuning is incorporated into the turn ratio (to steer back towards the line) and our aim is to reduce oscillation (rate of turning in and out) as much as possible and achieve smooth line following. The formula for the turn ratio value we need to repeat is:

turnRatio = (error * Kp) + (integral * Ki) + (derivative * Kd)

Where:

error = Target – Ns, where the Target is the threshold value (black+white/2) and Ns is the normalised [turn into a number between 0-100] colour sensor value

Kp = proportional gain or how quickly the robot reacts to changes in the Error value

integral = sum of the errors or sum of how far away from the Target we are

Ki = integral gain

derivative = rate of errors or rate of how far away from target we are

Kd = derivative gain or fine tuning value for derivative or error rate.

So, as the Bot moves along the edge of the line, it will steer into and out of the line based on the value of the turnRatio. Depending on how we adjust the Kp, Ki and Kd values, the steering should be minimal and produce less oscillation.

**Pseudocode**

on start

Power = 50 // default speed

Target = 58 // threshold calculated by white level + black level /2 (theoretically centre of black line)

Kp = 0.7 // proportional gain. The Gain value determines how quickly the robot reacts to changes in the Error value

Kd = 12 // gain or response to errors for the derivative. Kd needs to be set at the beginning of the program to a value you arrive at

after some experimentation

Ki = 0.05 // gain or response to errors for the integral

lastError = 0 //for tracking errors

integral = 0 // add up errors

Direction = -1 //are you left of the line or right of the line

min = 5 // light reading on black

max = 65 // light reading on white

steer motors Power // start moving Bot

forever

Ns = 100 * (raw sensor reading – min) / (max – min) // normalise light sensor reading for calculations

error = Target – Ns // calculate error

derivative = error – lastError // calculate the derivative or rate of errors

lastError = error // update lastError

integral = 0.5 * integral + error // calculate the new integral or total errors

turnRatio = Direction * (Kp * Error + Kd * Derivative + Ki * Integral ) // make final turn ratio calculation

steer motors turnRatio Power // turn slightly according to calculations

**Tuning Strategy 1**

The most common way to tune your PID constants is trial and error. Disable everything but the proportional part (set the other constants to zero). Adjust just the proportional constant until robot follows the line well. Then, enable the integral and adjust until it provides good performance on a range of lines. Finally, enable the derivative and adjust until you are satisfied with the line following.

When enabling each segment, here are some good numbers to start with for the constants:

P: 1.0 adjust by ±0.5 initially and ±0.1 for fine tuning

I: 0.05 adjust by ±0.01 initial and ±0.005 for fine tuning

D: 1.0 adjust by ±0.5 initially and ±0.1 for fine tuning

**Tuning Strategy 2**

1. Set the Power to 50.

2. Start with Kd and Ki at 0 and Kp at 1. With our target at 60, this will make the Steering value change between -60 and 40 as the normalized sensor reading goes between 0 and 100.

3. Start by testing with just a straight line. A Kp of 1 is likely too large and will cause noticeable oscillation. Progressively reduce Kp by 0.05 until the robot follows a line with no side-to-side movement or only small movement to one side of the edge.

4. Progressively increase Ki by 0.01 until the robot follows the edge of a straight line with no oscillation. If the robot does not constantly drift to one side, you may be able to leave Ki at 0. Be aware that setting Ki too high (above 0.05) will cause the oscillations to grow bigger.

5. Now test the program on a line with curves. Increase the Power variable until the robot is unable to make the turn.

6. Progressively increase Kd by 1 until the robot can traverse the entire path.

The much longer version of this is here: https://wp.me/a8n5jj-fu

## RoboCup Soccer with EV3 and MakeCode Mindstorms

Next year, Lego Mindstorms coding will be no more; to be replaced by a scratch-like coding environment. My students are about to finish the First Lego League season and will be looking for the next challenge to work on. Now is a good time to transition them to a block-based coding environment. As the new Mindstorms is not available, I am going with MakeCode.

I have already made RoboCup Rescue Line resources available as PDF or OneNote. I have just finished whipping something up for RoboCup Soccer. It comes with the caveat that I have not beta-tested it with students and my logic may be all over the place. Also, the MakeCode API does not have blocks for the HiTechnic sensors, so LEGO Infared and Gyro sensors are used instead. This has resulted in significantly different solution algorithms. The resource is available as PDF or OneNote.

## STEM Invention with SAM Labs

I recently was lent a SAM Labs kit from MTA, so I decided to design a unit for an upcoming STEM class. I normally beta test these with students before I blog, but I couldn’t wait to make these available, and maybe you can give it a go.

The unit is wide open, with a lot of work in having students identifying a problem that needs to be solved or how life can be improved with some kind of IOT device. While this has always been my dream, its probably only for the brave and perhaps a hackathon in a restricted context is wiser.

I have also used Blockly via Workbench, which is starting to complement Makecode nicely. The standard environment for SAM Labs is their proprietary App which is a node-based coding environment.

The unit also uses Agile project management and team problem solving for all those 21st Century soft skills. These are also mapped into both the Digital and Design Technologies syllibi.

The unit can be downloaded as a Onenote or PDF and other goodies are available on the DigTech page.

Enjoy!

## Embedded Systems with MakeCode, CircuitPython and the Circuit Playground Express

## The BBC Micro:bit

For younger students, we use BBC Micro:bit to introduce them to programming and connecting the physical inputs and outputs needed with embedded systems. We do this mainly based on the learning resources we have access to, which generally target younger students. Otherwise, the BBC Micro:bit is very comparable to the Circuit Playground Express.

## The Circuit Playground Express (CPX)

The reason we use the CPX for years 9-10 is because Adafruit provides such good support via MakeCode , CircuitPython and their own learning system. Their projects are also a little more advanced and challenging.

## From Blocks to Text

I like to have students design and prototype their algorithms in a block-based programming environment. I find this to be easier and more efficient when cycling through several iterations of solution design and testing. It’s also a more visual and coherent experience. With CPX, I start with MakeCode and have students implement their final solutions in CircuitPython. Interestingly, Adafruit went with MakeCode and not Edublocks. Edublocks uses python, while MakeCode uses Javascript?

## The Unit

Embedded-SystemsNOTE: The latest updates, revisions and OneNote files may be found in the **DigTech Resources** menu link above

## Resources for Learning with the BBC Micro:bit

[ “BBC micro:bit” by luipermom is licensed under CC BY-NC-SA 2.0 ]

Resources for Learning with the BBC Microbit