2017-05-15 9 views
3

こんにちは、私はアンドロイドで開発することに新しいのですが、最近BluetoothのAPIを使い始めました。私は自分の電話機をHC-06のArduino NANOに接続することができました。しかし、私は正しくデータを転送するように見えることはできません。私の目標は、デバイスから現在の値を取得し、それを表示しながら、アプリケーション上の変数に保存することです。ここでは、arduinoとアプリの両方のための私のコードです。私はこのスレッドを使用するすべての私のAndroid/ArduinoのプロジェクトのためにAndroid Bluetoothアプリケーション

のAndroidメーカー

package com.clipius.clipiusweight; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
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.view.View; 
import android.widget.TextView; 
import android.widget.EditText; 
import android.widget.Button; 
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 { 

    TextView myLabel; 
    TextView dataLabel; 
    EditText myTextbox; 
    BluetoothAdapter mBluetoothAdapter; 
    BluetoothSocket mmSocket; 
    BluetoothDevice mmDevice; 
    OutputStream mmOutputStream; 
    InputStream mmInputStream; 
    Thread workerThread; 
    byte[] readBuffer; 
    int readBufferPosition; 
    int counter; 
    volatile boolean stopWorker; 

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

     Button openButton = (Button)findViewById(R.id.getDataB); 
     Button sendButton = (Button)findViewById(R.id.sendDataB); 
     //Button closeButton = (Button)findViewById(R.id.close); 
     myLabel = (TextView)findViewById(R.id.ConnectionCheck); 
     dataLabel = (TextView) findViewById(R.id.weightValueText); 
     //myTextbox = (EditText)findViewById(R.id.weightValueText); 

     //Open Button 
     openButton.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       try 
       { 
        findBT(); 
        openBT(); 
       } 
       catch (IOException ex) { } 
      } 
     }); 

    } 



    void findBT() 
    { 
     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     if(mBluetoothAdapter == null) 
     { 
      myLabel.setText("No bluetooth adapter available"); 
     } 

     if(!mBluetoothAdapter.isEnabled()) 
     { 
      Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBluetooth, 0); 
     } 

     Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 
     if(pairedDevices.size() > 0) 
     { 
      for(BluetoothDevice device : pairedDevices) 
      { 
       if(device.getName().equals("HC-06")) 
       { 
        mmDevice = device; 
        break; 
       } 
      } 
     } 
     myLabel.setText("Bluetooth Device Found"); 
    } 

    void openBT() throws IOException 
    { 
     UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID 
     mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); 
     mmSocket.connect(); 
     mmOutputStream = mmSocket.getOutputStream(); 
     mmInputStream = mmSocket.getInputStream(); 

     beginListenForData(); 

     myLabel.setText("Bluetooth Opened"); 
    } 

    void beginListenForData() 
    { 
     final Handler handler = new Handler(); 
     final byte delimiter = 10; //This is the ASCII code for a newline character // old 10 

     stopWorker = false; 
     readBufferPosition = 0; 
     readBuffer = new byte[1024]; 
     workerThread = new Thread(new Runnable() 
     { 
      public void run() 
      { 
       while(!Thread.currentThread().isInterrupted() && !stopWorker) 
       { 
        try 
        { 
         int bytesAvailable = mmInputStream.available(); 
         if(bytesAvailable > 0) 
         { 
          byte[] packetBytes = new byte[bytesAvailable]; 
          mmInputStream.read(packetBytes); 
          for(int i=0;i<bytesAvailable;i++) 
          { 
           byte b = packetBytes[i]; 
           if(b == delimiter) 
           { 
            byte[] encodedBytes = new byte[readBufferPosition]; 
            System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); 
            final String data = new String(encodedBytes, "US-ASCII"); 
            readBufferPosition = 0; 


            handler.post(new Runnable() 
            { 
             public void run() 
             { 
              dataLabel.setText(data); 
             } 
            }); 
           } 
           else 
           { 
            readBuffer[readBufferPosition++] = b; 
           } 
          } 
         } 
        } 
        catch (IOException ex) 
        { 
         stopWorker = true; 
        } 
       } 
      } 
     }); 
     Toast.makeText(getApplicationContext(), "Starting Worker Thread", Toast.LENGTH_SHORT).show(); 
     workerThread.start(); 
    } 

} 

Arduinoの

#include <SoftwareSerial.h> 

int sensorPin = A0; 
int sensorValue = 0; 
char stringValue[5]; 

SoftwareSerial BTserial(10, 11); // RX | TX 


void setup() { 
Serial.begin(9600); 
BTserial.begin(9600);  
} 

void loop() { 

// Gets the int. value of the sensor 
sensorValue = analogRead(sensorPin); 

//conversion to string so AS can read it in. 
itoa(sensorValue, stringValue, 10); 

// Writes value to console for debugging 
Serial.println(stringValue); 


     BTserial.print(stringValue); 
     BTserial.print(sensorValue); 

      delay(1000); 

答えて

0


このメソッドは動作するため(、あなたはより多くの情報が必要な場合は私に知らせて! !)
OpenButtonのOnClickで接続スレッドを起動します。

接続スレッド(安定した接続を確立する):

private class ConnectThread extends Thread { 
    private final BluetoothDevice mmDevice; 
    private BluetoothSocket mmSocket; 

    ConnectThread(BluetoothDevice device) { 
     mmDevice = device; 
     try { 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { 
      //connectedNotification("DIS"); 
     } 
     mmSocket = tmp; 
    } 

    public void run() { 
     //connectedNotification("Connecting ..."); 
     mBluetoothAdapter.cancelDiscovery(); 
     try { 
      mmSocket.connect(); 
      beginListenForData(); 
     } catch (IOException connectException) { 
      try { 
       mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1); 
       mmSocket.connect(); 
       beginListenForData(); 
      } catch (Exception e2) { 
       try { 
        mmSocket.close(); 
        //connectedNotification("DIS"); 
       } catch (IOException closeException) { 
        //connectedNotification("DIS"); 
       } 
      } 
     } 
    } 

    void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { 
      //connectedNotification("DIS"); 
     } 
    } 
}