连接到arduino蓝牙

时间:2016-05-11 07:57:29

标签: android bluetooth arduino

我有一个项目,我必须连接电路的蓝牙。首先,我必须连接HC-06模块然后发送数据,如" red"," green"和"蓝"。我已经编写了电路,它适用于windows(C#)应用程序,但我想制作android应用程序。

总之,用户在Android设备上选择一种颜色。 Android设备会将该颜色的名称发送到HC-06模块,电路将运行正确的彩色电机。

我已经尝试了不同的方法来成功,但Android应用程序关闭。我的最后一个代码在这里:

BluetoothAdapter bt;

OutputStream outputStream;
BluetoothSocket soket;
StringBuilder sb;


private static final UUID uuid_kodu = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String mac_adres = "00:15:FF:F2:19:5F";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anasayfa);



    bt = BluetoothAdapter.getDefaultAdapter();


    bt_control();

 }

private void bt_control() {

    if(bt==null) {
        Toast.makeText(Anasayfa.this, "Bt doesnt supports on this device", Toast.LENGTH_SHORT).show();
    } else {
        if (!bt.isEnabled()) {

            Toast.makeText(Anasayfa.this, "Bt is opening", Toast.LENGTH_SHORT).show();
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);


        }
    }
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这是一个非常简单的库,可将您的Android连接到HC-06模块:

<强> https://github.com/omaflak/Bluetooth-Library

要安装它,请添加到您的gradle app依赖项:

compile 'me.aflak.libraries:bluetooth:1.2.4'

这是一个简短的样本:

Bluetooth bluetooth = new Bluetooth(this);
bluetooth.enableBluetooth();

bluetooth.setCommunicationCallback(new Bluetooth.CommunicationCallback() {
      @Override
      public void onConnect(BluetoothDevice device) {
              // device connected
              bluetooth.send("message");
      }

      @Override
      public void onDisconnect(BluetoothDevice device, String message) {
            // device disconnected
      }

      @Override
      public void onMessage(String message) {
            // message received (it has to end with a \n to be received)
      }

      @Override
      public void onError(String message) {
            // error occurred 
      }

      @Override
      public void onConnectError(BluetoothDevice device, String message) {
            // error during connection
      }
});

// three options
bluetooth.connectToName("name");
bluetooth.connectToAddress("address");
bluetooth.connectToDevice(device);
相关问题