【问题标题】:Data packet reception via bluetooth at android GUI在 android GUI 上通过蓝牙接收数据包
【发布时间】:2013-12-18 08:01:36
【问题描述】:

我对 arduino 和 android 域都很陌生。我正在使用 arduino 使用蓝牙模块(linvor JY-MCU v.1.05)向 android 发送数据。它与我的应用程序完美通信,但我无法接收此特定应用程序的任何数据。我正在从 arduino => ($ 43 56!)传输一个数据包,我想提取它并在 android 应用程序上单独显示数字。 这里$-header, 43-hr value, 56-temp value, !-footer

我的arduino代码如下:

  #include <SoftwareSerial.h>


  SoftwareSerial mySerial(10, 11); // RX, TX
  String command = "";             // Stores response of bluetooth device
                           // which simply allows \n between each
                           // response.


  void setup() {
  mySerial.begin(9600); // initialization

  delay(25);
  }

  void loop() 

  {
  mySerial.println("$-43:56^!");  // print   message


  delay(5000);
  }

字符串就像一个数据包。我希望 43 显示在编辑框中,56 显示在文本框中。

我的 android 代码也很庞大,它也会检查蓝牙连接。所以我把它限制在一个部分。有人可以帮我解决它的编码部分,分别在两个 txtView1 和 txtView2 中显示两组数字....

    package com.example.projtrial;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.reflect.Method;
    import java.util.UUID;

    import com.example.projtrial.R;


    import android.R.string;
    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.Build;
    import android.view.Menu;
    import android.os.Handler;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.EditText;
    import java.util.regex.Pattern;
    import java.util.Arrays;
    import java.util.StringTokenizer;

    public class MainActivity extends Activity {
  private static final String TAG = "projtrial";

  public EditView editView1;
  public TextView textView1;
  Handler h;

final int RECEIVE_MESSAGE = 1;       //Handler status
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();

private ConnectedThread mConnectedThread;

//SPP UUID service
  private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-    00805F9B34FB");       
// MAC-address of Bluetooth module 
  private static String address = "20:13:05:13:01:98";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


editText1 = (EditText) findViewById(R.id.editText1);       
textView1 = (TextView) findViewById(R.id.textView1);

h = new Handler() {
    private String strIncom;
private String header;
    private String hr;
    private String tempr;
    private String footer;


public void handleMessage(android.os.Message msg) {

switch (msg.what) {
        case RECEIVE_MESSAGE:   // If one receives a message                                

            byte[] readBuf = (byte[]) msg.obj;
            String header = new String(readBuf, 0, msg.arg1);

            String[] separated = message.split("\\:");
            editText1.setText("hr: " + separated[0]);  //works
            textView1.setText("temp:" + separated[1]); //doesnt work
               }
            break;    
    }

};

};


btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
checkBTState();

}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws        IOException {
    if(Build.VERSION.SDK_INT >= 10){
        try {
            final Method  m =   device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, MY_UUID);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
    }
    return  device.createRfcommSocketToServiceRecord(MY_UUID);
}


@Override
public void onResume() {
  super.onResume();

  Log.d(TAG, "...onResume - try connect...");

  // Set up a pointer to the remote node using it's address.
  BluetoothDevice device = btAdapter.getRemoteDevice(address);

  // Two things are needed to make a connection:
  //   A MAC address, which we got above.
  //   A Service ID or UUID.  In this case we are using the
  //     UUID for SPP.

try {
    btSocket = createBluetoothSocket(device);
} catch (IOException e) {
    errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}

  /*try {
    btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  } catch (IOException e) {
    errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  }*/

  // Discovery is resource intensive.  Make sure it isn't going on
  // when you attempt to connect and pass your message.
  btAdapter.cancelDiscovery();

  // Establish the connection.  This will block until it connects.
  Log.d(TAG, "...Connecting...");
  try {
    btSocket.connect();
    Log.d(TAG, "....Connection ok...");
  } catch (IOException e) {
    try {
      btSocket.close();
    } catch (IOException e2) {
      errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
    }
  }

  // Create a data stream so we can talk to server.
  Log.d(TAG, "...Create Socket...");

  mConnectedThread = new ConnectedThread(btSocket);
  mConnectedThread.start();
}

@Override
public void onPause() {
  super.onPause();

  Log.d(TAG, "...In onPause()...");

  try     {
    btSocket.close();
  } catch (IOException e2) {
    errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
  }
}

private void checkBTState() {
  // Check for Bluetooth support and then check to make sure it is turned on
  // Emulator doesn't support Bluetooth and will return null
  if(btAdapter==null) { 
    errorExit("Fatal Error", "Bluetooth not support");
  } else {
    if (btAdapter.isEnabled()) {
      Log.d(TAG, "...Bluetooth ON...");
    } else {
      //Prompt user to turn on Bluetooth
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(enableBtIntent, 1);
    }
  }
}

private void errorExit(String title, String message){
  Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
  finish();
}

private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


  public void run() {
        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
              h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget();       // Send to message queue Handler
            } catch (IOException e) {
                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.main, menu);
    return true;
}
  */
            }
      }
        }
   }

有人请尽快帮助我。我已经坚持了一个多星期。提前谢谢你。 三杰

“案例接收”和“运行”是必须进行更改的循环。 查找字符“indexOf()”的索引会产生错误(字符串索引超出范围)。 我也尝试在进入机箱接收块后关闭蓝牙,但徒劳无功。 希望能找到解决办法。

【问题讨论】:

    标签: android bluetooth arduino


    【解决方案1】:

    Message 包含什么?与

    byte[] readBuf = (byte[]) msg.obj;
    String header = new String(readBuf, 0, msg.arg1);
    

    所有连续的

     byte[] readBuf2 = (byte[]) msg.obj; 
     String hr = new String(readBuf2, 0, msg.arg1);
    

    您总是提取相同的数据。 鉴于在 obj 中包含 $! 之间的字符,那么您可以阅读所有消息

    byte[] readBuf = (byte[]) msg.obj;
    String message = new String(readBuf, 0, msg.arg1);
    

    然后提取所有行

    String[] cell = message.split("\n");
    txtView1.setText("HR:" +cell[1]);
    [...]
    

    如果在 obj 中有一些字节 [],则必须将它们添加到缓冲区,然后删除所有字节,直到 $,添加字节 [],直到找到 !,然后从中提取并删除缓冲两个分隔符之间的数据,包括在内,并按照我之前所说的进行。 (嗯,这只是一种解决方案)

    【讨论】:

    • 谢谢。我尝试了你的建议,但我似乎没有很好地分割它。我只能在文本框 txtView1 中显示第一半说单元格 [0]。但是当我尝试显示单元格 [1] 时,应用程序崩溃了。我收到错误“数组索引超出范围”。我面临的另一个问题是我无法拆分数据并同时在两个文本视图中显示。我只编辑了案例接收部分,其余代码相同。我已经在它的编辑部分添加了它。
    【解决方案2】:

    现在我之前没有使用过蓝牙,但我想说问题可能出在以下几行:

    mySerial.println("$");  // print   message
    
    mySerial.println(23);
    
    mySerial.println(546);
    
    mySerial.println("!");
    

    因为你使用的是 println();您在每一行将消息作为单独的数据包发送,因此接收端无法将其拆分并使用信息。

    我遇到了类似的问题并通过简单地将所有需要的数据放在一个字符串中并发送整个字符串一次来解决它。

    由于某种原因,arduino 编码语言也不能像这样将整数和字符串连接到另一个字符串,我花了一段时间才弄明白,但你只需要使用类似这样的行:

    String output = "$";
    output += 23; //or "23", not sure if it matters which one you use.
    output += 546;
    output += "!";
    mySerial.println(output);
    

    【讨论】:

    • 谢谢你,但它似乎仍然没有帮助我。
    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2018-03-14
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多