Domanda

Conosci qualcuno, come costruire una connessione Bluetooth tra Android e Lego-Mindstorm-NXT? La connessione tra due NXT funziona bene.Ma l'altro tipo di connessione non piace così facile. Sto lavorando con il firmware Lejos 0.85 e gli strumenti SDK Android (2.2 Froyo).

È stato utile?

Soluzione

Quindi l'ho risolto e mostrerò tutto come funziona, perché ho visto che molte persone hanno problemi con questo.

La classe include 4 funzioni:

    .
  • Abilita Bluetooth se non abilitato prima -> Enablebt ()
  • Connetti a 2 NXT -> ConnectTonxts ()
  • Scrivi il messaggio a uno degli NXT -> WriteMessage (Byte Msg, String NXT)
  • Leggi il messaggio da uno degli NXT -> ReadMessage (stringa NXT)

    Ecco il codice per il dispositivo Android (BT_COMM.Java):

    package de.joen.android.CubeScan;
    
    
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.UUID;
    
    
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    
    import android.util.Log;
    
    public class BT_Comm {
    
      //Target NXTs for communication
      final String nxt2 = "00:16:53:04:52:3A";
      final String nxt1 = "00:16:53:07:AA:F6";
    
      BluetoothAdapter localAdapter;
      BluetoothSocket socket_nxt1, socket_nxt2;
      boolean success = false;
    
      // Enables Bluetooth if not enabled
      public void enableBT(){
        localAdapter = BluetoothAdapter.getDefaultAdapter();
        // If Bluetooth not enable then do it
        if (!localAdapter.isEnabled()) {
          localAdapter.enable();
          while(!(localAdapter.isEnabled()));
        }
      }
    
      // Connect to both NXTs
      public boolean connectToNXTs() {
    
        // Get the BluetoothDevice of the NXT
        BluetoothDevice nxt_2 = localAdapter.getRemoteDevice(nxt2);
        BluetoothDevice nxt_1 = localAdapter.getRemoteDevice(nxt1);
        // Try to connect to the nxt
        try {
          socket_nxt2 = nxt_2.createRfcommSocketToServiceRecord(UUID
              .fromString("00001101-0000-1000-8000-00805F9B34FB"));
    
          socket_nxt1 = nxt_1.createRfcommSocketToServiceRecord(UUID
              .fromString("00001101-0000-1000-8000-00805F9B34FB"));
    
          socket_nxt2.connect();    
          socket_nxt1.connect();      
    
          success = true;
    
        } catch (IOException e) {
          Log.d("Bluetooth","Err: Device not found or cannot connect");
          success=false;
        }
        return success;    
      }
    
    
      public void writeMessage(byte msg, String nxt) throws InterruptedException {
        BluetoothSocket connSock;
    
        // Swith nxt socket
        if (nxt.equals("nxt2")) {
          connSock=socket_nxt2;
        } else if(nxt.equals("nxt1")) {
          connSock = socket_nxt1;
        } else {
          connSock=null;
        }
    
        if (connSock!=null) {
          try {
    
            OutputStreamWriter out = new OutputStreamWriter(connSock.getOutputStream());
            out.write(msg);
            out.flush();
    
            Thread.sleep(1000);
    
          } catch (IOException e) {
            // TODO: Auto-generated catch block
            e.printStackTrace();
          }
        } else {
          // Error
        }
      }
    
      public int readMessage(String nxt) {
        BluetoothSocket connSock;
        int n;
    
        // Swith nxt socket
        if (nxt.equals("nxt2")) {
          connSock=socket_nxt2;
        } else if (nxt.equals("nxt1")) {
          connSock=socket_nxt1;
        } else {
          connSock=null;
        }
    
        if (connSock!=null) {
          try {
    
            InputStreamReader in = new InputStreamReader(connSock.getInputStream());
            n = in.read();
            return n;
    
          } catch (IOException e) {
            // TODO: Auto-generated catch block
            e.printStackTrace();
            return -1;
          }
        } else {
          // Error
          return -1;
        }
      }
    }
    
    .

    Per ottenere messaggi dallo smartphone Android devi avere una chiamata di lettura sul lato NXT. Ecco il codice dal lato NXT che accetterà la connessione dallo smartphone e leggerà i messaggi da esso:

    Boolean isrunning = true;
    
    // Main loop   
    while (true)
    {
      LCD.drawString(waiting,0,0);
      LCD.refresh();
    
      // Listen for incoming connection
    
      NXTConnection btc = Bluetooth.waitForConnection();
    
      btc.setIOMode(NXTConnection.RAW);
    
      LCD.clear();
      LCD.drawString(connected,0,0);
      LCD.refresh();  
    
    
      // The InputStream for read data 
      DataInputStream dis = btc.openDataInputStream();
    
    
      // Loop for read data  
      while (isrunning) {
        Byte n = dis.readByte();
        LCD.clear();
        LCD.drawInt(n, 4, 4);
      }
    
      dis.close();
    
      // Wait for data to drain
      Thread.sleep(100); 
    
      LCD.clear();
      LCD.drawString(closing,0,0);
      LCD.refresh();
    
      btc.close();
    
      LCD.clear();
    }
    
    .

    Spero che questo aiuterà gli altri ...

Altri suggerimenti

C'è un documento che ho trovato molto utile http://wiki.tinyclr.com/images/d/df/lego_mindstorms_nxt_direct_commands.pdf

Il pacchetto Minddroid su GitHub è un punto di partenza per iniziare.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top