Android - Arduino蓝牙通讯

时间:2015-10-10 07:43:55

标签: java android bluetooth arduino

嗨我是android studio和java的新手,并希望从arduino读取数据到android。

计划是让我的界面上的按钮小部件向arduino发送信号,并让我的flex传感器通过蓝牙将信息发送回android。

我拥有的蓝牙模块是HC-06,这个代码的设计是为了让手机发送一个' *'到arduino并且它将一个随机值发送回android但我希望该随机值显示在我的界面上的文本框中。这种变化意味着发生在java ofcourse但我不知道该怎么做。请帮忙。

这是我的第一个arduino代码

#include <SoftwareSerial.h>
const int RX_PIN = 2;
const int TX_PIN = 3;
SoftwareSerial serial(RX_PIN, TX_PIN);
char commandChar;

void setup ()
{
serial.begin (9600);
andomSeed(analogRead(0))
}

void loop ()
{
 if(serial.available())
 {
  commandChar = serial.read();
 switch(commandChar)
  {
      case '*':
      serial.print(random(1000) + "#");
      break;
     }
  }
}

这是我在android studio上完成的代码:

package com.example.ft.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

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


public class MainActivity extends AppCompatActivity {

BluetoothAdapter mBluetoothAdapter;

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

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
    }
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new                    Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    }
    Set<BluetoothDevice> pairedDevices =   mBluetoothAdapter.getBondedDevices();
    BluetoothDevice mDevice = null;
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            mDevice = device;
        }
    }
    ConnectThread mConnectThread = new ConnectThread(mDevice);
    mConnectThread.start();


}

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        byte[] writeBuf = (byte[]) msg.obj;
        int begin = (int)msg.arg1;
        int end = (int)msg.arg2;

        switch(msg.what) {
           case 1:
                String writeMessage = new String(writeBuf);
                writeMessage = writeMessage.substring(begin, end);
                break;
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        mmDevice = device;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }
    public void run() {
        mBluetoothAdapter.cancelDiscovery();
        try {
            mmSocket.connect();
        } catch (IOException connectException) {
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
        ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
        mConnectedThread.start();

    }
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
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() {
        String s = "*";
        write(s.getBytes());

        byte[] buffer = new byte[1024];
        int begin = 0;
        int bytes = 0;
        while (true) {
            try {
                bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
                for(int i = begin; i < bytes; i++) {
                    if(buffer[i] == "#".getBytes()[0]) {
                        mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
                        begin = i + 1;
                        if(i == bytes - 1) {
                            bytes = 0;
                            begin = 0;
                        }
                    }
                }
            } catch (IOException e) {
                break;
            }
        }
    }
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

}

0 个答案:

没有答案