首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从Android发送到HC-05蓝牙Arduino的数据未显示

从Android发送到HC-05蓝牙Arduino的数据未显示
EN

Stack Overflow用户
提问于 2017-07-15 09:31:57
回答 1查看 2.1K关注 0票数 0

我正在创建一个Android应用程序,它允许我使用蓝牙控制连接到Arduino的设备,使用Android 4.4.2,Arduino Uno和HC-05模块。

现在,我发现在Arduino系列中打印数据非常困难(为了验证它是否真的有效)。我尝试了我在这个或其他与这个主题相关的论坛中找到的所有东西。

目前,我已经能够检测设备,与它们配对,并创建套接字和OutputStream,但由于某种原因,数据没有显示出来。

代码是2个基本的活动及其布局(Android)和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对象的意图,作为我们要连接的设备。创建OutputStream的BluetoothSocket、连接线程。

*在这部分代码中,我试图获取另一个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());
  }
}

下一步我可以尝试什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-30 00:36:38

更新:

如果您必须在项目中使用此代码,请随意使用。

我已经设法解决了这个问题,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);  
}

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45113605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档