Using Sensors

EV3 Basic is compatible with all the standard EV3 and NXT sensors with the probable exception of the NXT sound sensor. It is helpful (but not obligatory) to attach sensors to sensor ports on the EV3 according to the following convention:

       port 1 = touch, port 2 = gyro, port 3 = color, port 4 = infrared or ultrasonic.

As in the standard Lego EV3 software, many sensors can be used in different modes. Some information on the different modes can be found below, and more can be found in the sensor appendix. To set the desired mode for the sensor you are using, use Sensor.Setmode(port number, mode). For example, to set a color sensor on port 3 to mode 1 (ambient light intensity) use Sensor.SetMode(3, 1). It is important to always set the mode of the sensor before it is used.

You can obtain further guidance on the EV3 Basic sensor functions from the EV3 Basic Manual.

 

Touch sensor

The touch sensor is a simple switch and Sensor.ReadPercent(port number) returns a value of zero when the switch is not being pressed and 100 when it is being pressed.

Color Sensor

In EV3 Basic, the color sensor can be used to read:

In mode 0, the value returned by Sensor.ReadPercent(port number) is the percentage of the emitted light that is reflected back to the sensor. The maximum value that I can achieve for this sensor (by holding white paper a centimeter in front of the sensor) is about 86%. 

Mode 1, ambient light mode, returns zero when there is no ambient light and a maximum of 100 in bright light. Here is an example of code that will continuously display the ambient light level:

Sensor.SetMode(3,1)  'will set color sensor on port 3 to mode 1: ambient light

While "True"

    LCD.StopUpdate()    'don't update the screen until all the text is ready

    LCD.Clear()

    LCD.Text(1,30,20, 2, "Ambient")

    LCD.Text(1,40,40, 2, "light")

    LCD.Text(1,10,60, 2, "intensity:")

    LCD.Text(1,80,90, 2, Sensor.ReadPercent(3))

    LCD.Update()

    Program.Delay(100)  'pause 0.1 seconds

EndWhile

In mode 2 the color sensor will return a code number corresponding to which standard Lego color has been detected (0=unknown, 1=black, 2=blue, 3=green, 4=yellow, 5=red, 6=white, 7=brown). Since the sensor is returning a single value that is not a percentage you should use Sensor.ReadRawValue(port number, 0). Here is an example of code that will continuously display the standard color detected:

Sensor.SetMode(3,2)  'will set color sensor on port 3 to mode 2: detect color

While "True"

    LCD.StopUpdate()    'don't update the screen until all the text is ready

    LCD.Clear()

    code=Sensor.ReadRawValue(3, 0)

    LCD.Text(1,33,40, 2, "Color "+ code) 

    If code =0 Then

        col="UNKNOWN"

    ElseIf code =1 Then

        col="BLACK"

    ElseIf code =2 Then

        col="BLUE"

    ElseIf code =3 Then

        col="GREEN"

    ElseIf code =4 Then

        col="YELLOW"

    ElseIf code =5 Then

        col="RED"

    ElseIf code =6 Then

        col="WHITE"

    ElseIf code =7 then

        col="BROWN"

    EndIf 

    LCD.Text(1,33,75, 2, col)

    LCD.Update()

    Program.Delay(100)

EndWhile

It's much neater to use an array of color names rather than the If.. ElseIf.. EndIf structure:

Sensor.SetMode(3,2)

'Make an array containing the colors, matched to the array index values

Colors[0]="UNKNOWN"

Colors[1]="BLACK"

Colors[2]="BLUE"

Colors[3]="GREEN"

Colors[4]="YELLOW"

Colors[5]="RED"

Colors[6]="WHITE"

Colors[7]="BROWN"

While "True"

    LCD.StopUpdate()

    LCD.Clear()

    code=Sensor.ReadRawValue(3, 0)

    LCD.Text(1,33,40, 2, "Color "+ Code)

    LCD.Text(1,33,75, 2, Colors[Code])

    LCD.Update()

    Program.Delay(100)

EndWhile

Note that in mode 2 the color sensor is quite fussy about the colors. Genuine 'Lego colors' work best e.g. colored Lego pieces. The colors of other objects may not be recognised correctly even though they may seem obvious to you.

In the above program it is tempting to neatly create the array like this:

   Colors="0=UNKNOWN;1=BLACK;2=BLUE;3=GREEN;4=YELLOW;5=RED;6=WHITE;7=BROWN"

This method is fine for programs that will only ever run in 'PC mode' (directly within Small Basic) but it is not compatible with the EV3 Explorer compiler that tries to convert the Small Basic programs into the RBF format that the brick understands, should you wish to run the program in brick mode (from the brick's menu system). It's probably best to write programs that are compatible with both Small Basic and the EV3 Explorer compiler. See this page for more tips on this.

In mode 4 (not 3) the colour sensor will return RGB colour values for reflected light. This means you can measure any color, from a palette of millions, and are not limited to recognising one of 7 standard colours like you are in mode 2. This is a relatively advanced topic so it has been placed on a separate page.

Ultrasonic sensor 

Note that the ultrasonic sensor is not included in the home version of the EV3 robotics kit, though it is available for purchase as optional extra and the corresponding programming block can be downloaded free and incorporated into the home version of the Lego software. Since the ultrasonic sensor and the infra-red sensor both measure distance, the infra-red sensor can be substituted for the ultrasonic sensor in the lessons that follow (changes must also be made to the code - see the next section).

To obtain the distance reading from the ultrasound sensor, use Sensor.ReadRawValue(port number, 0). If the sensor is in mode 0 then the distance will be measured in mm (not cm). If the sensor is in mode 1 then the distance will be measured in tenths of an inch.

Here is a program that will continuously display the distance reading from the EV3 ultrasonic sensor in cm (or inches if you set the sensor to mode 1, i.e. change the highlighted number from 0 to 1).

'connect an EV3 ultrasound sensor to port 4

Sensor.SetMode(4,0) 'set port 4 to mode 0: distance in mm

While "True"

    LCD.StopUpdate() 'to prevent flickering, don't update LCD until text is ready

    LCD.Clear()

    LCD.Text(1,45,55,2,Sensor.ReadRawValue(4, 0)/10+" cm")  'convert mm to cm

    LCD.Update()

EndWhile

Infrared sensor

Note that the infrared sensor and beacon are not included in the education version of the EV3 robotics kit, but are available for purchase as optional extras. In EV3 Basic, the infra-red sensor can be used to measure:

By default, the sensor will work in mode 0 and Sensor.ReadRawValue(port, 0) will return the distance to an obstacle in centimeters (as in integer). It will not be very accurate since it estimates distance based only on the reflected light intensity. Distance estimates work better for light-colored objects. Here is a program that will continuously display the distance reading from the infrared sensor in cm:

'connect IR sensor to port 4

Sensor.SetMode(4,0)  'Set port 4 to mode 0: distance in cm

While "True"

    LCD.StopUpdate() 'to prevent flickering, don't update LCD until text is ready

    LCD.Clear()

    LCD.Text(1,45,55,2,Sensor.ReadPercent(4,0)+" cm")

    LCD.Update()

EndWhile

After switching to mode 1 with the command Sensor.SetMode(4,1) (for an IR sensor on port 4) the sensor will detect and return the direction and distance of an IR beacon. Since it is returning two values simultaneously you must use Sensor.ReadRaw(port number, 2). This will return an array of two elements in which element 0 is the direction and element 1 is the distance in cm. More help with this later...

After switching to mode 2, IR-REMOTE, with the command Sensor.SetMode(4,2) (for an IR sensor on port 4) the sensor will detect which buttons are being pressed on one or several IR beacons (remote controls) that are sending signals to the brick.

Gyro Sensor

The gyro sensor is included in the education version of the EV3 but not in the home version, though it's always possible to buy it separately.

It's very important to keep the gyro sensor and EV3 very still when connecting the cable and during start-up of the EV3, otherwise the gyro reading will continually wander away from the correct value. If you are not sure that this condition was met then simply unplug the sensor from its port and then reconnect it before running the program, while ensuring that the EV3 and the gyro sensor are perfectly still. You can use port view on the third tab of the brick menus to check whether the angle value is wandering even when the robot is still, but don't forget to exit port view before you try to run any EV3 Basic program.

Even if you are careful to ensure that the gyro sensor is still when it is started up, and even if you have verified in port view that the angle value is not wandering, you cannot expect perfect accuracy from the gyro sensor. How accurate is it? Visit this page to see the results of my testing. In a nutshell, my carefully-initialized gyro sensor usually measures counter-clockwise rotation fairly accurately, but usually underestimates clockwise rotations by about 2.5%. This may not sound like much, but these errors will accumulate, so for example if my sensor is twisted back and forth through 360° ten times then the error will be about 2.5% x 10 = 25% or 45°, which is really significant. I also noticed that errors were large for slow or jerky rotations, and smaller for faster, smoother rotations ('faster' meaning a full rotation in about 5 seconds). It's possible that my observations apply only to my gyro sensor, but it's also possible that they apply to all EV3 gyro sensors - if you need high accuracy from your sensor then you should do your own tests...

Mode 0 measures angles in degrees (relative to the gyro position when the program was started). The gyro sensor can be used to measure angles in either a horizontal or a vertical plane, according to how it is attached to the robot. The gyro sensor should be read with Sensor.ReadRawValue(port number, 0). In mode 0 the sensor supplies an array which contains a single element (element[0]) - see how that element is read in the code below.

Here is a simple program that continuously displays the angle in degrees through which the sensor has been rotated since the program was started (attach the gyro sensor to port 2):

'connect gyro sensor to port 2

Sensor.SetMode(2,0)  'measure angle in degrees

While "True"

    LCD.StopUpdate()    'don't update the screen until all the text is ready

    LCD.Clear()

    LCD.Text(1,35,50,2, Sensor.ReadRawValue(2,0) + " deg")

    LCD.Update()

    Program.Delay(100)  'pause 0.1 seconds

EndWhile

Mode 1 measures rate of change of angle in deg/s. This is a more advanced concept than angles themselves. If you set the mode to 1 instead of 0 in the above program (by changing the highlighted digit from 0 to 1) then the program will display rate of change of angle in deg/s. Don't forget to also change the units displayed on the LCD.

Motors as angle sensors

Just as in the official Lego EV3 software, the motors can also be used as angle sensors, detecting the angle to which they have moved by their own force or some eternal force. The command Motor.GetCount (port letter) will accurately measure (in degrees) all movements of a motor, even if the motor is driven by some external force while not actively running.

Third party sensors

Here's what the developer has to say: "Some other third party sensors may work as well, but again I can't test this myself. I think that if the manufacturer has successfully tested them with the Lego software, EV3 Basic should also be able to speak with them somehow (either using 'ReadRaw' or in the worst case with some custom made I2C communication programming), but this would probably be far beyond beginner level."

Demo Program

To get a better feel for percent and raw values, connect any standard NXT or EV3 sensor (except the NXT sound sensor?) to port 1 and run the SensorReading.sb file that was included in the Examples folder that was part of the installation of the EV3 extension. To make sense of that program, refer to the Sensor Appendix.

You can find other examples of EV3 Basic programs using sensors in the Robot Educator section (especially on the hardware page).