Micro:bitArduinoMakeCodePythonC++BuildersAI inside

Sorting machine: teach it to see

Build a cardboard machine that sorts red and yellow beans. A gate lets one bean at a time into a tray, a camera looks, and the tray tips left or right. The eyes of the machine are a model you trained yourself. Choose the Micro:bit or the Arduino.

QR code to this pageScan to open

What you learn

13 things on the Builders path: open to see them

On the learning path: Builders with the Micro:bit or the Arduino: a machine with two servos, a trained model as its eyes, and words between the laptop and the board

Programming

  • One function tip(angle) for both directions
  • Decide with if and else if: red, yellow, or something else from story 2
  • Let one in, wait, ask, tip: a small state machine that starts again from story 4
  • Count the sorted beans and the tries from story 4
  • C++: Servo, SoftwareSerial and String in one sketchThe same program as Python, next to the blocks

Electronics

  • A servo turns to an angle and holds it: the tray, and from story 4 the gate

Thinking and making

  • Test each part alone first: the tray, then the model, then the whole machine
  • Is it the ramp, the model or the program? Change one thing at a time

AI in the loop

  • Train a model with red, yellow and empty, and test it with new beans from story 2
  • A colour rule or a trained model: try both in the AI link

Systems

  • Build a machine that works: a steep, smooth ramp and a gate that lets one bean through
  • Words between the laptop and the board, one per line; the board can ask with ? from story 2
  • Camera, decision, servo: a machine that sorts by itself from story 3

1See it in action

On screen: beans roll down the ramp, the gate lets one into the tray, the AI names its colour and the tray tips it into the red or the yellow box
One bean at a time story 4, on screen
Our first sorter in class: a cardboard ramp in front of a laptop camera, a trained model sorting red and yellow beans
Our first sorter it worked, but the beans jammed
The new design: a hopper, a ramp, a gate that lets one bean through, a tray under a camera, two boxes, a Micro:bit on a servo board
The new design a gate and a tray

2Parts you need

Micro:bit V2
Simple Servo board (Kitronik), 3 AA batteries
Arduino UNO
Bluetooth module HM-10
Breadboard
1 kΩ and 2 kΩ resistorsfrom story 2
FS90 servo (180°): the tray
A second FS90 servo: the gatefrom story 4

And: cardboard, tape (smooth, for the ramp), scissors, a white card, two small boxes, and a handful of red and yellow beans. A laptop with Chrome or Edge; a USB webcam on a small stand is best, because it can look down at the tray.

Use FS90 servos that turn to an angle. The FS90R spins round and round: it cannot hold the tray level.

3Learn the basics

Read these before you start, or come back when you need them.

examples car no car learns the pattern car: 92 % a new picture

Teach a computer with examples

Some jobs are easy to write as a rule: "if the distance is less than 15 cm, open the gate". Others are not: try writing a rule for "there is a car in this picture". Machine learning works the other way round: you show many examples of each kind, and the computer finds the pattern itself. That trained pattern is called a model.

Clear job with numbers: write a rule. Messy job with pictures, sounds or movements: train a model, then test it on examples it has never seen.

More: train your own model

Two free tools we use in class:

  • micro:bit CreateAI (in Chrome or Edge): the Micro:bit V2 learns movements. Record a few seconds of each move (swing, wave, still), train, test, then use the model in MakeCode.
  • Teachable Machine (Google, no account, the pictures stay on your computer): learns pictures, sounds or poses from the laptop camera or microphone. Make one class "car" and one "no car", record many examples of each, press Train, and try it with new things.
  • Many and different: film the toy car from all sides, near and far, in light and in shadow.
  • The other kind too: the model only learns "car" if it also sees many pictures without a car.
  • Test with new things: a different toy, a hand, an empty table. Where it fails, add examples.
  • It says how sure it is: "car: 92 %" is a guess, not a fact. Your program decides what to do with it.

Use toys and things, never photos of people. A model is only as good as its examples.

AI link your board red ⏎ ? ⏎ Bluetooth or a USB cable one word, then a new line

Send words to your board

A laptop and a board can talk in short words, like red. Each word ends with a new line (the Enter key): the board reads until the new line, so it knows the word is complete. The board can also ask: it sends ?, and the laptop answers with what it sees now.

One word per line. Read until the new line, then compare the whole word, like if word = "red".

More: Bluetooth, the USB cable, and the code
  • Micro:bit by Bluetooth: the bluetooth extension in MakeCode, bluetooth uart service at the start, and on bluetooth data received new line. In Project Settings choose No Pairing Required. It cannot be used together with the radio blocks.
  • Arduino by Bluetooth: an HM-10 module on two pins, read with SoftwareSerial. Its RXD pin wants 3.3 V: two resistors (1 kΩ and 2 kΩ) turn the Arduino's 5 V into about 3.3 V.
  • USB cable: the same words over the cable you already have, in Chrome or Edge on a computer.
SoftwareSerial bluetooth(4, 2);   // pin 4 hears the HM-10, pin 2 talks to it

void loop() {
  if (bluetooth.available()) {
    String word = bluetooth.readStringUntil('\n');
    word.trim();                     // away with spaces and the return at the end
    if (word == "red") {
      // do something for red
    }
  }
}

The AI link page sends the answer of a trained model as a word, or answers when the board asks with ?.

A small blue servo with its three wires

Servo

A servo is a small motor with gears and a little control chip. A 180° servo turns to an angle and stays there. A 360° servo (continuous) spins round, forwards or backwards: that one can drive a wheel.

Three wires: brown or black to GND, red to +, orange or yellow is the signal from a pin.

More: how a pin controls it

The board sends a short pulse 50 times a second. A pulse of 1 millisecond means 0°, 1.5 milliseconds 90°, 2 milliseconds 180°. A 360° servo reads the same pulses as a speed: 90 stands still, below 90 turns one way, above 90 the other way. Servos can take more current than a board pin gives, so a servo board like the Kitronik Simple Servo board gives them their own battery power.

The MakeCode blocks of this program
The same in Python
def on_button_pressed_a():
    pins.servo_write_pin(AnalogPin.P0, 0)
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    pins.servo_write_pin(AnalogPin.P0, 180)
input.on_button_pressed(Button.B, on_button_pressed_b)
#include <Servo.h>
Servo arm;                 // one Servo object per servo

void setup() {
  arm.attach(9);           // the signal wire on pin 9
}

void loop() {
  arm.write(0);            // to 0 degrees
  delay(1000);
  arm.write(180);          // to 180 degrees
  delay(1000);
}

State machine: what the program remembers

A sensor only tells you what is true now. To close a gate three seconds after a car has gone, the program must remember which state it is in: closed, open, or waiting to close. A program built that way is a state machine, and engineers draw it as a state chart: a box for each state, an arrow for each thing that makes it change.

Keep the state in a variable (like gateOpen), change it only when something happens, and act on it every loop.

More: state chart or flow chart, and counting something once

A flow chart shows the steps of the program one after the other. A state chart shows the states and what moves the machine from one to the next; it does not care how many lines of code that takes. Traffic lights, washing machines, lifts, games (playing, paused, game over) and robots are all state machines.

The same idea counts a car once. The loop runs ten times a second, so a car that stands in front of the sensor for two seconds is "near" twenty times. Remember what the sensor said last time: the car has driven past when it was near last time and is not near now. That is a tiny state machine too, with two states: no car, car.

bool carWasNear = false;      // the state of the sensor last time round
int cars = 0;

void loop() {
  bool near = sensor.measureDistanceCm() < 15;
  if (carWasNear && !near) {   // near before, not near now: a car drove past
    cars = cars + 1;
  }
  carWasNear = near;          // remember for the next loop
  delay(100);
}

The same gate as a flow chart: the steps, not the states. Draw both for your program and compare.

4Build it

Craft work: cut, fold, glue. It does not have to be perfect, only the parts the steps test must work. A Saturday of its own is fine.

The machine from the front: a hopper, a steep ramp, a gate on a servo above the ramp, a tray on a second servo in front of a white card, a camera looking down, a red box and a yellow box under the tray The gate up close: when it holds, the right pin stops the row of beans; when it tips, the left pin holds the next bean and only the first one rolls on

Build it from cardboard and tape. Make the ramp steep, about 35°, with smooth tape on it, and one and a half beans wide. The two pins of the gate are one bean apart. The tray sits flat on the servo arm; the white card behind it gives the camera a calm background.

Cardboard kit: print, cut, fold

Cardboard templates, page 1 of 4 Cardboard templates, page 2 of 4 Cardboard templates, page 3 of 4 Cardboard templates, page 4 of 4

Cardboard templates to print (PDF, 4 pages)

Print at 100 % (actual size), check the 5 cm line, glue the paper on the cardboard, then cut. How to make cardboard parts that fit

Also: a base board about 28 × 20 cm (the side of a box), toothpicks, smooth tape, glue stick; hot glue by the teacher.

The parts

  1. 1 Hopper thin card
  2. 2 Ramp thin card, smooth side up
  3. 3 Ramp support corrugated cardboard, make 2
  4. 4 Gate tower corrugated cardboard
  5. 5 Rocker corrugated cardboard
  6. 6 Tray stand corrugated cardboard
  7. 7 Tray thin card
  8. 8 White backdrop white card
  9. 9 Bean box thin card, make 2

Put it together: 14 steps

5Wire it

Calm work: power off, one wire at a time, check every hole twice. One wrong hole can stop the whole machine.

The Simple Servo board with the Micro:bit: the gate servo on the Servo 1 header, the tray servo on the Servo 2 header, the darkest wire on Ground

Servo 1 (pin P8) moves the gate, Servo 2 (pin P15) the tray. The darkest wire goes on Ground. Switch the board OFF while you plug in wires.

The HM-10's RXD pin wants 3.3 V: the 1 kΩ and the 2 kΩ resistor turn the 5 V from pin 2 into about 3.3 V. Its TXD goes straight to pin 4. Unplug the USB cable while you wire.

Circuit diagram: the same wiring, drawn the way engineers do

Every line is a wire and every part has its own symbol. The parts new in this story are blue. How to read a circuit diagram

Circuit diagram for story 1 Circuit diagram for story 2 Circuit diagram for story 3 Circuit diagram for story 4 Circuit diagram for story 1 Circuit diagram for story 2 Circuit diagram for story 3 Circuit diagram for story 4
Teacher check

Show your teacher the two resistors before the first power-up: without them the HM-10's RXD gets 5 V instead of 3.3 V.

You first

Plug in each servo yourself: the darkest wire on Ground. Switch the board off first, and check both plugs before you switch on.

6Try it

The sorter lab runs every story on screen. Make the room darker with the light slider and watch the model get unsure; change how sure it must be before it answers.

Open the sorter lab in a new tab

7Program it

You see the program for . Choose another story in the bar at the top of the page.

In MakeCode, the servo block servo write pin is under Advanced, then Pins. From story 2 you need the bluetooth extension, and in Project Settings (the gear) choose No Pairing Required.

In the Arduino IDE: type the code line by line, choose your board and port, then Upload. The Servo library comes with the IDE; SoftwareSerial too.

Story 1: Tip the trayservo angles

The MakeCode blocks of story 1
The same in Python
# Story 1: Tip the tray. Button A tips it left, button B right, then it comes back level.
# The tray sits on Servo 2 of the Simple Servo board (pin P15).
level = 90
left = 45
right = 135

def on_button_pressed_a():
    pins.servo_write_pin(AnalogPin.P15, left)
    basic.pause(600)
    pins.servo_write_pin(AnalogPin.P15, level)
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    pins.servo_write_pin(AnalogPin.P15, right)
    basic.pause(600)
    pins.servo_write_pin(AnalogPin.P15, level)
input.on_button_pressed(Button.B, on_button_pressed_b)

pins.servo_write_pin(AnalogPin.P15, level)

In MakeCode, switch from Blocks to Python at the top of the editor to type it yourself.

// Story 1: Tip the tray. Type left or right in the Serial Monitor (with "Newline" at the bottom).
#include <Servo.h>

const int trayPin = 9;
const int level = 90;
const int left = 45;
const int right = 135;
Servo tray;

void setup() {
  Serial.begin(9600);
  tray.attach(trayPin);
  tray.write(level);
  Serial.println("Type left or right");
}

void tip(int angle) {
  tray.write(angle);
  delay(600);
  tray.write(level);
}

void loop() {
  if (Serial.available()) {
    String word = Serial.readStringUntil('\n');
    word.trim();
    if (word == "left") {
      tip(left);
    } else if (word == "right") {
      tip(right);
    }
  }
}

Open the Serial Monitor, choose Newline at the bottom, and type left or right.

The tray is the machine's hand. A servo turns to the angle you give it: 90 is level, 45 tips it one way, 135 the other way. After a short wait it comes back level, ready for the next bean.

Your turn: put a bean on the tray and find the smallest tip that still lets it roll off.

You first

Today's know-how: angles. Find level, left and right on your own tray: no AI can measure them for you.

Story 2: Show what the AI seesa trained model

The MakeCode blocks of story 2
The same in Python
# Story 2: Show what the AI sees. The AI link sends a word by Bluetooth: red, yellow or empty.
word = ""

def on_bluetooth_connected():
    basic.show_icon(IconNames.YES)
bluetooth.on_bluetooth_connected(on_bluetooth_connected)

def on_bluetooth_disconnected():
    basic.show_icon(IconNames.NO)
bluetooth.on_bluetooth_disconnected(on_bluetooth_disconnected)

def on_uart_data_received():
    global word
    word = bluetooth.uart_read_until(serial.delimiters(Delimiters.NEW_LINE))
    if word == "red":
        basic.show_string("R")
    elif word == "yellow":
        basic.show_string("Y")
    else:
        basic.clear_screen()
bluetooth.on_uart_data_received(serial.delimiters(Delimiters.NEW_LINE),
    on_uart_data_received)

bluetooth.start_uart_service()
// Story 2: Show what the AI sees. The AI link sends a word through the HM-10: red, yellow or empty.
#include <SoftwareSerial.h>

SoftwareSerial bluetooth(4, 2);   // pin 4 hears the HM-10's TXD, pin 2 talks to its RXD

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  if (bluetooth.available()) {
    String word = bluetooth.readStringUntil('\n');
    word.trim();
    Serial.println(word);
    if (word == "red") {
      digitalWrite(LED_BUILTIN, HIGH);
    } else {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}

The AI link sends what the model sees as a word and a new line. The board reads until the new line and shows it: R or Y on the Micro:bit, the word in the Arduino's Serial Monitor and the L light for red.

Then teach it your beans

  1. Open Teachable Machine, make three classes: red, yellow, empty.
  2. Point the camera at the tray. For each class, record about 40 pictures: beans in different places and turned, and the empty tray.
  3. Train Model, then test it with new beans. Then Export Model, Upload my model, copy the link.
  4. In the AI link paste the link at 1 The model and press Open. Test again: now your model decides.

Your turn: hold a bean half in the picture. What does the model say, and how sure is it?

AI inside

The machine's eyes are a model you train in Teachable Machine (Google, free, no account; the pictures stay on your computer). Three classes: red, yellow and empty. How it works

  1. Record about 40 pictures of each class: beans in different places and turned, and the empty tray.
  2. Train, then test with beans the model has never seen.
  3. Upload the model, open the AI link, and connect your board.
You first

You decide what the model learns: good, varied pictures are your work. Bad pictures make a bad model.

Story 3: Let it decideif, else if

The MakeCode blocks of story 3
The same in Python
# Story 3: Let it decide. Red tips the tray left, yellow tips it right.
word = ""
level = 90
left = 45
right = 135
def tip(angle: number):
    pins.servo_write_pin(AnalogPin.P15, angle)
    basic.pause(600)
    pins.servo_write_pin(AnalogPin.P15, level)

def on_bluetooth_connected():
    basic.show_icon(IconNames.YES)
bluetooth.on_bluetooth_connected(on_bluetooth_connected)

def on_uart_data_received():
    global word
    word = bluetooth.uart_read_until(serial.delimiters(Delimiters.NEW_LINE))
    if word == "red":
        tip(left)
    elif word == "yellow":
        tip(right)
bluetooth.on_uart_data_received(serial.delimiters(Delimiters.NEW_LINE),
    on_uart_data_received)

bluetooth.start_uart_service()
pins.servo_write_pin(AnalogPin.P15, level)
// Story 3: Let it decide. Red tips the tray left, yellow tips it right.
#include <Servo.h>
#include <SoftwareSerial.h>

const int trayPin = 9;
const int level = 90;
const int left = 45;
const int right = 135;
Servo tray;
SoftwareSerial bluetooth(4, 2);   // pin 4 hears the HM-10's TXD, pin 2 talks to its RXD

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  tray.attach(trayPin);
  tray.write(level);
}

void tip(int angle) {
  tray.write(angle);
  delay(600);
  tray.write(level);
}

void loop() {
  if (bluetooth.available()) {
    String word = bluetooth.readStringUntil('\n');
    word.trim();
    Serial.println(word);
    if (word == "red") {
      tip(left);
    } else if (word == "yellow") {
      tip(right);
    }
  }
}

Now the word decides: red tips left, yellow tips right. Put the beans on the tray by hand. The AI link only sends a word when the model is sure enough and the answer stays the same for a few pictures.

Your turn: sort 20 beans. How many land in the wrong box?

Real world

Real sorting machines in factories sort rice, coffee beans and recycling with cameras and trained AI, many objects every second.

Story 4: One at a timea small state machine

The MakeCode blocks of story 4
The same in Python
# Story 4: One at a time. The gate (Servo 1, P8) lets one bean into the tray, the board asks the AI link "?",
# and the answer decides: tip left, tip right, or let in again when the tray is still empty.
word = ""
level = 90
left = 45
right = 135
hold = 60
open2 = 120
sorted2 = 0
tries = 0
def letOneIn():
    pins.servo_write_pin(AnalogPin.P8, open2)
    basic.pause(250)
    pins.servo_write_pin(AnalogPin.P8, hold)
    basic.pause(700)
    bluetooth.uart_write_line("?")
def tip(angle: number):
    global sorted2
    pins.servo_write_pin(AnalogPin.P15, angle)
    basic.pause(600)
    pins.servo_write_pin(AnalogPin.P15, level)
    basic.pause(400)
    sorted2 += 1
    basic.show_number(sorted2)

def on_bluetooth_connected():
    basic.show_icon(IconNames.YES)
bluetooth.on_bluetooth_connected(on_bluetooth_connected)

def on_uart_data_received():
    global word, tries
    word = bluetooth.uart_read_until(serial.delimiters(Delimiters.NEW_LINE))
    if word == "red":
        tries = 0
        tip(left)
        letOneIn()
    elif word == "yellow":
        tries = 0
        tip(right)
        letOneIn()
    elif word == "empty":
        tries += 1
        if tries < 3:
            letOneIn()
        else:
            basic.show_icon(IconNames.SAD)
    else:
        basic.pause(300)
        bluetooth.uart_write_line("?")
bluetooth.on_uart_data_received(serial.delimiters(Delimiters.NEW_LINE),
    on_uart_data_received)

def on_button_pressed_a():
    global tries
    tries = 0
    letOneIn()
input.on_button_pressed(Button.A, on_button_pressed_a)

bluetooth.start_uart_service()
pins.servo_write_pin(AnalogPin.P15, level)
pins.servo_write_pin(AnalogPin.P8, hold)
// Story 4: One at a time. The gate lets one bean into the tray, the Arduino asks the AI link "?",
// and the answer decides: tip left, tip right, or let in again when the tray is still empty.
#include <Servo.h>
#include <SoftwareSerial.h>

const int trayPin = 9;
const int gatePin = 6;
const int level = 90;
const int left = 45;
const int right = 135;
const int hold = 60;
const int open = 120;
Servo tray;
Servo gate;
SoftwareSerial bluetooth(4, 2);   // pin 4 hears the HM-10's TXD, pin 2 talks to its RXD
int sorted = 0;
int tries = 0;

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  tray.attach(trayPin);
  gate.attach(gatePin);
  tray.write(level);
  gate.write(hold);
  Serial.println("Type go to start");
}

void letOneIn() {
  gate.write(open);
  delay(250);
  gate.write(hold);
  delay(700);                        // let the bean roll in and lie still
  bluetooth.println("?");
}

void tip(int angle) {
  tray.write(angle);
  delay(600);
  tray.write(level);
  delay(400);
  sorted = sorted + 1;
  Serial.print("sorted: ");
  Serial.println(sorted);
}

void loop() {
  if (Serial.available()) {          // "go" in the Serial Monitor starts the machine
    String command = Serial.readStringUntil('\n');
    command.trim();
    if (command == "go") {
      tries = 0;
      letOneIn();
    }
  }
  if (bluetooth.available()) {
    String word = bluetooth.readStringUntil('\n');
    word.trim();
    if (word == "red") {
      tries = 0;
      tip(left);
      letOneIn();
    } else if (word == "yellow") {
      tries = 0;
      tip(right);
      letOneIn();
    } else if (word == "empty") {
      tries = tries + 1;
      if (tries < 3) {
        letOneIn();
      } else {
        Serial.println("Empty or stuck: check the hopper, then type go");
      }
    } else {                         // "unsure": look again
      delay(300);
      bluetooth.println("?");
    }
  }
}

Type go in the Serial Monitor to start.

The AI link answers only when the board asks. The machine works in steps: let one bean in, wait until it lies still, ask with ?, then tip and start again. If the tray is still empty, the gate moves again; after three tries it stops, because the hopper is empty or a bean is stuck.

Your turn: how many beans can it sort in one minute? Which wait can you make shorter?

You first

Draw the steps on paper first: let one in, wait, ask, tip, start again. That is your state machine.

8Challenges

Four challenges: a third box for green beans, counting the red and the yellow beans, the AI link set to 95 % sure, and a model trained in daylight tested under a desk lamp

Challenges

  • A third box: train green beans (or white ones) and give them their own place.
  • Count them: show how many red and how many yellow beans were sorted.
  • Never wrong: set the AI link to 95 % sure. What happens to the speed, and to the mistakes?

Explore further

  • Light test: train in daylight, then sort under a desk lamp. Add pictures where it fails.
  • A rule or a model? In the AI link, try No model: a colour rule. When is it as good as your model, and when not?
  • Faster: make the ramp, the gate and the tray quicker without more mistakes.
AI option

Beans still stick on the ramp? Ask an AI for three ways to make them roll more reliably. Test each one on your ramp and keep what works.

The question to ask
I built a cardboard ramp, about 35 degrees, where beans roll down one by one to a gate.
Sometimes a bean sticks and stops.
Give me 3 simple ways to make the beans roll more reliably, with cardboard, tape or paper, and how I can test each one.

9How others did it

Other kids solved the same task their own way. Made it your own way? Show your teacher.

Nothing here yet. Made it your own way? Show your teacher: it may end up here.

10Check what you learned

Before you leave. Your teacher picks some of these for you: answer out loud, draw on paper, or work with the person next to you. Some cards change with your story: now .

Answer it

Tap an answer: you see at once if it is right, and why

  1. gate.write(90) tells a 180° servo to …

  2. level = 90 and left = 80. What does the tray do when it tips left?

  3. Why does every word end with a new line?

  4. Why does the model also learn a class called empty?

  5. You teach a computer to see a toy car. Which examples help most?

  6. The AI link sends a word only when the model is 80 % sure. You set it to 50 %. What happens?

  7. The sorter asks "?" when the bean lies still, instead of hearing every answer. Why?

  8. True or false: the Arduino's pin 2 may go straight into the HM-10's RXD pin.

  9. An AI said: "Ask the AI link right after the gate opens, so the machine is faster." What goes wrong?

Predict, then try

Choose what will happen, then try it in the lab or on your board

  1. You trained the model in daylight. Now you sort under a desk lamp in the evening. What will happen?

  2. A bean sticks on the ramp. What does the machine do?

I can …

Tick what is true for you today. Your ticks stay on this computer.

Find the bug

A mistake we often see in class. What does the board do? Why? How do you fix it?

"I type left in the Serial Monitor and press Enter. The tray does not move. At the bottom of the Serial Monitor it says Both NL & CR."

#include <Servo.h>

const int level = 90;
const int left = 45;
const int right = 135;
Servo tray;

void setup() {
  Serial.begin(9600);
  tray.attach(9);
  tray.write(level);
}

void tip(int angle) {
  tray.write(angle);
  delay(600);
  tray.write(level);
}

void loop() {
  if (Serial.available()) {
    String word = Serial.readStringUntil('\n');
    if (word == "left") {
      tip(left);
    } else if (word == "right") {
      tip(right);
    }
  }
}
Need a hint?

Both NL & CR sends two invisible characters after your word. Which one does readStringUntil keep?

  • What makes the program work with any line ending?

"The AI link is connected to the HM-10 and sends red, yellow, red, but the Serial Monitor stays empty."

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(2, 4);

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
}

void loop() {
  if (bluetooth.available()) {
    String word = bluetooth.readStringUntil('\n');
    word.trim();
    Serial.println(word);
  }
}
Need a hint?

Follow the TXD wire of the HM-10: which Arduino pin does it go to? Which pin does SoftwareSerial listen on?

  • Which line is right for TXD on pin 4 and the divider on pin 2?

"The AI link says red, then yellow, and both times the tray tips left. The red box gets every bean."

The MakeCode blocks of this program
The same in Python
word = ""
level = 90
left = 45
right = 135
def tip(angle: number):
    pins.servo_write_pin(AnalogPin.P15, angle)
    basic.pause(600)
    pins.servo_write_pin(AnalogPin.P15, level)

def on_uart_data_received():
    global word
    word = bluetooth.uart_read_until(serial.delimiters(Delimiters.NEW_LINE))
    if word == "red":
        tip(left)
    elif word == "yellow":
        tip(left)
bluetooth.on_uart_data_received(serial.delimiters(Delimiters.NEW_LINE),
    on_uart_data_received)

bluetooth.start_uart_service()
pins.servo_write_pin(AnalogPin.P15, level)
Need a hint?

Read the two branches of the if: which angle does each one give to tip?

  • What should the yellow branch do?

Show it without AI

Two minutes, no screen help: the proof that the know-how is yours

  1. Set the AI link to 99 % sure. Say first what will happen, then try.
  2. Put something the model has never seen on the tray, like a white bean or a coin. What does it say, and why?
  3. Point to where your program decides between left and right.

Then: What did you hand over to AI today, and why? What did you keep for yourself?

Ask one question

Each of you asks one question about today

Ask your teacher or the class one question about today. Anything counts: a part, a block, a word on this page, something that went wrong, or where this is used in real life. There are no wrong questions, only questions nobody asked.

Start with: Why does …?   What happens if …?   How does a real … do it?   What does … mean?   Could I use this to …?

Poster to print (PDF)

Poster to print (PDF)