Sonar.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import java.io.DataInputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import lejos.nxt.Motor;
  5. import lejos.nxt.SensorPort;
  6. import lejos.nxt.Sound;
  7. import lejos.nxt.UltrasonicSensor;
  8. import lejos.nxt.comm.BTConnection;
  9. import lejos.nxt.comm.Bluetooth;
  10. import lejos.robotics.navigation.DifferentialPilot;
  11. class Scanner extends Thread {
  12. DataOutputStream output;
  13. boolean run;
  14. public boolean scann;
  15. Scanner(DataOutputStream output) {
  16. super();
  17. this.output = output;
  18. run = true;
  19. scann = false;
  20. }
  21. public void scann() {
  22. scann = true;
  23. }
  24. public void stop() {
  25. run = false;
  26. }
  27. public void run() {
  28. UltrasonicSensor sensor = new UltrasonicSensor(SensorPort.S1);
  29. while (run) {
  30. if (scann) {
  31. int distance = sensor.getDistance();
  32. try {
  33. output.write('@');
  34. output.write(distance);
  35. output.flush();
  36. scann = false;
  37. Thread.yield();
  38. } catch (IOException e) {
  39. }
  40. }
  41. }
  42. }
  43. }
  44. public class Sonar {
  45. public static final byte EXIT = 10;
  46. public static final byte READ = 2;
  47. public static final byte MOVE = 3;
  48. public static void main(String[] args) throws Exception {
  49. BTConnection btc = Bluetooth.waitForConnection();
  50. // USBConnection btc = USB.waitForConnection();
  51. DataInputStream input = btc.openDataInputStream();
  52. DataOutputStream output = btc.openDataOutputStream();
  53. DifferentialPilot pilot = new DifferentialPilot(5.6f, 11.2f, Motor.B, Motor.A, false);
  54. pilot.setRotateSpeed(5);
  55. pilot.setTravelSpeed(20);
  56. Scanner scan = new Scanner(output);
  57. scan.start();
  58. int input_byte;
  59. boolean run = true;
  60. Sound.twoBeeps();
  61. while (run) {
  62. if (input.available() <= 0) {
  63. Thread.yield();
  64. continue;
  65. }
  66. input_byte = input.readByte();
  67. System.out.println(input_byte);
  68. switch (input_byte) {
  69. case READ:
  70. scan.scann();
  71. break;
  72. case EXIT:
  73. run = false;
  74. break;
  75. case MOVE:
  76. float d = input.readFloat();
  77. pilot.travel(d);
  78. break;
  79. default:
  80. pilot.stop();
  81. break;
  82. }
  83. }
  84. Sound.beep();
  85. scan.stop();
  86. scan.join();
  87. }
  88. }