Cannot 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
For further details, see: Creating a robot application.
Put the following code in the onRobotFocusGained
method:
// Get the Touch service from the QiContext.
val touch: Touch = qiContext.touch
// 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 var headTouchSensor: TouchSensor? = null
// 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")
// Get the head touch sensor.
headTouchSensor = touch.getSensor("Head/Touch");
For futher details, see: TouchSensor.
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 " + (if (touchState.touched) "touched" else "released") + " ${touchState.time}")
}
// 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.
headTouchSensor?.removeAllOnStateChangedListeners()
// Remove onStateChanged listeners.
if (headTouchSensor != null) {
headTouchSensor.removeAllOnStateChangedListeners();
}
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>”. |
You are now able to use Pepper’s touch sensors.