2016年7月30日 星期六

Android與mBot機器人藍芽連線並透過藍芽傳送訊息

此範例檔的藍芽連線,需事先在手機做好與藍芽裝置的配對,android再指定對方藍芽裝置的MAC位置進行連線
*此範例是與mBot的藍芽裝置連線,若是藍芽裝置接麵包板可能要設定pin腳,不適用本範例,但可參考android藍芽連線


Android部分
AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN" />

建立一個類別檔叫AsClientConnectBT
public class AsClientConnectBT {
    BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothSocket socket;
    BluetoothDevice device;
    InputStream inStream;
    OutputStream outStream;
    UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")//固定的字串
    byte[] msgBuffer;

    public AsClientConnectBT(){
        device = mBtAdapter.getRemoteDevice("00:0D:19:03:17:D5")//對方藍芽裝置MAC位置
        try {
            socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            inStream = socket.getInputStream();     //接收傳來的資料
            outStream = socket.getOutputStream();   //傳送資料給arduino
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void run(){
        try {
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void cancel(){
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void SendMsg(){
        try {
            outStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        msgBuffer = "0".getBytes()//傳送0

        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MainActivity檔案
public class MainActivity extends AppCompatActivity {
    AsClientConnectBT clientCon = new AsClientConnectBT();
    TextView tv;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.textview);
        btn = (Button)findViewById(R.id.button);
        btn.setOnClickListener(btnClick);
        clientCon.run();
    }

    public Button.OnClickListener btnClick = new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            clientCon.SendMsg();
        }
    };
}

Arduino部分


範例檔案

紀錄Arduino IDE載入函式庫方法

沒有留言: