Skip to main content

Color Sorter

The arm is mareklew's design: Simple robot arm, pick and place, SPIKE Prime lesson, MOC-178586 on Rebrickable. Its building instructions are sold there: buy the instructions from mareklew on Rebrickable. Build the arm from them, then come back here for its program.

Put a red, yellow, green or blue brick in front of the arm's Color Sensor, and the arm picks it up, turns to that color's side and lets it go. Then it comes back for the next one.

Add the Build HAT library first

BuildHat comes from a library, not from the language, so this code won't build without it. In IntelliJ, choose Tools | Nylon | Add Nylon Library… and pick build-hat. It brings the Raspberry Pi library with it, and adds one line to your project's build.markup.code:

(+dependencies : RepositoryDependency coordinate={"com.grandtheorem:build-hat:0.3.0"} /)

What you need​

The ports​

PortPlug in
AThe base motor, which turns the arm
BThe lift motor, which raises and lowers it
CThe gripper motor
DThe Color Sensor, where a brick waits to be picked up

1. Calibrate​

No two builds sit quite the same, so the numbers at the top of the program are one arm's. Run calibrate: in IntelliJ, click the run icon beside entrypoint calibrate(). The motors go free, and twice a second it prints where each motor's dial points and what the sensor sees, such as:

base 92 lift -170 grip -8 sees nothing

Turn the arm by hand to each place, and copy the number into its let at the top of the program:

  • PICK: the base, with the gripper over the sensor.
  • RED, YELLOW, GREEN and BLUE: the base over each color's drop.
  • DOWN: the lift, with the open gripper around a brick in front of the sensor.
  • UP: the lift, high enough to carry a brick clear of everything.
  • OPEN: the gripper, open.
  • CLOSED: the gripper, a few degrees past where its jaws first touch a brick. It holds there, so that's how hard it squeezes.

While it runs, hold each brick in front of the sensor, and check that sees names its color.

Then run gripTest. It opens the gripper, closes it, and opens it again, so you can check OPEN, CLOSED and GRIP_SPEED before the whole arm moves.

2. Sort​

Run sort, the default. It opens the gripper, lifts the arm, turns it over the sensor, and prints ready. Put a brick in front of the sensor: a second later the arm picks it up, drops it at its color's side, comes back, and prints how many it has sorted. A brick of any other color stays where it is.

The program​

import namespace grandtheorem.buildhat brings in everything the Build HAT library names, BuildHat, Port, Motor, ColorSensor and Color among them, without an import for each.

namespace demo.sorter

import grandtheorem.rpi.Pi
import namespace grandtheorem.buildhat
import namespace nylon.time

# A color-sorting arm on the Build HAT. Put a red, yellow, green or blue brick in front of the Color Sensor, and the
# arm picks it up, turns to that color's side and lets it go.
#
# The ports: the base on A, the lift on B, the gripper on C and the Color Sensor on D.
#
# The lift and the gripper hold wherever each run leaves them (`holdAfterRuns()`): the arm stays up against gravity,
# and the gripper keeps its grip on a brick, with no push or squeeze to tune.

The places to calibrate, and the speeds. These are one arm's numbers: yours come from calibrate.

# Where the base's dial points, -180 to 180 degrees: over the sensor, to pick a brick up, and over each color's
# drop. Run `calibrate`, turn the arm by hand to each place, and copy what it prints here.
let PICK = 90
let RED = 170
let YELLOW = -60
let GREEN = 4
let BLUE = 20

# Where the lift's dial points: down at the sensor, to grip a brick, and up, to carry it.
let DOWN = 137
let UP = -176

# Where the gripper's dial points: open, and closed on a brick. Run `calibrate`, and copy them here. Set CLOSED a few
# degrees past where the jaws first touch a brick: the gripper holds there, so that's how hard it squeezes.
let OPEN = -10
let CLOSED = 45

# How fast the gripper moves, 1 to 100.
let GRIP_SPEED = 30

# How fast the base turns and the lift moves, 1 to 100. 100 is five turns a second.
let TURN_SPEED = 7
let LIFT_SPEED = 3

sort is the default entry point. The lift and the gripper hold where each run leaves them, so the arm stays up and a gripped brick stays gripped. It gets ready over the sensor, then sorts until it's stopped.

# Sorts bricks until it's stopped.
entrypoint.default sort() {
let hat = BuildHat.connect(Pi)
let base = hat.motor(Port.A)
let lift = hat.motor(Port.B)
let gripper = hat.motor(Port.C)
let eye = hat.colorSensor(Port.D)
lift.holdAfterRuns()
gripper.holdAfterRuns()

release(gripper)
lift.runToPosition(UP, LIFT_SPEED)
base.runToPosition(PICK, TURN_SPEED)
println("ready: put a red, yellow, green or blue brick in front of the sensor")

var sorted = 0
while (true) {
if (sortOnce(base, lift, gripper, eye)) {
sorted = sorted + 1
println("sorted ${sorted}")
}
sleep(100.milliseconds())
}
}

gripTest checks the gripper on its own: open, closed, open again, then free.

# Opens, closes, then opens the gripper, to check OPEN, CLOSED and GRIP_SPEED. It holds each position as `sort` does,
# and lets go at the end.
entrypoint gripTest() {
let hat = BuildHat.connect(Pi)
let gripper = hat.motor(Port.C)
gripper.holdAfterRuns()
release(gripper)
sleep(1.seconds())
grip(gripper)
sleep(2.seconds())
release(gripper)
gripper.coast()
}

calibrate lets every motor turn freely, and prints where each dial points and what the sensor sees, twice a second.

# Prints where the base's, the lift's and the gripper's dials point, and what the sensor sees, twice a second, with the
# motors free to turn: move the arm by hand to each place, and copy the numbers into the lets above.
entrypoint calibrate() {
let hat = BuildHat.connect(Pi)
let base = hat.motor(Port.A)
let lift = hat.motor(Port.B)
let gripper = hat.motor(Port.C)
let eye = hat.colorSensor(Port.D)
base.coast()
lift.coast()
gripper.coast()
while (true) {
var sees = "nothing"
if (let color? = eye.color()) { sees = colorName(color) }
println("base ${dial(base)} lift ${dial(lift)} grip ${dial(gripper)} sees ${sees}")
sleep(500.milliseconds())
}
}

# Where a motor's dial points, or "?" when it doesn't answer.
let dial(motor: Motor): string {
if (let degrees? = motor.absolutePosition()) { return string(degrees) }
return "?"
}

One brick: down, grip, up, across to its color's side, let go, and back over the sensor.

# Sorts the brick in front of the sensor, if it's a color the arm sorts: picks it up, carries it to its color's
# side, lets it go, and comes back over the sensor. Answers whether it sorted one.
let sortOnce(base: Motor, lift: Motor, gripper: Motor, eye: ColorSensor): boolean {
if (let color? = steadyColor(eye)) {
if (sorts(color)) {
println("a ${colorName(color)} brick")
sleep(1.seconds())
lift.runToPosition(DOWN, LIFT_SPEED)
grip(gripper)
lift.runToPosition(UP, LIFT_SPEED)
base.runToPosition(sideFor(color), TURN_SPEED)
release(gripper)
base.runToPosition(PICK, TURN_SPEED)
return true
}
}
return false
}

# Closes the gripper on a brick. It holds there, squeezing the brick, until it's opened.
let grip(gripper: Motor) {
gripper.runToPosition(CLOSED, GRIP_SPEED)
}

# Opens the gripper.
let release(gripper: Motor) {
gripper.runToPosition(OPEN, GRIP_SPEED)
}

A brick still being put down can read as several colors, so a color counts only once three readings in a row agree.

# The color in front of the sensor once three readings in a row agree, or none: a brick still being put down can
# read as several colors.
let steadyColor(eye: ColorSensor): Color? {
if (let first? = eye.color()) {
var agreeing = 1
while (agreeing < 3) {
sleep(100.milliseconds())
if (let next? = eye.color()) {
if (number(next) != number(first)) { return none }
} else {
return none
}
agreeing = agreeing + 1
}
return first
}
return none
}

match! makes the compiler check that every color is handled, so each of these lists all eleven of LEGO's colors.

# Whether the arm sorts a brick of `color`: red, yellow, green and blue.
let sorts(color: Color): boolean = match!(color) {
Color.Red -> true
Color.Yellow -> true
Color.Green -> true
Color.Blue -> true
Color.Black -> false
Color.Pink -> false
Color.Lilac -> false
Color.Cyan -> false
Color.Turquoise -> false
Color.Orange -> false
Color.White -> false
}

# Where the base turns to drop a brick of `color`, one it sorts.
let sideFor(color: Color): i32 = match!(color) {
Color.Red -> RED
Color.Yellow -> YELLOW
Color.Green -> GREEN
Color.Blue -> BLUE
Color.Black -> PICK
Color.Pink -> PICK
Color.Lilac -> PICK
Color.Cyan -> PICK
Color.Turquoise -> PICK
Color.Orange -> PICK
Color.White -> PICK
}

# A number for each color, to compare two readings.
let number(color: Color): i32 = match!(color) {
Color.Black -> 0
Color.Pink -> 1
Color.Lilac -> 2
Color.Blue -> 3
Color.Cyan -> 4
Color.Turquoise -> 5
Color.Green -> 6
Color.Yellow -> 7
Color.Orange -> 8
Color.Red -> 9
Color.White -> 10
}

# A color's name, to print.
let colorName(color: Color): string = match!(color) {
Color.Black -> "black"
Color.Pink -> "pink"
Color.Lilac -> "lilac"
Color.Blue -> "blue"
Color.Cyan -> "cyan"
Color.Turquoise -> "turquoise"
Color.Green -> "green"
Color.Yellow -> "yellow"
Color.Orange -> "orange"
Color.Red -> "red"
Color.White -> "white"
}

Good to know​

The lift and the gripper hold the whole time sort runs. Holding draws power, as Hold a position says.

Too fast or too slow: change TURN_SPEED and LIFT_SPEED, from 1 to 100, where 100 is five turns a second.

Boards: every board on Boards.