2017-07-15 5 views
0

とありがとうございます。Androidから送信されたデータ - > HC-05 Bluetooth Arduinoが表示されない

Android 4.4.2、Arduino Uno、HC-05モジュールを使用してArduinoに接続されたデバイスをBluetoothで制御できるAndroidアプリを作成しています。

今、Arduinoシリアル(実際に動作しているかどうかを確認するためにIrの順番)でデータを印刷するのは非常に困難です。このトピックに関するこのフォーラムまたは他のフォーラムで見つけたものすべてを試してみました。

私はデバイスを検出してペアにし、ソケットとOutputStreamを作成することができましたが、何らかの理由でデータが表示されませんでした。

コードは2つの基本的な活動とそのレイアウト(アンドロイド)とArduinoのコードです:

Image of how it shows the available devices.

Image of how now that device is paired with our Android Device.

GetPaired.java:

は基本的に使用可能なデバイスを取得し、それらをカスタムListViewに表示し、それらとペア設定/ペア設定することができます。また、デバイスがペアになった後に、 ConnectionControlアクティビティに移動します。

import java.lang.reflect.Method; 
import java.util.ArrayList; 
import java.util.Set; 
import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.ListView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.Toast; 

    public class GetPaired extends Activity { 

    ListView listViewPaired; 
    ListView listViewDetected; 
    ArrayList<String> arrayListpaired; 
    Button buttonSearch,buttonControl; 
    ArrayAdapter<String> adapter, detectedAdapter; 
    BluetoothDevice bdDevice; 
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices; 
    ListItemClickedonPaired listItemClickedonPaired; 
    BluetoothAdapter bluetoothAdapter = null; 
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null; 
    ListItemClicked listItemClicked; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_bluetooth_demo); 
     listViewDetected = (ListView) 
     findViewById(R.id.listViewDetected); 
     listViewPaired = (ListView) findViewById(R.id.listViewPaired); 
     buttonSearch = (Button) findViewById(R.id.buttonSearch); 
     buttonControl = (Button) findViewById(R.id.buttonControl); 
     arrayListpaired = new ArrayList<String>(); 
     bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice(); 
     listItemClickedonPaired = new ListItemClickedonPaired(); 
     arrayListBluetoothDevices = new ArrayList<BluetoothDevice>(); 
     adapter = new ArrayAdapter<String>(GetPaired.this, 
    R.layout.custom_layout, arrayListpaired); 
     detectedAdapter = new ArrayAdapter<String>(GetPaired.this, 
    R.layout.custom_layout); 
     listViewDetected.setAdapter(detectedAdapter); 
     listItemClicked = new ListItemClicked(); 
     detectedAdapter.notifyDataSetChanged(); 
     listViewPaired.setAdapter(adapter); 
    } 

    @Override 
    protected void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 
     //Get all the paired bluetooth devices with Android. 
     getPairedDevices(); 
     listViewDetected.setOnItemClickListener(listItemClicked); 
     listViewPaired.setOnItemClickListener(listItemClickedonPaired); 
    } 

    private void getPairedDevices() { 
     Set<BluetoothDevice> pairedDevice = 
    bluetoothAdapter.getBondedDevices(); 
     if (pairedDevice.size() > 0) { 
      for (BluetoothDevice device : pairedDevice) { 
       arrayListpaired.add(device.getName() + "\n" + 
    device.getAddress()); 
       arrayListPairedBluetoothDevices.add(device); 
       break; 
      } 
     } 
     adapter.notifyDataSetChanged(); 
    } 

    //When clicked a bluetooth device from the available list, a bond is 
    created between them. 
    class ListItemClicked implements OnItemClickListener{ 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int 
    position, long id) { 
      // TODO Auto-generated method stub 
      bdDevice = arrayListBluetoothDevices.get(position); 
      Log.i("Log", "The device : " + bdDevice.toString()); 
      Boolean isBonded = false; 
      try { 
       isBonded = createBond(bdDevice); 
       if (isBonded) { 
        getPairedDevices(); 
        adapter.notifyDataSetChanged(); 
        Log.i("Log", "The bond is created: " + isBonded); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      connect(bdDevice); 
     } 

    } 
    //When clicked in the list of paired devices, you remove the bond and 
    the pairing. 
    class ListItemClickedonPaired implements OnItemClickListener{ 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int 
    position, long id) { 
      bdDevice = arrayListPairedBluetoothDevices.get(position); 
      try { 
       Boolean removeBonding = removeBond(bdDevice); 
       if (removeBonding) { 
        arrayListpaired.remove(position); 
        adapter.notifyDataSetChanged(); 
       } 
       Log.i("Log", "Removed" + removeBonding); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

    private Boolean connect(BluetoothDevice bdDevice) { 
     Boolean bool = false; 
     try { 
      Log.i("Log", "service method is called "); 
      Class cl = Class.forName("android.bluetooth.BluetoothDevice"); 
      Class[] par = {}; 
      Method method = cl.getMethod("createBond", par); 
      bool = (Boolean) method.invoke(bdDevice); 
     } catch (Exception e) { 
      Log.i("Log", "Inside catch of serviceFromDevice Method"); 
      e.printStackTrace(); 
     } 
     return bool.booleanValue(); 
    } 


    public boolean removeBond(BluetoothDevice btDevice) 
      throws Exception { 
     Class btClass = 
    Class.forName("android.bluetooth.BluetoothDevice"); 
     Method removeBondMethod = btClass.getMethod("removeBond"); 
     Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice); 
     return returnValue.booleanValue(); 
    } 


    public boolean createBond(BluetoothDevice btDevice) 
      throws Exception { 
     Class class1 = Class.forName("android.bluetooth.BluetoothDevice"); 
     Method createBondMethod = class1.getMethod("createBond"); 
     Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); 
     return returnValue.booleanValue(); 
    } 


    //Searches for available bluetooth devices to add them to the 
    Detected 
    List. 
    private BroadcastReceiver myReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       Toast.makeText(context, "ACTION_FOUND", 
    Toast.LENGTH_SHORT).show(); 

       BluetoothDevice device = 
    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       if (arrayListBluetoothDevices.size() < 1) // this checks 
    if the size of bluetooth device is 0,then add the 
       {           // device to 
    the arraylist. 
        detectedAdapter.add(device.getName() + "\n" + 
    device.getAddress()); 
        arrayListBluetoothDevices.add(device); 
        detectedAdapter.notifyDataSetChanged(); 
       } else { 
        boolean flag = true; // flag to indicate that 
    particular device is already in the arlist or not 
        for (byte i = 0; i < arrayListBluetoothDevices.size(); 
    i++) { 
         if 
(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()) 
    ) { 
          flag = false; 
         } 
        } 
        if (flag == true) { 
         detectedAdapter.add(device.getName() + "\n" + 
    device.getAddress()); 
         arrayListBluetoothDevices.add(device); 
         detectedAdapter.notifyDataSetChanged(); 
        } 
       } 
      } 
     } 
    }; 

    //Method that starts the search of bluetooth devices to connect with. 
    public void startSearching(View v) { 
     arrayListBluetoothDevices.clear(); 
     Log.i("Log", "in the start searching method"); 
     IntentFilter intentFilter = new 
    IntentFilter(BluetoothDevice.ACTION_FOUND); 
     GetPaired.this.registerReceiver(myReceiver, intentFilter); 
     bluetoothAdapter.startDiscovery(); 
    } 


    //When you have the device paired with Android, you can go to the 
    next 
    Activity, where the proper connection is stablished. 
    public void onControl(View v) { 
     if (arrayListPairedBluetoothDevices.size() > 0) { 
      Log.i("Log", "There is a paired device."); 
      Intent sipoptent = new Intent(getApplicationContext(), 
    ConnectionControl.class).putExtra("Bluetooth", 
    arrayListPairedBluetoothDevices.get(0)); 
      startActivity(sipoptent); 
      if (arrayListPairedBluetoothDevices.get(0) != null) { 
      } else { 
      } 
     } else { 
      Log.i("Log", "Not paired to a device yet."); 
       Toast.makeText(GetPaired.this, "Not paired to a device 
    yet.", 
    Toast.LENGTH_SHORT).show(); 

      } 
     } 
    } 

ConnectionControl活動:

は、我々はと接続するために うとしているデバイスとして、BluetoothDeviceオブジェクトとの意図を受信します。 BluetoothSocketを作成します。接続はOutputStreamをスレッドします。

*コードのこの部分では、別のUUIDを取得しようとしましたが、もう何も見つかりませんでした。

import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 
import java.io.IOException; 
import java.util.UUID; 
import java.io.OutputStream; 

public class ConnectionControl extends AppCompatActivity { 
Button on, off; 
private BluetoothSocket btSocket = null; 
private BluetoothDevice device; 
private OutputStream mmOutStream =null; 
// SPP UUID service - this should work for most devices 
private static final UUID BTMODULEUUID = UUID.fromString("00001101- 
0000-1000-8000-00805F9B34FB"); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
on = (Button) findViewById(R.id.onbutton); 
off = (Button) findViewById(R.id.offbutton); 
device = getIntent().getExtras().getParcelable("Bluetooth"); 
//Bluetooth device information retrieved by an Intent. 
Toast.makeText(ConnectionControl.this, device.getAddress(), 
Toast.LENGTH_SHORT).show(); 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    try { 
     //Creation of the socket of the connection. 
     btSocket = createBluetoothSocket(device); 
    } catch (IOException e) { 
     Toast.makeText(getBaseContext(),"Socket connection failed.", 
Toast.LENGTH_LONG).show(); 
    } 
    // Establish the Bluetooth socket connection. 
    try { 
     btSocket.connect(); 
     ConnectedThread(btSocket); 
     write("x"); 
    } catch (IOException e) { 
     try { 
      btSocket.close(); 
     } catch (IOException e2) {} 
    } 
} 

//Creates secure outgoing connecetion with BT device using UUID 
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) 
throws IOException { 
    return device.createRfcommSocketToServiceRecord(BTMODULEUUID); 
} 

//Creates the OutputStream from the socket. 
public void ConnectedThread(BluetoothSocket socket) { 
    OutputStream tmpOut = null; 
    try { 
     tmpOut = socket.getOutputStream(); 
    } catch (IOException e) { 
     Toast.makeText(getBaseContext(), "Connection Not 
Established.", Toast.LENGTH_LONG).show(); 
    } 
    Toast.makeText(getBaseContext(), "Connection Established.", Toast.LENGTH_LONG).show(); 
    mmOutStream = tmpOut; 
} 

@Override 
public void onPause() 
{ 
    super.onPause(); 
    try 
    { 
     //Don't leave Bluetooth sockets open when leaving activity 
     btSocket.close(); 
    } catch (IOException e2) { 
     //insert code to deal with this 
    } 
} 

    //Transforms a String input into an array of bytes to send to the bluetooth device. 
    public void write(String input) { 
     byte[] msgBuffer = input.getBytes();   //converts entered String into bytes 
     try { 
      mmOutStream.write(msgBuffer);    //write bytes over BT connection via outstream 
     } catch (IOException e) { 
      //if you cannot write, close the application 
      Toast.makeText(getBaseContext(), "Conection failed.", Toast.LENGTH_LONG).show(); 
     } 
    } 

public void onON(View view){ 
    write("0"); 
} 
public void onOFF(View view){ 
    write("1"); 
} 
} 

そして、Arduinoのコード:Arduinoのハードウェアで

私は5Vに接続されており、すでに前にその名前を変更するにはブルートゥースにATモードに入りました。

#include <SoftwareSerial.h> 
SoftwareSerial mySerial(10, 11); // RX, TX 

void setup() { 
    // Open serial communications and wait for port to open: 
    Serial.begin(9600); 
    while (!Serial) { 
    ; // wait for serial port to connect. Needed for native USB port only 
    } 

    // set the data rate for the SoftwareSerial port 
    mySerial.begin(9600); 
} 

void loop() { // run over and over 
    if (mySerial.available()) { 
    Serial.write(mySerial.read()); 
    } 
    if (Serial.available()) { 
    mySerial.write(Serial.read()); 
    } 
} 

また、おかげさまで、助けてくれれば、私に与えることのできる手がかりは非常に高く評価されます。

答えて

0

UPDATE:あなたはこのプロジェクトのためにこのコードを使用する必要がある場合

はそれを使用して自由に感じます。

私は問題を解決するために管理している、Arduinoのコードが問題だった、これは作業コードです:

#include <SoftwareSerial.h> 
SoftwareSerial BTserial(11, 10); // RX | TX 
char c = ' '; 
void setup() 
{ 
Serial.begin(9600); 
Serial.println("Arduino is ready"); 

// HC-05 default serial speed for commincation mode is 9600 
BTserial.begin(9600); 
} 

void loop() 
{ 
if (BTserial.available()) 
{ 
    c = BTserial.read(); 
    Serial.write(c); 
} 

// Keep reading from Arduino Serial Monitor and send to HC-05 
if (Serial.available()) 
{ 
    c = Serial.read(); 
    BTserial.write(c); 
} 

} 
関連する問題