D
D
Denis Afonin2015-11-20 16:48:52
Android
Denis Afonin, 2015-11-20 16:48:52

How to organize a Bluetooth connection to two boards with HC-06?

How to organize two-way data exchange from ANDROID with two ARDUINO boards with HC-06 Bluetooth modules connected to them.
I establish a connection with one board, data transfer works. I do not understand how to make a connection to the second receiver.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Afonin, 2015-11-25
@Afdenis

The question is removed, the solution is found, the example found on the network slightly changed, where a single connection was implemented:

package ru.bltmulti;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
  private static final String TAG = "bluetooth2";
   
  Button btn1On, btn1Off, btn1Reset, btn2On, btn2Off, btn2Reset;
  TextView txtArduino;
  Handler h;
   
  private static final int REQUEST_ENABLE_BT = 1;
  final int RECIEVE_MESSAGE = 1;		// Статус для Handler
  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket = null;
  private BluetoothSocket btSocket2 = null;
  private StringBuilder sb = new StringBuilder();
  
  private ConnectedThread mConnectedThread;
  private ConnectedThread mConnectedThread2;
   
  private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
 
  private static String address = "98:D3:31:60:2F:13";
  private static String address2 = "98:D3:31:20:43:5F";
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    setContentView(R.layout.activity_main);
 
    btn1On = (Button) findViewById(R.id.btn1On);					// кнопка включения
    btn1Off = (Button) findViewById(R.id.btn1Off);				// кнопка выключения
    btn1Reset = (Button) findViewById(R.id.btn1Reset);
    btn2On = (Button) findViewById(R.id.btn2On);					// кнопка включения
    btn2Off = (Button) findViewById(R.id.btn2Off);				// кнопка выключения
    btn2Reset = (Button) findViewById(R.id.btn2Reset);
    txtArduino = (TextView) findViewById(R.id.txtArduino);		// для вывода текста, полученного от Arduino
    
    h = new Handler() {
    	public void handleMessage(android.os.Message msg) {
    		switch (msg.what) {
            case RECIEVE_MESSAGE:													
            	byte[] readBuf = (byte[]) msg.obj;
            	String strIncom = new String(readBuf, 0, msg.arg1);
            	sb.append(strIncom);											
            	int endOfLineIndex = sb.indexOf("\r\n");							
            	if (endOfLineIndex > 0) { 										
            		String sbprint = sb.substring(0, endOfLineIndex);				
                    sb.delete(0, sb.length());										
                	txtArduino.setText("Ответ от Arduino: " + sbprint); 	      
                	btn1Off.setEnabled(true);
                	btn1On.setEnabled(true);
                    btn2Off.setEnabled(true);
                    btn2On.setEnabled(true);
                }
            	//Log.d(TAG, "...Строка:"+ sb.toString() +  "Байт:" + msg.arg1 + "...");
            	break;
    		}
        };
  };
     
    btAdapter = BluetoothAdapter.getDefaultAdapter();		
    checkBTState();
 
    btn1On.setOnClickListener(new OnClickListener() {       
      public void onClick(View v) {
        btn1On.setEnabled(false);
        mConnectedThread.write("w");    
        
      }
    });
 
    btn1Off.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        btn1Off.setEnabled(false);
        mConnectedThread.write("s");   
        
      }
    });

    btn1Reset.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        //btn1Reset.setEnabled(false);
        mConnectedThread.write("x");   
      }
    });

    btn2On.setOnClickListener(new OnClickListener() {        
      public void onClick(View v) {
        btn2On.setEnabled(false);
        mConnectedThread2.write("e");   
      }
    });

    btn2Off.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        btn2Off.setEnabled(false);
        mConnectedThread2.write("d");  
      }
    });

    btn2Reset.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        //btn2Reset.setEnabled(false);
        mConnectedThread2.write("c");   
      }
    });
  }
   
  @Override
  public void onResume() {
    super.onResume();
 
    Log.d(TAG, "...onResume - попытка соединения...");
   
    
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    BluetoothDevice device2 = btAdapter.getRemoteDevice(address2);
   
    try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
      btSocket2 = device2.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

   btAdapter.cancelDiscovery();
   
    Log.d(TAG, "...Соединяемся...");
    try {
      btSocket.connect();
      Log.d(TAG, "...Соединение 1 установлено и готово к передачи данных...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }
    try {
      btSocket2.connect();
      Log.d(TAG, "...Соединение 2 установлено и готово к передачи данных...");
    } catch (IOException e) {
      try {
        btSocket2.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }

    Log.d(TAG, "...Создание Socket...");
   
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();
    mConnectedThread2 = new ConnectedThread(btSocket2);
    mConnectedThread2.start();
  }
 
  @Override
  public void onPause() {
    super.onPause();
 
    Log.d(TAG, "...In onPause()...");
  
    try     {
      btSocket.close();
    } catch (IOException e2) {
      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
    try     {
      btSocket2.close();
    } catch (IOException e2) {
      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
  }
   
  private void checkBTState() {
    if(btAdapter==null) { 
      errorExit("Fatal Error", "Bluetooth не поддерживается");
    } else {
      if (btAdapter.isEnabled()) {
        Log.d(TAG, "...Bluetooth включен...");
      } else {
        Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
    }
  }
 
  private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
  }
 
  private class ConnectedThread extends Thread {
      private final BluetoothSocket mmSocket;
      private final InputStream mmInStream;
      private final OutputStream mmOutStream;
   
      public ConnectedThread(BluetoothSocket socket) {
          mmSocket = socket;
          InputStream tmpIn = null;
          OutputStream tmpOut = null;
          try {
              tmpIn = socket.getInputStream();
              tmpOut = socket.getOutputStream();
          } catch (IOException e) { }
   
          mmInStream = tmpIn;
          mmOutStream = tmpOut;
      }
   
      public void run() {
          byte[] buffer = new byte[256];  // buffer store for the stream
          int bytes; // bytes returned from read()
          while (true) {
          	try {
                  bytes = mmInStream.read(buffer);
                        h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();		
              } catch (IOException e) {
                  break;
              }
          }
      }
   
      public void write(String message) {
      	Log.d(TAG, "...Данные для отправки: " + message + "...");
      	byte[] msgBuffer = message.getBytes();
      	try {
              mmOutStream.write(msgBuffer);
          } catch (IOException e) {
              Log.d(TAG, "...Ошибка отправки данных: " + e.getMessage() + "...");     
            }
      }
   
      public void cancel() {
          try {
              mmSocket.close();
          } catch (IOException e) { }
      }
  }
  
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question