Beginner Tutorial - Part 4: Interacting with the environment
From NXT++
Making a motor turn for the first time is fun, but a robot isn't really a robot until it can sense what's going on outside of the NXT brick. You'll find that reading from a sensor isn't all that hard to master. Before you read from any sensor, you have to let the NXT know what kind of sensor is in the port. This only has to be done once since the NXT remembers which sensors are in which ports. If you wanted to tell the NXT that there is a touch sensor in Port 1, you would put:
NXT::Sensor::SetTouch(&comm, IN_1);
You can find out about how to initialize other sensors here.
Retrieving the value of a sensor is a lot easier that initializing one. If you want to get the value of a touch, sound, or light sensor, you use NXT::Sensor::GetValue(). If you want to get the value of the sonar sensor, you use NXT::Sensor::GetSonarValue(). Here is an example of reading from both types of sensors:
int soundvolume = NXT::Sensor::GetValue(&comm, IN_2); int sonardistance = NXT::Sensor::GetSonarValue(&comm, IN_4);
An example program
Let's begin by implementing the content we just learned into a program. We'll have Tribot wait until the touch sensor is pressed and then start moving forward until there is an obstacle within 30 cm.
#include "NXT++.h"
int main()
{
Comm::NXTComm comm;
if(NXT::Open(&comm)) //initialize the NXT and continue if it succeeds
{
NXT::Sensor::SetTouch(&comm, IN_1);
NXT::Sensor::SetSonar(&comm, IN_4);
while(!NXT::Sensor::GetValue(&comm, IN_1)){}
NXT::Motor::SetForward(&comm, OUT_A, 50); //turn both motors on 50% power
NXT::Motor::SetForward(&comm, OUT_C, 50);
while(NXT::Sensor::GetSonarValue(&comm, IN_4) > 30){}
NXT::Motor::Stop(&comm, OUT_A, true); //stop both motors with no braking
NXT::Motor::Stop(&comm, OUT_C, true);
NXT::Close(&comm); //close the NXT
}
return 0;
}
Be sure to change Open() to OpenBT() if you want to use bluetooth. Otherwise, lift up Tribot so it doesn't run off the desk :).
