React when touched — Touch

no_virtual_ robotCannot be tested on an emulated robot, requires a real robot.

Goal

In this tutorial, we will use Pepper’s touch sensors. We will use the touch service, represented by the Touch interface.

Prerequisites

Before stepping in this tutorial, you should be familiar with the robot focus and robot lifecycle notions.

For further details, see: Mastering Focus & Robot lifecycle.

Let’s start a new project

  • Start a new project, let’s call it TouchSensorPepper.
  • Robotify it and make sure it implements the QiSDK & the Robot Life Cycle.

For further details, see: Creating a robot application.

Retrieving a sensor

Put the following code in the onRobotFocusGained method:

// Get the Touch service from the QiContext.
Touch touch = qiContext.getTouch();

The Touch interface allows you to get a touch sensor by its name. Here we will get and store Pepper’s head touch sensor, named “Head/Touch”.

Store the head TouchSensor in the MainActivity:

// Store the head touch sensor.
private TouchSensor headTouchSensor;

And add the following code to the onRobotFocusGained method:

// Get the head touch sensor.
headTouchSensor = touch.getSensor("Head/Touch");

For futher details, see: TouchSensor.

Listening to touch events

Now that we have access to a touch sensor, we will be able to detect when a physical touch is performed on it.

Each TouchSensor provides an TouchSensor.OnStateChangedListener that notifies you when the touch sensor’s state changes. This listener will be triggered each time someone touches the robot’s head, but also each time this physical contact is lost.

Add this listener in the onRobotFocusGained method:

// Add onStateChanged listener.
headTouchSensor.addOnStateChangedListener(touchState -> {
    Log.i(TAG, "Sensor " + (touchState.getTouched() ? "touched" : "released") + " at " + touchState.getTime());
});

The listener provides a TouchState instance, containing the sensor’s current state and the last time its state changed.

For futher details, see: TouchState.

Finally, remove the listener in the onRobotFocusLost method:

// Remove onStateChanged listeners.
if (headTouchSensor != null) {
    headTouchSensor.removeAllOnStateChangedListeners();
}

Let’s try it

github_icon The sources for this tutorial are available on GitHub.

Step Action

Install and run the application.

For further details, see: Running an application.

Choose “React when touched”.

Touch the top of Pepper’s head with your hand.

You should see the log “Sensor touched at <time>”.

If you withdraw your hand, you should see the log “Sensor released at <time>”.

https://developer.softbankrobotics.com/sites/default/files/repository/60_rst_pepper/public/source/_build/html/_images/touch.png

You are now able to use Pepper’s touch sensors.