Sharpening pencils

Let’s build a sharpener for our pencils using Lego EV3 and Kotlin. The idea is quite simple, we only need one sharpener, one motor and one touch sensor. Here are some pictures of my design:

The code is very simple:

package com.kotlinrobots.sharpener

import lejos.hardware.BrickFinder
import lejos.hardware.Keys
import lejos.hardware.motor.EV3LargeRegulatedMotor
import lejos.hardware.port.MotorPort
import lejos.hardware.port.SensorPort
import lejos.hardware.sensor.EV3TouchSensor

fun EV3TouchSensor.isTouched(): Boolean {
    val touchMode = this.touchMode
    val sample = FloatArray(touchMode.sampleSize())
    touchMode.fetchSample(sample, 0)
    return sample[0].toInt() == 1

fun main(args: Array<String>) {
    val motorA = EV3LargeRegulatedMotor(MotorPort.A)
    val touchSensor = EV3TouchSensor(SensorPort.S4)

    println("Insert your pencil")

    while (BrickFinder.getLocal().keys.buttons != Keys.ID_ESCAPE) {
        if (touchSensor.isTouched()) {
            motorA.speed = 1080
            motorA.rotate(360 * 5)


Note that we wrote an extension function for the touch sensor, so that we can know if the sensor was touched. This extension function makes our code more readable and easier to maintain.

This simple design can be extended, for example we can put the whole robot inside a box with a little hole where the user can insert a coin that touches the sensor which will make the motor rotate.

Here is a video of our sharpener in action:

Source code


Leave a Reply

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