RemoteControl.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import lejos.nxt.*;
  2. import java.io.*;
  3. import lejos.nxt.comm.*;
  4. import lejos.util.Delay;
  5. import lejos.robotics.navigation.DifferentialPilot;
  6. public class RemoteControl {
  7. public static DataOutputStream dataOut;
  8. public static DataInputStream dataIn;
  9. public static NXTConnection Link;
  10. public static DifferentialPilot pilot;
  11. public static LightSensor sensor;
  12. public static int speed = 200, turnSpeed = 125, speedBuffer, speedControl;
  13. public static int commandValue,transmitReceived, lastCommand = 0;
  14. public static void main(String [] args) throws Exception {
  15. connect();
  16. pilot = new DifferentialPilot(5.6f, 11.2f, Motor.A, Motor.C, false);
  17. sensor = new LightSensor(SensorPort.S4) ;
  18. while(true){
  19. if (dataIn.available() > 0){
  20. byte x = dataIn.readByte();
  21. byte y = dataIn.readByte();
  22. if(checkCommand((int)x, (int)y)) {
  23. disconnect();
  24. break;
  25. }
  26. }
  27. }
  28. }
  29. public static boolean checkCommand(int cmd, int data) {
  30. System.out.println(data);
  31. try {
  32. switch (data) {
  33. case 0x1:
  34. pilot.travel(data);
  35. dataOut.writeChars("OK");
  36. break;
  37. case 0x2:
  38. pilot.rotate(data/255.0*360);
  39. dataOut.writeChars("OK");
  40. break;
  41. case 0x3:
  42. int v = sensor.readValue();
  43. dataOut.writeChars(String.valueOf(v));
  44. break;
  45. }
  46. dataOut.flush();
  47. } catch (IOException e) {
  48. }
  49. return false;
  50. }
  51. public static void connect() {
  52. System.out.println("Listening..");
  53. Link = Bluetooth.waitForConnection(0, NXTConnection.RAW);
  54. dataOut = Link.openDataOutputStream();
  55. dataIn = Link.openDataInputStream();
  56. }
  57. public static void disconnect() throws java.io.IOException {
  58. System.out.println("Closing...");
  59. dataOut.close();
  60. dataIn.close();
  61. USB.usbReset();
  62. System.exit(0);
  63. }
  64. }