Robot
JavaScript
Compiler
Language
Simulator
Games
Examples
Download
Cheat sheet

Sensor Examples


Touch Sensor Value

Example:
// touchSensorValue() returns a number (0 or 1)
settled( 0 )
while true {
  if touchSensorValue() == 1
    setLED( 1 )
    drawText(40, 40, "On ", 2)
  else
    setLED( 0 )
    drawText(40, 40, "Off", 2)
  sleep(500)
}

Touch Sensor Pressed

Example:
// touchSensorPressed() returns a boolean value (true/false)
settled( 0 )
while true {
  if touchSensorPressed()
    setLED( 1 )
  else
    setLED( 0 )
  sleep(500)
}

Touch Sensor Event Handler

Example:
/* Use the touchSensor event handler to tell the robot when to stop the motors.
   In this example you should place a touchSensor at the front (or back) of the robot 
   so that when the robot bumps into an object, it will stop moving.  Think of a vacuum
   robot bumping into a chair, wall, or table. This program will use an event listener 
   to determine when the robot has bumped into something.
*/
okToMove=true                        // Create a Boolean variable to indicate when the robot should move
                                     // The robot will only move when okToMove is true.  Initially, the
                                     // robot will be allowed to move.  However, once it bumps into something,
                                     // this variable will be set to 'false' to stop the robot.

direction=-1                         // This variable controls the direction the robot travels.
                                     // The value of this variable will change between -1 and +1.

                                     // Create an event handler to handle the touchSensor events
function toHandleTheTouchSensor(e) { // A touchSensor event will occur when the touchSensor is pressed as well as when it is released.
  if e.value==0 okToMove=true        // If the touchSensor was released the event value will equal 0.
  if e.value==1 okToMove=false       // If the event value is 1, the touchSensor was pressed.  Set the okToMove to 'false'.
  drawText(10,10, e.value, 2)        // Show the event value on the LCD screen
}
                                     // Add an event listener to listen for touchSensor events and then handle them by passing the event to the callback function.
                                     // An event listener requires two parameters: 1) name of the event as a string and 2) identifier of the callback function (i.e., the event handler).
addEventListener('touchSensor',toHandleTheTouchSensor)

while true {                            // Enter an infinite loop
  syncMotors(B,C, 30*direction)      // Multiplying the power by the direction enables the robot to move either forward or backward
  waitHereWhile(okToMove)            // The Boolean variable okToMove is set in the handler function above.
  stopAllMotors()                    // If okToMove is false, then stop all motors.
  direction *= -1                    // This line will reverse the direction of the robot.
  waitHereUntil(okToMove)            // Wait here until it is OK to move.
}                                    // Repeat the loop.

Light Sensor Value

Example:
while true {
  clearScreen()
  drawText(10, 10, 'Value: '+lightSensorValue(), 2)
  sleep( 100 )
}

Light Sensor Percent

Example:
// lightSensorPct() 
// -----------------
// Returns the percent of light reflected from a surface

while true {
  clearScreen()
  drawText(0, 10, 'Percent '+lightSensorPct(), 2)
  // Graph it ///////////////
  rect( 20, 40, 100, 40 )                   // x, y, width, height
  fillRect( 21, 41, lightSensorPct(), 38 )  // x, y, width, height
  sleep( 100 )
}

Ambient Light

Example:
// ambientLight() 
// -----------------
// Returns the percent of ambient light detected by the sensor

while true {
  clearScreen()
  drawText(0, 10, 'Percent '+ambientLight(), 2)
  // Graph it ///////////////
  rect( 20, 40, 100, 40 )                 // x, y, width, height
  fillRect( 21, 41, ambientLight(), 38 )  // x, y, width, height
  sleep( 100 )
}

Color Sensor Value

Example:
// The colorSensorValue() function returns an object with three properties: r, g, b
// If defined as a literal, the object would look like:
//    colorSensorValueObject = { r: redValue, g: greenValue, b: blueValue }
//
// In the example below, the object is assigned to the variable 'x'
while true {
  x=colorSensorValue()                  // Assign the color sensor value object to the variable x
  drawText( 10, 10, 'Red:  ' + x.r, 2 ) // Display the value for red
  drawText( 10, 40, 'Green:' + x.g, 2 ) // Display the value for green
  drawText( 10, 70, 'Blue: ' + x.b, 2 ) // Display the value for blue
  sleep(500)                            // Wait for 500 milliseconds
  clearScreen()                         // Clear the screen
}                                       // Repeat

Gyro Sensor Value

Example:
while true {
  clearScreen()
  drawText(40, 30, gyroSensorValue(), 2)
  sleep( 100 )
}

Ultrasonic Sensor Value

Example:
forever {
  clearScreen()
  drawText(10, 10, ultrasonicSensorValue())
  sleep( 100 )
}

Resetting the Gyro Sensor

Example 1:
// This program displays the gyroSensorValue
// The value of the sensor is reset to zero
//  when you press the touch sensor
while true {
  clearScreen()
  drawText(10, 10, gyroSensorValue())
  sleep( 100 )
  if touchSensorPressed() { 
    setLED(2)
    resetGyroSensor()
    sleep(500)
    setLED(1)
  } 
}
Example 2:
// Usage
// The resetGyroSensor() function is useful if you need
// to make a turn.  You could reset the gyro before turning.
// Then check the gyro sensor as the robot is turning until
// a specific number of degrees has been met.

// Example:
resetGyroSensor()
setMotor( 2, 30 )

waitHereWhile abs(gyroSensorValue()) < 90

stopAllMotors()

Storing the Gyro Sensor

Example 1:
// Store the gyro sensor value in a variable
// Use a waitHereWhile statement
// Compare the absolute value of the difference between the sensor and the variable
// Wait while the absolute value of the difference is less than a set criteria
gyro=gyroSensorValue() // Store the gyro variable
syncMotors( B, C, 30, -200 ) // Start turning (point turn)
waitHereWhile abs(gyro-gyroSensorValue())<90 // Turn for 90 degrees

Graphing the Gyro Sensor Values

The gyro sensor measures rotation of the sensor.
When attached to the robot, this will effectively measure the rotation of the robot.
The return value is the number of degrees rotated starting when the robot was turned on.

There are three ways of resetting the sensor.

  1. turn the robot off / on
  2. disconnect the sensor from the robot (i.e., unplug the cable from the sensor or robot)
  3. use the resetGyroSensor() function
Tip: Prevent the sensor from being moved when turning on the robot or resetting the sensor. If the sensor detects movement as the robot is being turned on or the sensor reset, you may experience 'drift' in the sensor readings. 'Drift' in the sensor readings means that the values from the sensor are changing even though the sensor is not being moved.
There are three ways of handling 'drift' in the sensor.
  1. turn the robot off / on
  2. disconnect the sensor from the robot (i.e., unplug the cable from the sensor or robot)
  3. only use the sensor for short periods of time so that the effect of 'drift' is minimized
Example:
// Create a 'center' object to represent the center of the LCD screen.  
// Add a radius to be used in expressions for drawing the two circles and line.
center = { x: 89, y: 64, radius: 60 }
while true {
  gyro = gyroSensorValue()         // Assign the gyro sensor's value to a variable called 'gyro'.
                                   // The gyro variable will used in multiple places in the program.
  clearScreen()                    // Clear the screen
  drawText( center.x-30, center.y-10, gyro, 2) // Show the value of the gyro sensor
  // Graph it =============
  gyro += 90
  // 90 degrees are being added to the sensor value so that the indicators below will point to the
  //   top of the LCD display if the sensor value is zero (0).
  circle( center.x, center.y, center.radius )  // Draw a center circle
  x2=center.x+cosin(gyro)*center.radius        // Calculate an x2 coordinate.
  // The x2 coordinate will be center of circle offset by cosine of gyro times circle's radius
  y2=center.y-sin(gyro)*center.radius          // Calculate an y2 coordinate.
  // The y2 coordinage will be center of circle offset by sine of the gyro times circle's radius
  // Note that in calculating y2 the offset is subtracted from the coordinate because the y-scale
  // on the LCD display increases in values from top to bottom (i.e., 0 on the y axis is at the
  // top of the display)
  line( center.x, center.y, x2, y2 )  // line from the center to the edge of the circle
  fillCircle( x2, y2, 5 )  // Draw an indicator of the direction
  sleep( 100 )
  if touchSensorPressed() resetGyroSensor()    // Reset the sensor
}

To experiment with 'drift', run this program, point the robot at a fixed object (e.g., door or window or wall), then press the touch sensor to reset the gyro sensor. Watch the values shown and slowly rotate the robot clockwise or counter-clockwise to maintain a zero (0) value shown on the display. You are countering the drift in the sensor by turning the robot. Disconnect and reconnect the sensor. Press the touch sensor to reset the gyro. Is the drift in the same direction? At the same rate? Can you make the drift higher by moving the robot as you are reconnecting the sensor?

Turn Using the Gyro Sensor

Example:
// Multiple Turns using the Gyro
// ------------------------------
// This program uses the gyroSensor and two motors (on ports B and C)
// This program will demonstrate three different types of turns: point turn, swing turn, gradual turn
// A point turn is when the drive motors turn in opposite directions
// A swing turn is when one of the drive motors is active while the other drive motor is stopped
// A gradual turn is when both drive motors turn in the same direction--but one turns faster than the other
// The syncMotors() function can create a variety of turns
// A point turn is created if the turning ratio parameter is either 200 or -200
// A swing turn is created if the turning ratio parameter is either 100 or -100
// A gradual turn is created if the turning ratio parameter is between 0 and 100
// After starting the robot in a syncMotors() turn, reset the gyroSensor and check it in a while loop
//
// Point turn
syncMotors( B, C, 30, -200 )            // Start a point turn
resetGyroSensor()                       // Reset the sensor
while abs(gyroSensorValue()) < 90 {     // While the absolute value of the sensor is less than 90 degrees
  sleep(50)                             // Move for a period of time
}                                       // Repeat the loop

stopAllMotors()                         // Stop the motors
sleep(2000)                             //   for 2 seconds

// Swing turn
syncMotors( B, C, 30, 100 )             // Start a swing turn in the other direction
resetGyroSensor()                       // Reset the sensor
while abs(gyroSensorValue()) < 90 {     // While the absolute value of the sensor is less than 90 degrees
  sleep(50)                             // Move for a period of time
}                                       // Repeat the loop

stopAllMotors()                         // Stop the motors
sleep(2000)                             //   for 2 seconds

// Gradual turn
syncMotors( B, C, 30, -25 )             // Start a gradual turn
resetGyroSensor()                       // Reset the sensor
while abs(gyroSensorValue()) < 90 {     // While the absolute value of the sensor is less than 90 degrees
  sleep(50)                             // Move for a period of time
}                                       // Repeat the loop

Multiple Touch Sensors

Example:
// Multiple Sensors of the same type
// ===========================================
// The EV3 robot has 4 sensor ports.  The robot is able to examine these
// ports to see what sensors are connected to each.  When you connect
// a touch sensor to port 1, the robot is able to detect this and uses 
// this information to help interpret your program.  For example:
// If you have a touch sensor connected to port 1 and your program
// includes the following expression  "if(touchSensorValue()==0)" the
// robot will know that the touch sensor you are referring to is connected
// to port 1 and will use that sensor on that port to determine how to 
// evaluate the expression.  In other words, you do not need to specify
// the port number in your program.  The robot will know which port to use.
//
// The robot automatically checks its sensor ports at the start of each program.
// Your program will perform the same regardless of which port you have
// connected your sensor to.
//
// If, however, you have two or more touch sensors connected to the robot
// you will need to specify the port numbers for the sensors connected to
// the higher numbered ports.
// 
// The program below uses two touch sensors.  One of the touch sensors must
// be connected to port 4.  The other touch sensor can be connected to either
// port 1, 2, or 3.
//
setLED( 0 )
while true {
  if touchSensorValue() == 1 {         // Check the touch sensor on the lowest port number
    setLED( 1 )                        // Set LED to Green
  } else {
	  if touchSensorValue(4) == 1 {    // Check the touch sensor connected to port #4
	    setLED( 2 )                    // Set LED to Red
	  } else {                         // If neither touch sensor was pressed
	    setLED( 0 )                    // Turn LED off
	  }
  }
  sleep(10)
}

// Pressing one touch sensor will turn the LED to Green
// Pressing the other touch sensor will turn the LED to Red
//
// Can you modify the program so that the LED will show Red only if both touch sensors are pressed?
// Hint: You will need to use a boolean "and" to help check both conditions as in:
//    if( touchSensorValue() == 1 && touchSensorValue(4) == 1) { 
// or,
//   You could eliminate lines 29 and 30 as in:
/*--------
setLED( 0 )
while true {
  if touchSensorValue() == 1 {       // Check the touch sensor on the lowest port number
    if touchSensorValue(4) == 1 {    // Check the touch sensor connected to port #4
      setLED( 2 )                    // Set LED to Red
    } else {                         // If neither touch sensor was pressed
      setLED( 0 )                    // Turn LED off
    }
  }
  sleep(10)
}
--------*/