### START IMPORTS ###
import time     # import the time library for the sleep function
import brickpi3 # import the BrickPi3 drivers

# Create an instance of the BrickPi3 class. BP will be the BrickPi3 object.
BP = brickpi3.BrickPi3()

# Configure for a touch sensor. If an EV3 touch sensor is connected, it will be configured for EV3 touch, otherwise it'll configured for NXT touch.
BP.set_sensor_type(BP.PORT_1, BP.SENSOR_TYPE.TOUCH)
### END IMPORTS ###

### START CODE HERE ###
# Print instruction to guide the user for play.
print("Press touch sensor on port 1 to run motors")
# Set a variable "value" to save the touch sensor status.
value = 0

# Read the touch sensor status in port 1 and pass when encounter SensorError.
while not value:
    try:
        value = BP.get_sensor(BP.PORT_1)
    except brickpi3.SensorError:
        pass
        
# Use while loop to control motor speed by touch sensor status. 
while True:    
    # BP.get_sensor returns the sensor value.
    value = BP.get_sensor(BP.PORT_1)
     
    # Control motor speed by touch sensor status.
    if value:
        power = 40
    else:
        power = 0
        
    # Set port A motor speed in "power" value.
    BP.set_motor_power(BP.PORT_A, power)
    #BP.set_motor_position(BP.PORT_A, power)
    # Delay for 0.02 seconds (20ms) to reduce the Raspberry Pi CPU load.
    time.sleep(0.02)
### END CODE HERE ###