I want to send an instruction to Arduino through an android app over the micro USB port.
For example, on clicking a button in the app there should glow an led connected to Arduino and the connection should be done via the micro USB port on android phone. I've done the same using bluetooth connection. How should I proceed on this? Or what should be the changes in the code?
Via bluetooth:
package com.example.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
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.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
int red_count=0;
int yellow_count=0;
int green_count=0;
int white_count=0;
private static final String TAG = "bluetooth2";
Button red_button,yellow_button,green_button,white_button,reset_button;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
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 (you must edit this line)
private static String address = "20:13:01:18:05:08";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
red_button = (Button) findViewById(R.id.red_button);
yellow_button = (Button) findViewById(R.id.yellow_button);
green_button = (Button) findViewById(R.id.green_button);
white_button = (Button) findViewById(R.id.white_button);
reset_button = (Button) findViewById(R.id.reset_button);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
sb.delete(0, sb.length()); // and clear
red_button.setEnabled(true);
yellow_button.setEnabled(true);
green_button.setEnabled(true);
white_button.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
red_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
red_count++;
yellow_count=0;
green_count=0;
white_count=0;
red_button.setText(""+red_count);
yellow_button.setText("");
green_button.setText("");
white_button.setText("");
mConnectedThread.write("1"); // Send "1" via Bluetooth
}
});
yellow_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
yellow_count++;
red_count=0;
green_count=0;
white_count=0;
yellow_button.setText(""+yellow_count);
red_button.setText("");
green_button.setText("");
white_button.setText("");
mConnectedThread.write("2"); // Send "2" via Bluetooth
}
});
green_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
green_count++;
red_count=0;
yellow_count=0;
white_count=0;
green_button.setText(""+green_count);
red_button.setText("");
yellow_button.setText("");
white_button.setText("");
mConnectedThread.write("3"); // Send "3" via Bluetooth
}
});
white_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
white_count++;
red_count=0;
green_count=0;
yellow_count=0;
white_button.setText(""+white_count);
red_button.setText("");
green_button.setText("");
yellow_button.setText("");
mConnectedThread.write("4"); // Send "4" via Bluetooth
}
});
reset_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
white_count=0;
red_count=0;
green_count=0;
yellow_count=0;
white_button.setText("");
red_button.setText("");
green_button.setText("");
yellow_button.setText("");
mConnectedThread.write("0"); // Send "0" via Bluetooth
}
});
}
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 (SecurityException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (InvocationTargetException 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(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
}
Ok,first of all i don't know anything about adruino coding,but in-order to communicate with usb devices android uses USB Host Api,goto the link for that.and here is a tutorial that may help interfacing android with Adruino,
how to communicate between the Arduino Uno and your computer using plain USB bulk and control transfers
Hope this helps
Related
I have a big problem and i cant solve. Please help me.
I have a data at the fragment i want to send data other devices with bluetooth but my ConnectedThread does not work. For the solve my problem firstly i tried log cat and i find my ConnectedThread is empty but why ? i although initilazed on my fragment.
**BluetoothConnectionService.java **
package com.example.duygu.mybluetoothdevicelist;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
Context mContext;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
private ConnectedThread mConnectedThread;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
/**
AcceptThread starts and sits waiting for a connection.
Then ConnectThread starts and attempts to make a connection with the other devices AcceptThread.
**/
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
/**
Finally the ConnectedThread which is responsible for maintaining the BTConnection, Sending the data, and
receiving incoming data through input/output streams respectively.
**/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "ConnectedThread: doest work OUTPUT");
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("theMessage", incomingMessage);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
/**
* Write to the ConnectedThread in an unsynchronized manner
*
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) { //changed this
// Create temporary object
if(mConnectedThread!=null){
ConnectedThread r;
r=mConnectedThread;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
r.write(out);
}
else{
Log.d(TAG, "ConnectedThread empty");
}
}
}
I saw this log.cat: ConnectedThread empty
public void write(byte[] out) { //changed this
// Create temporary object
if(mConnectedThread!=null){
ConnectedThread r;
r=mConnectedThread;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
r.write(out);
}
else{
Log.d(TAG, "ConnectedThread empty");
}
}
But i initilazed service in there (Fragment)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(convertView==null) {
convertView = inflater.inflate(R.layout.fragment_ota__update, container, false);
text=(TextView)convertView.findViewById(R.id.text);
InputStream is =this.getResources().openRawResource(R.raw.blink);
BufferedReader reader = new BufferedReader( new InputStreamReader(is));
send =(Button) convertView.findViewById(R.id.send);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
if(is!=null){
try {
while ((data = reader.readLine()) != null) {
char [] ch =data.toCharArray();
for (char c: ch) {
int i= (int) c;
sbuffer.append(Integer.toHexString(i).toUpperCase());
text.setText(sbuffer);
}
}
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sbuffer!=null) {
String deneme;
deneme="Hi";
byte[] bytes = deneme.toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
}
});
}
I'm doing an application that comunicate with car by an OBD 2 port.
Now i'm working with bluetooth connection and i'm reading Android documentation and have some issues about connection and comunication with obd device.
I'm moving like this steps:
1)If bluetooth not active, activate the bluetooth
2)search device and show in a list
3)OnItemClick in the listview for connect with touched device (founded) with a client bluetooth connection
And here i have some problem to understand the Android documentation....
For the connection with device i use this code (like documentation)
foundedDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
final int position, long id) {
mBluetoothAdapter.cancelDiscovery();
String deviceName = (String)adapter.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Selezionato: " + deviceName,
Toast.LENGTH_LONG).show();
for(BluetoothDevice dv : deviceList){
if(dv.getName() != null && dv.getName().equals(deviceName)){
selectedDevice = dv;
}
}
ConnectThread connectThread = new ConnectThread(selectedDevice);
connectThread.run();
}
});
//Thread of bluetooth connection
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.i(TAG, "Socket's create() successfull");
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
mBluetoothAdapter.cancelDiscovery();
Log.i(TAG, "run() eseguito");
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
//manageMyConnectedSocket(mmSocket);
}
// Closes the client socket and causes the thread to finish.
public void cancel() {
Log.i(TAG, "cancel() eseguito");
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
}
}
}
I'm not sure about the connectThread.run() they don't explain the usage of method inside ConnectThread and i don't know how declare the manageMyConnectedSocket(mmSocket);
For the comunication i create a class MyBluetoothService.java and like documentation i write this code:
package com.tesi.ddz.obd_project;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by ddz on 24/04/17.
*/
public class MyBluetoothService{
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service
// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
// ... (Add other message types here as needed.)
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
public ConnectedThread(BluetoothSocket socket) {
mmSocket = 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();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_READ, numBytes, -1,
mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
Message writtenMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
writtenMsg.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
Message writeErrorMsg =
mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast",
"Couldn't send data to the other device");
writeErrorMsg.setData(bundle);
mHandler.sendMessage(writeErrorMsg);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
}
I would implement the method manageMyConnectedSocket(mmSocket); by calling the class MyBluetoothService.java and manage the connection as i understand the documentation....
They declare ConnectedThread as private so i can't call this method in the MainActivity.java.... so what is the best way to implement this connection?
Don't use MyBluetoothService and declare all to the MainActivity or keep working like that and maybe declare ConnectedThred public so i can use it in the MainActivity?
Especially i don't understand how use the class MyBluetoothService.java and the method manageMyConnectionSocket(mmsocket)
I use a temperature sensor connected to arduino, then send temperature information through bluetooth to my phone. My phone application has a complete UI and is ready to receive information.
Every single tutorial I see is used to do the bluetooth pairing. I have not done this part yet (because arduino code is not complete yet, so can't test), but assuming I use the phone options to do the pairing, I still have no idea how to do the data transmission.
How do I receive information on the phone and display it? Could anyone point me to a tutorial or an explanation/code on how to proceed?
Thanks in advance!
Look at this.... very effective. In this code, you take a MAC address by file and connect it to the device automatically. Then you can send and receive string data from Arduino. You can take inspiration from this code.
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
public String ultimodato;
////
private static final String TAG = "bluetooth2";
Handler h;
final int RECEIVE_MESSAGE = 1; //1 // Status for Handler
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 (you must edit this line)
private static String address = "00:14:02:13:00:10";
////
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/* se non esiste il folder, creare il folder */
File folder = new File(Environment.getExternalStorageDirectory() + "/Asiagem");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
setContentView(R.layout.main);
//LETTURA DA FILE DEL MAC-ADDRESS A CUI CONNETTERSI
try{
String MACFile = readFileAsString("/sdcard/MAC.txt");
if(MACFile==""){
Toast.makeText(this,"Nessun dispositivo salvato, torno alla fase precedente", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
finish();
}else {
address = MACFile;
}
}catch(Exception e){
Toast.makeText(getApplicationContext(),"Errore nella lettura dei dati" , Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
finish();
}
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
Toast.makeText(getBaseContext(), strIncom, Toast.LENGTH_SHORT).show();
Log.d("INCOME", "INCOME: " + strIncom);
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);
}
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void SendMessageBT(View v){
//INVIO MESSAGGIO AL BLUETOOTH
mConnectedThread.write("U");
}
#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() + ".");
}
// 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();
previousTime = System.currentTimeMillis();
}
#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) {
if(System.currentTimeMillis() - previousTime > 10000){
previousTime = System.currentTimeMillis();
mConnectedThread.write("w");
}
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;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
ultimodato=message;
to_send=true;
//connect();
new connect_and_send().execute();
}
}
}
private class connect_and_send extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() { // Fa vedere solo il dialog
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
btSocket.close();
Log.d(TAG, "...ALERT: " + "SOCKET CHIUSA" + "...");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.d(TAG, "...ALERT: " + "IMPOSSIBILE CHIUDERE SOCKET" + "...");
}
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() + ".");
}
// 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();
//REINVIA L'ULTIMO DATO
if (to_send==true){
mConnectedThread.write(ultimodato);
to_send=false;
}
previousTime = System.currentTimeMillis();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
}
return result;
}
}
I want to connect android mobile to one electronic device,but I want to connect it insecurely.but its giving me the error of "java.io.IOException: read failed, socket might closed or timeout, read ret: -1"
here is my code
package net.londatiga.android.bluetooth;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final UUID WELL_KNOWN_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,because
// mmSocket is final
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// tmp = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
tmp = device
.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
Object[] params = new Object[] {Integer.valueOf(1)};
// This is the trick
Method m = device.getClass().getMethod("createInsecureRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, params);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
#SuppressLint("NewApi")
public void run() {
// DebugLog.i(TAG, "Trying to connect...");
// Cancel discovery because it will slow down the connection
MainActivity.mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
boolean val=mmSocket.isConnected();
Log.v("val", ""+val);
// DebugLog.i(TAG, "Connection stablished");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
// DebugLog.e(TAG, "Fail to connect!", connectException);
try {
mmSocket.close();
} catch (IOException closeException) {
// DebugLog.e(TAG, "Fail to close connection", closeException);
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
You have to implement an another thread, like below, which always receives your calls and does operations. Start this thread when you start the application.
class AcceptThread extends
Thread {
private final BluetoothServerSocket serverSocket;
private boolean flag = true;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter
.listenUsingInsecureRfcommWithServiceRecord(
NAME_UUID, uuid);
} catch (IOException e) {
}
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = serverSocket.accept();
if (socket.isConnected()) {
Log.d(TAG, "run: connection successfull");
Log.d(TAG, "run: " + socket.getRemoteDevice().getName() + " " +
socket.getRemoteDevice().getAddress());
}
} catch (IOException e) {
try {
socket.close();
} catch (Exception eee) {
Log.d(TAG, "run: " + eee.getMessage());
}
break;
}
}
}
public void cancel() {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}
I am pretty new to both arduino as well as the android domains. I am using arduino to send data to android using bluetooth module(linvor JY-MCU v.1.05). It is communicating with my app perfectly but i am not able to receive any data for this particular app. I am transferring a packet from arduino => ( $ 43 56 ! ) I want to extract it and display numbers alone on the android app.
Here $-header, 43-hr value, 56-temp value, !-footer
My arduino code is as follows:
#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);
}
The string is like a packet. I want 43 to be displayed in an editbox and 56 to be displayed in a text box.
My android code is a vast one that checks bluetooth connectivity too. So i am limiting it to just a section. Could someone please help me out with the coding part of it to just display the two sets of numbers in two txtView1 and txtView2 respectively....
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;
}
*/
}
}
}
}
Someone please help me out soon. I have been stuck up with dis for over a week. Thanking you in advance.
Sanj
"Case receive" and "Run" are the loops where the change has to be made.
Finding the index of a character "indexOf()" provides an error(string index out of bound).
I have tried switching off the bluetooth after entering the case receive block too but in vain.
Hoping to find a solution.
what does Message contains? with
byte[] readBuf = (byte[]) msg.obj;
String header = new String(readBuf, 0, msg.arg1);
all the consecutive
byte[] readBuf2 = (byte[]) msg.obj;
String hr = new String(readBuf2, 0, msg.arg1);
you are extrancing always the same data.
given the fact that in obj there are the chars between $ and ! included, then you can read all message
byte[] readBuf = (byte[]) msg.obj;
String message = new String(readBuf, 0, msg.arg1);
and then extract all the line
String[] cell = message.split("\n");
txtView1.setText("HR:" +cell[1]);
[...]
if in obj instead there are some byte[], then you have to add them to a buffer, then you remove all byte until $, add byte[] until you find a !, extract and remove from the buffer the data between the two delimeter, inclusive, and do what i said before. (well, this is just one solution)
Now right off the bat I haven't used bluetooth before but I'd say that the problem could be at these lines:
mySerial.println("$"); // print message
mySerial.println(23);
mySerial.println(546);
mySerial.println("!");
Because you are using println(); you send the message at each line as a separate packet hence the receiving end can't split it up and use the information.
I had a similar problem and fixed it by simply putting all the data needed in one string and the sending the whole string once.
The arduino coding language also for some reason cant join an integer and a string to another string just like that, It took me a while to figure it out but you simply have to use lines similar to this:
String output = "$";
output += 23; //or "23", not sure if it matters which one you use.
output += 546;
output += "!";
mySerial.println(output);