Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: Help with serial read-in

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Help with serial read-in

    Hi I have the following code which reads in data from a bluetooth transmitter, however the program is crashing upon read-in. The bluetooth connects to the device just fine, as indicated by the indicator LED on the transmitter. However during the read-in:

    void beginListenForData()

    is where the exception happens. Specifically, it is at the line

    readBuffer[readBufferPosition++] = b;

    however I don't know why it is crashing. My transmitter is sending 1 byte (0x02) at 9600 baud every 1 sec for testing purposes.

     
    package com.example.bluetoothtest2;
    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.util.Log;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.EditText;  
    import android.widget.Button;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Set;
    import java.util.UUID;
     
    public class MainActivity extends Activity
    {
    TextView myLabel;
    EditText myTextbox;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;
    String tag = "debugging";
     
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        Button openButton = (Button)findViewById(R.id.open);
        Button sendButton = (Button)findViewById(R.id.send);
        Button closeButton = (Button)findViewById(R.id.close);
        myLabel = (TextView)findViewById(R.id.label);
        myTextbox = (EditText)findViewById(R.id.entry);
     
        //Open Button
        openButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try 
                {
                    findBT();
                    openBT();
                }
                catch (IOException ex) { }
            }
        });
     
        //Send Button
        sendButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try 
                {
                    sendData();
                }
                catch (IOException ex) { }
            }
        });
     
        //Close button
        closeButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try 
                {
                    closeBT();
                }
                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("RN42-403A")) 
                {
                    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
     
        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1];
        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++)
                            { Log.i(tag, "in for loop");
                                System.out.println(i);
                                byte b = packetBytes[i];
                                System.out.println(b);
                                Log.i(tag, "after b");
                                if(b == delimiter) //THIS IS THE PROBLEM, NEVER ENTERS THis IF STATEMENT
                                { Log.i(tag, "reach delim");
         byte[] encodedBytes = new byte[readBufferPosition];
         System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
         final String data = new String(encodedBytes, "US-ASCII");
         readBufferPosition = 0;
         Log.i(tag, "Read buff 0");
                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            myLabel.setText(data);
                                            Log.i(tag, "set text");
                                        }
                                    });
                                }
                                else
                                {
                                	System.out.println(b);
                                    readBuffer[readBufferPosition++] = b;
                                    Log.i(tag, "Read buff");
                                }
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });
     
        workerThread.start();
    }
     
    void sendData() throws IOException
    {
        String msg = myTextbox.getText().toString();
        msg += "\n";
        mmOutputStream.write(msg.getBytes());
        myLabel.setText("Data Sent");
    }
     
    void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }
    }
    Attached Images Attached Images
    Last edited by baseball07; March 12th, 2014 at 02:46 PM. Reason: Updated code


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    where the exception happens
    Please copy the contents of the logcat and paste it here showing the exception.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    Hi, I have attached a picture of the logcat to my original post.

  4. #4
    Member
    Join Date
    Mar 2012
    Location
    United States
    Posts
    118
    My Mood
    Inspired
    Thanks
    1
    Thanked 33 Times in 31 Posts

    Default Re: Help with serial read-in

    It is tiny and barely readable that is why Norm would like you to paste the text.
    On another note this:
    readBuffer[readBufferPosition++] = b;
    seems suspect to me since that would mean readBuffer[1] which would be an indexoutofbounds exception but without being able to read the text in the picture, can't be sure if that is really affecting anything.


    You seem to believe that b == delimiter will be true at some point, perhaps print the value of b just to see what is going on with that.
    Last edited by KucerakJM; March 8th, 2014 at 09:09 AM. Reason: brain told me to

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    There is a button with the Logcat that saves its contents to where it can be copied.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    Hey guys, my appologies, I was not aware my attachment was so small. Here is logcat. Note the code doesn't reach the if statement

    03-08 14:29:02.240: D/libEGL(1652): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_130.so
    03-08 14:29:02.270: D/libEGL(1652): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_130.so
    03-08 14:29:02.270: D/libEGL(1652): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_130.so
    03-08 14:29:02.350: D/OpenGLRenderer(1652): Enabling debug mode 0
    03-08 14:29:02.350: W/HardwareRenderer(1652): Backbuffer cannot be preserved
    03-08 14:29:19.220: W/BluetoothAdapter(1652): getBluetoothService() called with no BluetoothManagerCallback
    03-08 14:29:19.230: D/BluetoothSocket(1652): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[49]}
    03-08 14:29:22.160: I/Choreographer(1652): Skipped 172 frames!  The application may be doing too much work on its main thread.
    03-08 14:29:22.310: I/debugging(1652): in for loop
    03-08 14:29:22.310: I/debugging(1652): after b
    03-08 14:29:22.310: I/debugging(1652): Read buff
    03-08 14:29:22.340: I/debugging(1652): in for loop
    03-08 14:29:22.340: I/debugging(1652): after b
    03-08 14:29:22.340: W/dalvikvm(1652): threadid=14: thread exiting with uncaught exception (group=0x41b9c930)
    03-08 14:29:22.340: E/AndroidRuntime(1652): FATAL EXCEPTION: Thread-153
    03-08 14:29:22.340: E/AndroidRuntime(1652): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    03-08 14:29:22.340: E/AndroidRuntime(1652): 	at com.example.bluetoothtest2.MainActivity$4.run(MainActivity.java:174)
    03-08 14:29:22.340: E/AndroidRuntime(1652): 	at java.lang.Thread.run(Thread.java:856)
    03-08 14:29:32.570: I/Process(1652): Sending signal. PID: 1652 SIG: 9

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    03-08 14:29:22.340: E/AndroidRuntime(1652): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    03-08 14:29:22.340: E/AndroidRuntime(1652): at com.example.bluetoothtest2.MainActivity$4.run(Main Activity.java:174)
    The code at line 174 used an index with a value of 1 with an array with only 1 element (max index would be 0)
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Member
    Join Date
    Mar 2012
    Location
    United States
    Posts
    118
    My Mood
    Inspired
    Thanks
    1
    Thanked 33 Times in 31 Posts

    Default Re: Help with serial read-in

    I am betting line 174 is
    readBuffer[readBufferPosition++] = b;
    Please consider my suggestion of printing the value (or perhaps logging it) of b.

  9. #9
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    Thanks Norm. My initial thought was a problem with the readbuffer array size and/or for loop, however any array size throws an exception, and I also tried changing the loop to for(int i=0;i <= bytesAvailable;i++). Is this what you are refering to?

    --- Update ---

    Ok, I will try that. Isn't that just checking for the delimiter though? I don't understand what the problem would be there.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    The code needs some println() statements to print out the values of the variables it is working with so you can see what the computer sees when the code executes.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    I have printed the variable "i" and "b" at various locations, see the attached logcat and updated code. My bluetooth device is broadcasting 1 byte of data every 1 sec (the value 0x02). "i" is reading out as 0 and "b" is reading out as 2 (in logcat). I am still unsure as to what is causing the crash. It is indeed happening at

    readBuffer[readBufferPosition++] = b;

    The log that comes after this line is not printed, however the value of b is printed out just before.

     
    03-12 12:35:16.820: D/libEGL(2187): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_130.so
    03-12 12:35:16.830: D/libEGL(2187): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_130.so
    03-12 12:35:16.840: D/libEGL(2187): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_130.so
    03-12 12:35:16.910: D/OpenGLRenderer(2187): Enabling debug mode 0
    03-12 12:35:16.910: W/HardwareRenderer(2187): Backbuffer cannot be preserved
    03-12 12:35:20.210: W/BluetoothAdapter(2187): getBluetoothService() called with no BluetoothManagerCallback
    03-12 12:35:20.210: D/BluetoothSocket(2187): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[49]}
    03-12 12:35:22.810: I/Choreographer(2187): Skipped 152 frames!  The application may be doing too much work on its main thread.
    03-12 12:35:23.570: I/debugging(2187): in for loop
    03-12 12:35:23.570: I/System.out(2187): 0
    03-12 12:35:23.570: I/System.out(2187): 2
    03-12 12:35:23.570: I/debugging(2187): after b
    03-12 12:35:23.570: I/System.out(2187): 2
    03-12 12:35:23.570: I/debugging(2187): Read buff
    03-12 12:35:24.620: I/debugging(2187): in for loop
    03-12 12:35:24.620: I/System.out(2187): 0
    03-12 12:35:24.620: I/System.out(2187): 2
    03-12 12:35:24.620: I/debugging(2187): after b
    03-12 12:35:24.620: I/System.out(2187): 2
    03-12 12:35:24.620: W/dalvikvm(2187): threadid=13: thread exiting with uncaught exception (group=0x40c1b930)
    03-12 12:35:24.620: E/AndroidRuntime(2187): FATAL EXCEPTION: Thread-194
    03-12 12:35:24.620: E/AndroidRuntime(2187): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    03-12 12:35:24.620: E/AndroidRuntime(2187): 	at com.example.bluetoothtest2.MainActivity$4.run(MainActivity.java:177)
    03-12 12:35:24.620: E/AndroidRuntime(2187): 	at java.lang.Thread.run(Thread.java:856)

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    what is causing the crash.
    The code is using an index of 1 with an array of length 1 at line 177. Max index for an array of length 1 is 0

    The debug output printed by your println()s should show the length of the array and the index being used.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    Thanks for the feedback, its lots of help, I have used println() on many variables to see what is going on, and I found that I was indexing incorrectly as per your suggestion. I am now having issues with what seems like formatting. I have carried out the simplest scenario, I am sending one byte of the value 2 (0x02), and have set the delimiter as 2, so then it enters the portion which displays the result (if b==delimiter). However, the value of "readBuffer" is displaying as [B@40f125a8. And I am not seeing it on the UI.

     
     
    void beginListenForData()
    {
        final Handler handler = new Handler(); 
        final byte delimiter = 2; //This is the ASCII code for a newline character
     
        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[0];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {                
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try 
                    {
                        int bytesAvailable = mmInputStream.available(); 
                        //System.out.println(bytesAvailable);
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
     
                            for(int i=0;i<bytesAvailable;i++)
                            {
                            	Log.i(tag, "in for loop");
                            	System.out.println("Buffer Position = " +readBufferPosition);
                               	System.out.println("i =" +i);
                                byte b = packetBytes[i];
                                System.out.println("b =" +b);
                                System.out.println("read buffer =" +readBuffer);                          
                                if(b == delimiter) 
                                {
                                	Log.i(tag, "reach delim");
                                	byte[] encodedBytes = new byte[readBufferPosition];
                                	System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);  
                                	final String data = new String(encodedBytes, "US-ASCII");
                                	System.out.println("string =" +data);
                                	readBufferPosition = 0;
     
                                    handler.post(new Runnable()
                                    		{
                                				public void run()
                                				{
                                        	        myLabel.setText(data);
                                        	        Log.i(tag, "set text");
                                				}
                                    		});
                                	}
                                else
                                	{
                                	System.out.println("else read buff position =" +readBufferPosition);
                                	readBuffer[readBufferPosition++] = b;   //readBufferPosition++
                                    System.out.println("buff++ b =" +b);
     
                                	}
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });

    03-13 09:59:34.582: I/Choreographer(6171): Skipped 104 frames!  The application may be doing too much work on its main thread.
    03-13 09:59:35.332: I/debugging(6171): in for loop
    03-13 09:59:35.332: I/System.out(6171): Buffer Position = 0
    03-13 09:59:35.332: I/System.out(6171): i =0
    03-13 09:59:35.332: I/System.out(6171): b =2
    03-13 09:59:35.332: I/System.out(6171): read buffer =[B@40f0dfd8
    03-13 09:59:35.332: I/debugging(6171): reach delim
    03-13 09:59:35.332: I/System.out(6171): string =
    03-13 09:59:35.332: I/debugging(6171): set text

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    the value of "readBuffer" is displaying as [B@40f125a8.
    That String is the value returned from the default toString() method of a byte array. To format the contents of an array for printing use the Arrays class's toString() method:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    baseball07 (March 17th, 2014)

  16. #15
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    Thank you I was unaware of that. Something is still not right though. The buffer value is showing up as [] and the final string is blank in logcat. I confirmed that the buffer position is OK, as it is 0, the first position. I am transmitting a 42 (0x2A) which should be * in ascii.


    void beginListenForData()
    {
        final Handler handler = new Handler(); 
        final byte delimiter = 42; //This is the ASCII code for a newline character
     
        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[0];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {                
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try 
                    {
                        int bytesAvailable = mmInputStream.available(); 
                        //System.out.println(bytesAvailable);
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
     
                            for(int i=0;i<bytesAvailable;i++)
                            {
                            	Log.i(tag, "in for loop");
                            	System.out.println("Buffer Position = " +readBufferPosition);
                               	System.out.println("i =" +i);
                                byte b = packetBytes[i];
                                System.out.println("b =" +b);
                                System.out.println("read buffer =" +readBuffer);                          
                                if(b == delimiter) 
                                {
                                	System.out.println("ReadBuffer"+ java.util.Arrays.toString(readBuffer));
                                	Log.i(tag, "reach delim");
                                	System.out.println("Buffer Position = " +readBufferPosition);
                                	byte[] encodedBytes = new byte[readBufferPosition];
                                	System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);  
                                	System.out.println("ReadBuffer"+ java.util.Arrays.toString(encodedBytes));
                                	final String data = new String(encodedBytes, "US-ASCII");
     
                                	readBufferPosition = 0;
     
                                    handler.post(new Runnable()
                                    		{
                                				public void run()
                                				{
                                					System.out.println("String Data = " +data);
                                					myLabel.setText(data);
                                        	        Log.i(tag, "set text");
                                				}
                                    		});
                                	}
                                else
                                	{
                                	System.out.println("else read buff position =" +readBufferPosition);
                                	readBuffer[readBufferPosition++] = b;   //readBufferPosition++
                                    System.out.println("buff++ b =" +b);
     
                                	}
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });
     
        workerThread.start();
    }

    03-13 13:22:15.332: I/Choreographer(8156): Skipped 70 frames!  The application may be doing too much work on its main thread.
    03-13 13:22:15.522: I/debugging(8156): in for loop
    03-13 13:22:15.522: I/System.out(8156): Buffer Position = 0
    03-13 13:22:15.522: I/System.out(8156): i =0
    03-13 13:22:15.522: I/System.out(8156): b =42
    03-13 13:22:15.522: I/System.out(8156): read buffer =[B@40f02eb8
    03-13 13:22:15.522: I/System.out(8156): ReadBuffer[]
    03-13 13:22:15.522: I/debugging(8156): reach delim
    03-13 13:22:15.522: I/System.out(8156): Buffer Position = 0
    03-13 13:22:15.522: I/System.out(8156): ReadBuffer[]
    03-13 13:22:15.522: I/System.out(8156): String Data = 
    03-13 13:22:15.522: I/debugging(8156): set text

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    readBuffer = new byte[0];
    Is an empty array which would print as []
    If you don't understand my answer, don't ignore it, ask a question.

  18. The Following User Says Thank You to Norm For This Useful Post:

    baseball07 (March 17th, 2014)

  19. #17
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    Hi yes thank you. I have actually tried many different array values and I still get the same thing. The code is reading it fine from the array, as the value of "b" is correct. It is just in that for loop for printing there seems to be some syntax problem.

  20. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    It is just in that for loop for printing there seems to be some syntax problem.
    Please post the code and what is printed by the println() in and around the loop.
    Be sure to use the Arrays class's toString() method, not just the array name like here:
    03-13 13:22:15.522: I/System.out(8156): read buffer =[B@40f02eb8
    If you don't understand my answer, don't ignore it, ask a question.

  21. The Following User Says Thank You to Norm For This Useful Post:

    baseball07 (March 17th, 2014)

  22. #19
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    This is the code and Logcat. I believe my indexing is correct. I am reading buffer position 0 which is the first index of the buffer where my data should be. I changed the initial Buffer read to 1, and the 2nd logcat reflects this. The variable "b" seems to be reading the correct value.

     
    void beginListenForData()
    {
        final Handler handler = new Handler(); 
        final byte delimiter = 42; //This is the ASCII code for a newline character
     
        stopWorker = false;
        readBufferPosition = 0; 
        readBuffer = new byte[1];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {                
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try 
                    {
                        int bytesAvailable = mmInputStream.available(); 
     
                        if(bytesAvailable > 0)
                        {
                        	System.out.println("Bytes available =" +bytesAvailable);	
                        	byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
     
                            for(int i=0;i<bytesAvailable;i++)
                            {
                            	Log.i(tag, "in for loop");
                            	System.out.println("i =" +i);
                            	System.out.println("Buffer Position = " +readBufferPosition);
                                byte b = packetBytes[i];
                                System.out.println("b =" +b);
                                System.out.println("ReadBuffer"+ java.util.Arrays.toString(readBuffer));                          
                                if(b == delimiter) 
                                {
                                	Log.i(tag, "if statement, reached dellimiter");
                                	System.out.println("ReadBuffer"+ java.util.Arrays.toString(readBuffer));
                                	System.out.println("Buffer Position = " +readBufferPosition);
                                	byte[] encodedBytes = new byte[readBufferPosition];
                                	System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);  
                                	System.out.println("EncodedBytes"+ java.util.Arrays.toString(encodedBytes));
                                	final String data = new String(encodedBytes, "US-ASCII");
     
                                	readBufferPosition = 0;
     
                                    handler.post(new Runnable()
                                    		{
                                				public void run()
                                				{
                                					System.out.println("StringData"+ data);
                                					myLabel.setText(data);
                                        	        Log.i(tag, "set text");
                                				}
                                    		});
                                	}
                                else
                                	{
                                	System.out.println("else read buff position =" +readBufferPosition);
                                	readBuffer[readBufferPosition++] = b;   //readBufferPosition++
                                    System.out.println("buff++ b =" +b);
     
                                	}
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });
     
        workerThread.start();
    }


    Read Buff Position = 0

     
    03-15 05:50:00.192: D/BluetoothSocket(4677): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[50]}
    03-15 05:50:00.192: D/alsa_pcm(107): pcm_open() period_cnt 6 period_sz 1024 channels 2
    03-15 05:50:00.192: I/alsa_mix(107): -->Playback Path access 3
    03-15 05:50:00.482: W/bt-btif(793): info:x0
    03-15 05:50:00.692: W/bt-sdp(793): process_service_search_attr_rsp
    03-15 05:50:01.142: I/Choreographer(4677): Skipped 55 frames!  The application may be doing too much work on its main thread.
    03-15 05:50:01.532: D/dalvikvm(4304): GC_CONCURRENT freed 411K, 10% free 4382K/4840K, paused 3ms+2ms, total 16ms
    03-15 05:50:01.632: D/Finsky(4304): [1] 5.onFinished: Installation state replication succeeded.
    03-15 05:50:01.682: I/System.out(4677): Bytes available =1
    03-15 05:50:01.682: I/debugging(4677): in for loop
    03-15 05:50:01.682: I/System.out(4677): i =0
    03-15 05:50:01.682: I/System.out(4677): Buffer Position = 0
    03-15 05:50:01.682: I/System.out(4677): b =42
    03-15 05:50:01.682: I/System.out(4677): ReadBuffer[0]
    03-15 05:50:01.682: I/debugging(4677): if statement, reached dellimiter
    03-15 05:50:01.682: I/System.out(4677): ReadBuffer[0]
    03-15 05:50:01.682: I/System.out(4677): Buffer Position = 0
    03-15 05:50:01.682: I/System.out(4677): EncodedBytes[]
    03-15 05:50:01.682: I/System.out(4677): StringData
    03-15 05:50:01.682: I/debugging(4677): set text
    03-15 05:50:02.692: I/System.out(4677): Bytes available =1
    03-15 05:50:02.692: I/debugging(4677): in for loop
    03-15 05:50:02.692: I/System.out(4677): i =0
    03-15 05:50:02.692: I/System.out(4677): Buffer Position = 0
    03-15 05:50:02.692: I/System.out(4677): b =42
    03-15 05:50:02.692: I/System.out(4677): ReadBuffer[0]
    03-15 05:50:02.692: I/debugging(4677): if statement, reached dellimiter
    03-15 05:50:02.692: I/System.out(4677): ReadBuffer[0]
    03-15 05:50:02.692: I/System.out(4677): Buffer Position = 0
    03-15 05:50:02.692: I/System.out(4677): EncodedBytes[]
    03-15 05:50:02.692: I/System.out(4677): StringData
    03-15 05:50:02.692: I/debugging(4677): set text

    Read Buff Position = 1

    03-15 05:55:12.512: I/Choreographer(4761): Skipped 129 frames!  The application may be doing too much work on its main thread.
    03-15 05:55:13.082: I/System.out(4761): Bytes available =1
    03-15 05:55:13.082: I/debugging(4761): in for loop
    03-15 05:55:13.082: I/System.out(4761): i =0
    03-15 05:55:13.082: I/System.out(4761): Buffer Position = 1
    03-15 05:55:13.082: I/System.out(4761): b =42
    03-15 05:55:13.082: I/System.out(4761): ReadBuffer[0]
    03-15 05:55:13.082: I/debugging(4761): if statement, reached dellimiter
    03-15 05:55:13.082: I/System.out(4761): ReadBuffer[0]
    03-15 05:55:13.082: I/System.out(4761): Buffer Position = 1
    03-15 05:55:13.082: I/System.out(4761): EncodedBytes[0]
    03-15 05:55:13.082: I/System.out(4761): StringData??
    03-15 05:55:13.082: I/debugging(4761): set text

  23. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

    Another help for debugging would be to save and print the value returned by the read() method.

    The debug output you posted shows that a byte with value 0 was in the buffer after the read. I don't know if read() will return a 0 for the number of bytes read.
    If you don't understand my answer, don't ignore it, ask a question.

  24. The Following User Says Thank You to Norm For This Useful Post:

    baseball07 (March 17th, 2014)

  25. #21
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Help with serial read-in

    The read function seems to be working fine, it is reading packetBytes as 0,
     
    byte[] packetBytes = new byte[bytesAvailable];

    and per the description on the oracle site, if len is zero, then no bytes are read and 0 is returned. However this is confusing because bytesAvailable is equal to 1, so the length is in fact 1, and further down in the code, packetBytes at the first index (b) is equal to 42

    byte b = packetBytes[i];

    So, how is the array empty?

    package com.example.biorasistest;
    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.util.Log;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.EditText;  
    import android.widget.Button;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Set;
    import java.util.UUID;
     
    import com.example.biorasistest.R;
     
    public class MainActivity extends Activity
    {
    TextView myLabel;
    EditText myTextbox;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;
    String tag = "debugging";
     
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        Button openButton = (Button)findViewById(R.id.open);
        Button closeButton = (Button)findViewById(R.id.close);
        myLabel = (TextView)findViewById(R.id.label);
     
        //Open Button
        openButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try 
                {
                    findBT();
                    openBT();
                }
                catch (IOException ex) { }
            }
        });
     
       //Close button
        closeButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try 
                {
                    closeBT();
                }
                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("RN42-403A")) 
                {
                    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 = 42; //This is the ASCII code for a newline character
     
        stopWorker = false;
        readBufferPosition = 1;  //was 0
        readBuffer = new byte[1];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {                
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try 
                    {
                        int bytesAvailable = mmInputStream.available(); 
     
                        if(bytesAvailable > 0)
                        {
                        	System.out.println("Bytes available =" +bytesAvailable);	
                        	byte[] packetBytes = new byte[bytesAvailable];
                        	System.out.println("packetBytes = "+ java.util.Arrays.toString(packetBytes));
                            mmInputStream.read(packetBytes);
     
                            for(int i=0;i<bytesAvailable;i++)
                            {
                            	Log.i(tag, "in for loop");
                            	System.out.println("i =" +i);
                            	System.out.println("Buffer Position = " +readBufferPosition);
                                byte b = packetBytes[i];
                                System.out.println("b =" +b);
                                System.out.println("ReadBuffer"+ java.util.Arrays.toString(readBuffer));                          
                                if(b == delimiter) 
                                {
                                	Log.i(tag, "if statement, reached dellimiter");
                                	System.out.println("ReadBuffer"+ java.util.Arrays.toString(readBuffer));
                                	System.out.println("Buffer Position = " +readBufferPosition);
                                	byte[] encodedBytes = new byte[readBufferPosition];
                                	System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);  
                                	System.out.println("EncodedBytes"+ java.util.Arrays.toString(encodedBytes));
                                	final String data = new String(encodedBytes, "US-ASCII");
     
                                	readBufferPosition = 0;
     
                                    handler.post(new Runnable()
                                    		{
                                				public void run()
                                				{
                                					System.out.println("StringData"+ data);
                                					myLabel.setText(data);
                                        	        Log.i(tag, "set text");
                                				}
                                    		});
                                	}
                                else
                                	{
                                	System.out.println("else read buff position =" +readBufferPosition);
                                	readBuffer[readBufferPosition++] = b;   //readBufferPosition++
                                    System.out.println("buff++ b =" +b);
     
                                	}
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });
     
        workerThread.start();
    }
     
     
    void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }
    }

    03-17 07:29:08.043: I/System.out(1672): Bytes available =1
    03-17 07:29:08.043: I/System.out(1672): packetBytes = [0]
    03-17 07:29:08.043: I/debugging(1672): in for loop
    03-17 07:29:08.043: I/System.out(1672): i =0
    03-17 07:29:08.043: I/System.out(1672): Buffer Position = 0
    03-17 07:29:08.043: I/System.out(1672): b =42
    03-17 07:29:08.043: I/System.out(1672): ReadBuffer[0]
    03-17 07:29:08.043: I/debugging(1672): if statement, reached dellimiter
    03-17 07:29:08.043: I/System.out(1672): ReadBuffer[0]
    03-17 07:29:08.043: I/System.out(1672): Buffer Position = 0
    03-17 07:29:08.043: I/System.out(1672): EncodedBytes[]
    03-17 07:29:08.043: I/System.out(1672): StringData
    03-17 07:29:08.043: I/debugging(1672): set text

  26. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,148
    Thanks
    65
    Thanked 2,721 Times in 2,671 Posts

    Default Re: Help with serial read-in

     mmInputStream.read(packetBytes);
    // vs
     int nbrRead = mmInputStream.read(packetBytes);
    The code doesn't capture and print out the value returned by the read() method.
    Does the read() read any bytes? Could it read byte(s) with value 0? Assign a value to the first element of the byte array before the read() and see if it was changed.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [Asking] Response Serial Conection
    By ardisamudra in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 21st, 2013, 12:22 AM
  2. Read input, read file, find match, and output... URGENT HELP!
    By MooseHead in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 3rd, 2012, 11:01 AM
  3. Java Serial RS232
    By Coveiro in forum Java Native Interface
    Replies: 0
    Last Post: October 7th, 2011, 11:28 PM
  4. Serial Bluetooth Programming
    By blackridinghood in forum Java ME (Mobile Edition)
    Replies: 0
    Last Post: January 28th, 2011, 11:15 AM
  5. List serial com ports of computer
    By mickey in forum Java Networking
    Replies: 2
    Last Post: August 6th, 2010, 01:44 AM