In both codes, Motor B is steering, Motor C powers the drive wheels.
Here is the car's code:
- Code: Select all
import lejos.nxt.*;
import lejos.nxt.comm.*;
import java.io.*;
public class DriveSteer //program on the car
{
public static void main(String [] args)
throws Exception
{
BTConnection mastercomm = Bluetooth.waitForConnection(); //wait for connection
DataInputStream btin = mastercomm.openDataInputStream(); //bluetooth input
SteerThread strthrd = new SteerThread(btin); //steering thread
DriveThread drvthrd = new DriveThread(btin); //driving thread
strthrd.start(); //start receiving the steering
drvthrd.start(); //start reveiving the driving
btin.close(); //close connectionn
mastercomm.close(); //close
}
}
class SteerThread //steering
extends Thread
implements Runnable
{
protected DataInputStream btin;
SteerThread(DataInputStream btinArg){btin = btinArg;} //copy bluetooth input
public void run()
{
int steer = 0;
while(!Button.ENTER.isPressed()) //while the orange button isn't pressed
{
try
{
steer = btin.readInt(); //try to receive
}
catch(IOException e)
{
//stay still
}
Motor.B.rotateTo(steer); //act upon reception
}
try
{
btin.close(); //try to close
}
catch(IOException e)
{
//nothing
}
}
}
class DriveThread //driving
extends Thread
implements Runnable
{
protected DataInputStream btin;
DriveThread(DataInputStream btinArg) {btin = btinArg;} //copy input stream
public void run()
{
int drive = 0;
while(!Button.ENTER.isPressed()) //while orange button has not been pressed
{
try
{
drive = btin.readInt(); //try to receive
}
catch(IOException e)
{
drive = 0; //stay still
}
MotorPort.C.controlMotor(drive,1); //act upon reception
}
try
{
btin.close(); //try to close
}
catch(IOException e)
{
//nothing
}
}
}
Here is the code for the controller:
- Code: Select all
import java.io.IOException;
import lejos.nxt.*;
import lejos.nxt.comm.*;
import java.io.*;
import javax.bluetooth.*;
public class ControlSteer
{
public static void main(String[] args)
throws Exception
{
Motor.B.flt();
Motor.C.flt();
String slavename;
slavename = "Joshamfn"; //change based on driving NXT Brick
RemoteDevice slave = Bluetooth.getKnownDevice(slavename); //find slave
if(slave != null) //if device exists
{
BTConnection slavecomm = Bluetooth.connect(slave); //connect to slave
if(slavecomm != null) //if connection successful
{
DataOutputStream btout = slavecomm.openDataOutputStream(); //initialize command stream
while(!Button.ENTER.isPressed()) //command continuously
{
btout.writeInt(-(Motor.B.getTachoCount()/4));
btout.writeInt(Motor.C.getTachoCount());
btout.flush(); //send commands
}
btout.close(); //close
slavecomm.close(); //close
}
}
}
}
