Tutorial: Using Sensors with LEGO™ Robots

This tutorial helps explain how to use sensors on Robots in Quorum.

Using Sensors with Robots in Quorum

In this tutorial, we will become more familiar with the sensors on the robots. We will explain the similarities and differences between the different types of sensors and cover these topics:

  • General sensor information
  • The color sensor
  • The infrared sensor
  • The ultrasonic sensor
  • The touch sensor

General Sensor Information

Sensors are used to gather information about the environment and relay it to the program. Although they collect different types of information, they are all connected to the brick in the same way. Each sensor needs to be plugged into any one of the four ports on the bottom side of the brick, labeled 1 through 4. Remember the motors are plugged into ports A, B, C and D on the top.

Just like the motors, it is important to remember which sensor is connected to which port, because the program needs to know where to send and receive information. In order to use actions with a sensor, the port for that sensor must be specified in the program.

Color Sensor

The color sensor's primary function is to detect colors, however, it can also detect light levels and measure the reflectivity of objects. The color sensor works by projecting a red, white, or blue light.

In order to detect colors, the color sensor projects its white light and measures the red, green, and blue levels. Based on its reading, the sensor can return text to the program representing the color it read. The colors that it can return to the program are "red", "green", "blue", "yellow", "brown", "white", and "black". If the sensor cannot read a color, it will return the text "none" to the program. The range of the color sensor is fairly short, so when measuring colors be sure to have the color to read located within a few centimeters of the sensor.

The actions of the color sensor are:
  • SetPort
  • GetColor
  • GetRedGreenBlueLevels
  • GetLightLevel
  • GetReflectionLevel
  • IsLightOn
  • SetLightColor
  • GetLightColor

The following is an example program that uses the ColorSensor class, playing different tones based on the color it reads:

use Libraries.Robots.Lego.ColorSensor
use Libraries.Robots.Lego.Motor
use Libraries.Robots.Lego.Utility
use Libraries.Robots.Lego.Sound

ColorSensor colorSensor
Motor motor
Utility utility
Sound sound

//SetPort is always called first on any sensor object
colorSensor:SetPort(4) 

//have the motors connected to ports A and B move the robot
//this command will run the motors until the program terminates or
//a Stop() action is issued to the motor.
motor:RotateForward("A")
motor:RotateForward("B")

//"text" holds the text value returned by the GetColor() action
text color = "" 
repeat 5 times
//attempt to read a color
    color = colorSensor:GetColor() 
    if color = "none"
        sound:Buzz()
    elseif color = "black"
        sound:PlayTone(20, 250)
    elseif color = "white"
        sound:PlayTone(60, 250)
    elseif color = "brown"
        sound:PlayTone(180, 250)
    elseif color = "red"
        sound:PlayTone(540, 250)
    elseif color = "green"
        sound:PlayTone(1620, 250)
    elseif color = "blue"
        sound:PlayTone(4860, 250)
    elseif color = "yellow"
        sound:PlayTone(14580, 250)
    end

    //lets the robot move a little before checking the color again
    utility:DelayMilliseconds(500)
end

For an in-depth look at each action in the ColorSensor class as well as how they can be used, see the ColorSensor reference page.

Infrared Sensor

The infrared sensor is used for two things:

  • measuring the distance of objects
  • interacting with the remote control

You can use the infrared sensor to find the distance between the robot and an object to prevent the robot from running into the object or to change the robot's behavior. While certain factors can affect the sensor's measurement range, the maximum reliable range to measure distance is around 40 to 50 centimeters. When the sensor returns the distance to the program, it returns an integer approximating the number of centimeters between the sensor and the object.

The remote control, also called a beacon, can be used with the infrared sensor to remotely issue commands to the robot. The infrared sensor is also capable of tracking relative distance and position of the remote control. All remote communication takes place over one of four channels, which are assigned in the program and changed on the remote. The center of the remote control has a red vertical slider that can be used to change the remote's channel. Above the slider is a circular hole that shows the channel number based on the slider's position. When the slider is at the top-most position, the remote is using channel 1, and when the slider is at the bottom-most position, the remote is using channel 4. When calling an action that uses remote interaction in a program, it will always require that we pass the channel we want to use as a parameter.

When tracking a remote with the infrared sensor, the reliable range is roughly 100 centimeters between the two points of connection. When the sensor is tracking the distance or direction of a remote, it is important that the remote sends out its signals. The large button on the top of the remote toggles the remote's signal on and off, while the smaller buttons on the left and right side of the remote only send out a signal while they are pressed. If the sensor is able to detect a remote, it will return the distance in centimeters (up to 100) as well as the angle (in degrees), of the remote with respect to the sensor. The angle will range from -180 to 180, where negative values represent that the remote is on the left side of the sensor, positive values are on the right side of the sensor, and a value of 0 means the remote is straight ahead. When using the GetRemoteDirection() action, be sure to keep in mind that the sensor's margin of error is around 7 degrees.

When retrieving commands from the remote, the sensor can read the following button combinations, listed by their corresponding integer return value:

Remote Control Button Mappings: Sensor Return Values and Corresponding Button Combinations
Return ValueButton
1TOP-LEFT
2BOTTOM-LEFT
3TOP-RIGHT
4BOTTOM-RIGHT
5TOP-LEFT+TOP-RIGHT
6TOP-LEFT+BOTTOM-RIGHT
7BOTTOM-LEFT+TOP-RIGHT
8BOTTOM-LEFT+BOTTOM-RIGHT
9TOP CENTER
10BOTTOM-LEFT + TOP-LEFT
11TOP-RIGHT + BOTTOM-RIGHT

There are five actions for the infrared sensor:

  • SetPort
  • GetDistance
  • GetRemoteDistance
  • GetRemoteDirection
  • GetRemoteCommand

Following is an example program that uses the infrared sensor to control the movement of a robot as long as it isn't about to run into anything:

use Libraries.Robots.Lego.InfraredSensor
use Libraries.Robots.Lego.Motor
use Libraries.Robots.Lego.Utility
use Libraries.Robots.Lego.Screen

InfraredSensor infraredSensor
Motor motor
Utility utility
Screen screen

integer command = 0
//register the infrared sensor connected to port 4 of the robot
infraredSensor:SetPort(4)
//IMPORTANT: this loop will continue until the program is stopped manually by pressing the center+down
//buttons on the brick simultaneously
repeat while true
    if infraredSensor:GetDistance() < 25
        screen:Output("Object nearby.", 0)
        sound:Buzz()
    else
        screen:Clear()
        //determines what button was pressed on the remote using channel 1
        command = infraredSensor:GetRemoteCommand(1)
        if command = 1
           //top-left button pressed, move forward
            motor:SetSpeed("B", 480)
            motor:SetSpeed("C", 480)
            motor:RotateForward("B")
            motor:RotateForward("C")
        elseif command = 2
            //bottom-left button pressed, move backward
            motor:SetSpeed("B", 480)
            motor:SetSpeed("C", 480)
            motor:RotateBackward("B")
            motor:RotateBackward("C")
        elseif command = 3
            //top-right button pressed, move right
            motor:SetSpeed("B", 480)
            motor:SetSpeed("C", 480)
            motor:Stop("B")
            motor:RotateForward("C")
        elseif command = 4
            //bottom-right button pressed, move left
            motor:SetSpeed("B", 480)
            motor:SetSpeed("C", 480)
            motor:Stop("C")
            motor:RotateForward("B")
        else
            motor:Stop("B")
            motor:Stop("C")
        end
    end
end

For an in-depth look at each action in the InfraredSensor class as well as how they can be used, see the InfraredSensor reference page..

Ultrasonic Sensor

The ultrasonic sensor is used solely to measure the distance of objects. It has a much further range for measuring distances than the infrared sensor, nearly three times as much, and is reliable up to around 1.5 meters. When measuring distances, the sensor will return a number to the program indicating how many meters away an object is.

The UltrasonicSensor class consists of two actions:

  • SetPort
  • GetDistance

The following is an example of how the ultrasonic sensor can be used by a moving robot to avoid a collision with an object:

use Libraries.Robots.Lego.UltrasonicSensor
use Libraries.Robots.Lego.Motor
use Libraries.Robots.Lego.Utility

UltrasonicSensor ultrasonicSensor
Motor motorController
Utility delayController

//tell the robot which port the sensor is plugged into
ultrasonicSensor:SetPort(1)

motor:RotateForward("B")
repeat 5 times
    motor:RotateForward("C")
    //allow the robot to continue going forward while no object within 1.25 meters exists in its path
    repeat while ultrasonicSensor:GetDistance() > 1.25
        //check the sensor every 20 milliseconds
        delayController:DelayMilliseconds(20)
    end
    //have the robot turn by stopping just one of its motors for a second
    motor:Stop("C")
    delayController:DelayMilliseconds(1000)
end

For an in-depth look at the actions in the UltrasonicSensor class as well as how they can be used, see the UltrasonicSensor reference page..

Touch Sensor

The touch sensor is much less complex than most of the other sensors and only used to determine whether its protruding button is pressed in or not. This button is most commonly used by a person to change what the robot is doing.

The TouchSensor class consists of two actions:

  • SetPort
  • IsPressed

The following is an example of how the touch sensor can be used to change a robot's behavior when it is pressed:

use Libraries.Robots.Lego.TouchSensor
use Libraries.Robots.Lego.Motor
use Libraries.Robots.Lego.Sound
use Libraries.Robots.Lego.Utility

TouchSensor touchSensor
Motor motor
Sound sound
Utility utility

//tell the program that the touch sensor connected to port 3 of the robot
touchSensor:SetPort(3)

//two motors used to move the robot, connected to ports B and C
motor:SetSpeed(motor:MOTOR_B, 720)
motor:SetSpeed(motor:MOTOR_C, 720) 
repeat 10 times
    if touchSensor:IsPressed()
        sound:Beep()
        motor:RotateForward(motor:MOTOR_B)
        motor:RotateBackward(motor:MOTOR_C)
    else
        sound:Buzz()
        motor:RotateBackward(motor:MOTOR_B)
        motor:RotateForward(motor:MOTOR_C)
    end
    //wait one second to start the loop and check the button status again.
    motor:Stop("C")
    delayController:DelayMilliseconds(1000)
end

For an in-depth look at the TouchSensor class as well as how they can be used, see the TouchSensor reference page..

Gyro Sensor

The gyro sensor is used to measure the orientation of the robot and the rate at which its orientation is changing. For best results, the gyro sensor should be secured firmly to the robot while in use.

The gyro sensor class consists of four actions:

  • SetPort
  • GetRotation
  • GetRotationSpeed
  • Reset

The following is an example of how the gyro sensor can be used to keep the robot moving in a straight line:

use Libraries.Robots.Lego.Motor
use Libraries.Robots.Lego.GyroSensor
use Libraries.Robots.Lego.Utility

class Main
    action Main
        Motor motor
        GyroSensor gyro
        Utility utility

        gyro:SetPort(2)

        motor:SetSpeed(motor:MOTOR_B, 50)
        motor:SetSpeed(motor:MOTOR_C, 50)

        // the motor on the right
        motor:RotateForward(motor:MOTOR_B)
        // the motor on the left
        motor:RotateForward(motor:MOTOR_C)

        repeat while true
            // if robot is moving too far to the right, adjust speed of motor
            // C (the left motor) to keep the robot moving in a straight line
            if gyro:GetRotation() < -1.0
                motor:Stop(motor:MOTOR_C)
                motor:SetSpeed(motor:MOTOR_C, motor:GetSpeed(motor:MOTOR_C) + 5)
                motor:RotateForward(motor:MOTOR_C)
            // if robot is moving too far to the left, adjust speed of motor
            // B (the right motor) to keep the robot moving in a straight line
            elseif gyro:GetRotation() > 1.0
                motor:Stop(motor:MOTOR_B)
                motor:SetSpeed(motor:MOTOR_B, motor:GetSpeed(motor:MOTOR_B) + 5)
                motor:RotateForward(motor:MOTOR_B)
            end
            // wait a second before sampling the angle again
            utility:DelayMilliseconds(1000)
        end
    end
end

For an in-depth look at the GyroSensor class as well as how they can be used, see the GyroSensor reference page..

Additional Information

  • A common cause of program crashes is forgetting to set the port of a sensor before using it.

  • Class constants can be used to refer to sensors, specifically when passing them to an action.
  • For documentation on the Color Sensor class, see here.

  • For documentation on the Infrared Sensor class, see here.

  • For documentation on the Touch Sensor class, see here.

Next Tutorial

In the next tutorial, we will discuss Buttons, which describes how to use lego buttons.