CS 141: Introduction to Programming
Lecture 19
Dr. Susan Bergin
Email:
[email protected]Room 2.108, Callan Building,
Department of Computer Science, NUI Maynooth
Robots Revisited
What do you need to know about the
RoboCar class?
You need to know how to create an instance of
a RoboCar
You need to know how to use the methods
covered in lectures and in labs
Moving on to the sensors
The NXT comes with a number of sensors and
were going to use the touch sensor.
The touch sensor should be plugged into Port 1 of
the NXT brick (see RoboCar API).
The method to check if the sensor has been
pressed is the following:
! robot.touchSensorIsPressed();
Using the touch sensor - example
if(touch sensor is pressed)!
{!
! // Do something e.g. reverse the robot!
}!
else!
{!
! // Do something different e.g. go Forward!
}!
Touch sensor in action..
public class TouchRobot {!
! public static void main(String[] args) !
! !
RoboCar robot = new RoboCar();!
! !
robot.setMotorSpeed(360);!
! !
!
! !
if(robot.touchSensorIsPressed())!
! !
{!
! !
robot.moveBackward(1000);!
! !
}!
! !
else!
! !
{!
! !
robot.moveForward(1000);!
! !
} !
}!
}!
But how do you get the program to continually check the selection statment?
{!
Fixing this with a loop
while(true)// creates an infinite loop!
{!
! ! if(robot.touchSensorIsPressed())!
! ! {!
! ! !
robot.moveBackward(1000);!
! ! }!
! ! else!
! ! {!
! ! !
robot.moveForward(1000);!
! ! }!
}!
Putting It Together
public class TouchRobotLoop1{!
! public static void main(String[] args) {!
! !
RoboCar robot = new RoboCar();!
! !
robot.setMotorSpeed(360);!
! !
while(true)!
! !
{!
! !
!
if ( robot.touchSensorIsPressed() )!
! !
!
{!
! !
!
!
robot.moveBackward(1000);!
! !
!
}!
! !
!
else!
! !
!
{!
! !
!
!
robot.moveForward(1000);!
! !
!
}!
! !
}!
! }!
}!
More methods
moveForwardForDistance(float distance)
Method to move RoboCar forward the specified
distance (approximately).
moveBackwardForDistance(float distance
Method to move RoboCar backward the
specified distance (approximately).
Something to think about..
How
would you solve this problem?
The robot needs to drive forward
for an unknown distance until it
hits an obstacle. It then needs to
navigate around the obstacle
(distances specified) and continue
again until it hits the red wall. Try
solving this on paper now!
What if you dont know in advance
how many obstacles there are
before the red wall but you know
that all the obstacles are all the
same size and the red wall is
much longer. Try solving this on
paper now!
Preparing for your January exam
Lets begin to work through an exam paper
together