Color Sensor in action : Safe box

In a previous post we learned how to read colors using color sensor. Now, let’s create a more interesting robot with everything we have learned so far. I came up with this idea of having a safe box built with Lego that can only be opened with a password made up of sequence of colors. Here are some pictures of the robot:

The main idea is that the box can only be opened after the user enters a sequence of colors, in other words, it can only be opened after the color sensor reads 3 colors. For this example, I chose this sequence: RED-WHITE-RED.

Here is the code:

package com.kotlinrobots.safebox

import lejos.hardware.BrickFinder
import lejos.hardware.Sound
import lejos.hardware.motor.EV3LargeRegulatedMotor
import lejos.hardware.port.MotorPort
import lejos.hardware.port.SensorPort
import lejos.hardware.sensor.EV3ColorSensor
import lejos.robotics.Color

fun main(args: Array<String>) {
    val motorA = EV3LargeRegulatedMotor(MotorPort.A)
    val colorSensor = EV3ColorSensor(SensorPort.S1)

    var valid = 0
    val password = listOf(Color.RED, Color.WHITE, Color.RED)

    println("Please enter your password: ")
    for (i in 0..2) {
        if (colorSensor.readColorId() == password[i]) {
        } else {

    if (valid == 3) {
        motorA.speed = 360
        println("Your password is OK!")
    } else {
        println("Your password is wrong.")


    println("Press any key to exit...")
  1. As usual, we need one variable for the motor and one for the color sensor.
  2. listOf is used to create a list of elements. Read more here.
  3. Sound is used to make the brick emit sounds

There is also an extension function named readColorId() that was moved to another file:

package com.kotlinrobots.safebox

import lejos.hardware.sensor.EV3ColorSensor

fun EV3ColorSensor.readColorId(): Int {
    val colorIDMode = this.colorIDMode
    var sample = FloatArray(colorIDMode.sampleSize())
    colorIDMode.fetchSample(sample, 0)
    return sample.get(0).toInt();

Finally, if and only if the three entered colors match the password, we rotate the motor and open the safe box, otherwise we emit a buzz sound.

Here is the video of our safe box in action:

Source code


Leave a Reply

Your email address will not be published. Required fields are marked *