Simple Question I expect

Post your NXJ projects, project ideas, etc here!

Moderators: 99jonathan, roger, imaqine

Simple Question I expect

Postby mattaseymour » Tue Mar 17, 2009 2:06 pm

I am wanting to read data via bluetooth to the lego mindstorm NXT brick. The current problem I have is that the DataInputStream.read(byte[]) returns an int.

How do I read an ASCII string through bluetooth as a byte array?
mattaseymour
New User
 
Posts: 8
Joined: Tue Mar 17, 2009 2:04 pm
Location: England

Postby lawrie » Tue Mar 17, 2009 5:47 pm

That method reads data into the byte array and returns the number of bytes read. You can send asciii data as bytes by casting each byte to a char.

For example:

Code: Select all
void sendAscii(String s, DataOutputStream dos) throws IOException {
  byte[] b = new byte[s.length()];

  for(int i =0;i<s.length();i++) {
    b[i] = (byte) s.charAt(i);
  }

  dos.writeInt(s.length];
  dos.write(b);
  dos.flush();
}

String readAscii(DataInputStream dis)  throws IOException {
  int sl = dis.readInt();

  byte[] b = new byte[sl];
  StringBuffer sb = new StringBuffer();

  int l = dis.read(b);

  for(int i=0;i<l;i++) {
    sb.append((char) b[i]);
  }

  return sb.toString();
}


You can read and write characters instead of bytes on the data streams if you prefer. The readLine() method of DataInputStream does this.
lawrie
leJOS Team Member
 
Posts: 929
Joined: Mon Feb 05, 2007 1:27 pm


Return to NXJ Projects

Who is online

Users browsing this forum: No registered users and 1 guest

more stuff