Instructional Material: Exercise: Using a Touch Sensor

Lets look a using sensors by starting with the simple touch sensor. This is simply a button that can be used to signal your code that something has happened by pushing the button. We will add a REV Robotics Touch Sensor to the robot and plug it into digital port 0-1 on the Expansion Hub. We modify our controller phone configuration to identify digital port 1 as a  Rev Touch Sensor and name it touch_sensor. Why did we use port 1 instead of 0? It has to do with the way the ports are wired. More about that here.

We will take the earlier DriveCircle exercise and modify it to use the touch sensor to determine when to stop driving:

Copy and paste this code into a new OpMode class called DriveCircleTouch and demonstrate your robot driving in a circle. It should keep driving until you press the touch sensor button or 5 seconds pass. Note the use of the while loop to run the robot while watching for 5 seconds to pass and also watching for the touch sensor button press. The TouchSensor isPressed() function returns false when not pressed and true when pressed. For us to continue to run while not pressed, we invert the result of the isPressed() function by preceeding it with the ! (invert) operator.

When using the REV Robotics touch sensor, you can also access the sensor as a generic digital (input) device. Go into the controller configuration and change the touch_sensor device type from REV Touch Sensor to Digital Device. Here is the above code sample modified to use the REV sensor configured as a digital input:

Connecting the touch sensor as a digital input or some other digital device to the REV Hub has some nuances. Be sure to read the discussion here.

 

Material Type: 
Lab Activity
Education Level: 
Middle School
High School
Focus Subject: 
Computing / Computer Science
Robotics Software
HW Platform: 
Tetrix
SW Platform: 
Java
Interactivity Style: 
Mixed
Audience: 
Learner