Read/Write Access to a Sun SPOT

So while I'm in the “use[ full | less ]” Sun SPOT tips mood, I thought I'd post this one. Since I just worked it out this morning, and since it is directly related to the previous 'tip'.


How would you implement a 'console' application on a Sun SPOT? Well, the bigger question of course is “why would you want to?” but that's a bigger question, so I will ignore it. But it is possible. Being a CLDC Device, the Sun SPOT has a System.out (as you are probably aware) but no System.in. So while your application can simply do a “System.out.println(“Foobar”); and that message will show up on a connected terminal of your host computer, you cannot read input from that computer via System.in as you might on a regular J2SE application.


But there is a way around that. If you poke around in the Sun SPOT Developer's Guide, you will find (on page 30, in case you're interested) a brief description of using the serial port of the Sun SPOT.



InputStream input = Connector.openInputStream("serial://usb”);

OutputStream output = Connector.openOutputStream(“serial://usb”);



Will open the input and output streams, respectively, of a USB-connected Sun SPOT.



while(true) {

   try {

   StringBuffer myBuf = new StringBuffer();

       int character;

   while ((character = input.read()) != (char)'\\n') {


    if((char)character == '\\r') break;

    myBuf.append((char)character);

    leds[0].setOn();

    } // Blink LED

    leds[0].setOff();

    String outString = "Read String: " + myBuf.toString() + "\\n";

    output.write(outString.getBytes());

     output.flush();  

} catch (IOException ex) {

   ex.printStackTrace();

}

}


Is all you really need. That will read input from the terminal, and echo it back after you hit return. Not very useful, but it could be used to send commands to an attached device (which is what I'm going to be doing. Watch for a post on controlling a BlueTooth Module attached to the eDemoBoard UART shortly).


But how does this relate to the BootLoaderListener thread from my previous post? Well, it turns out that if you followed my advice on that post, this code will fail. The BootLoaderListener will grab the serial UART, so your attempt to do so will generate a fatal exception. So while it is (generally) a good idea to run that thread, in this particular case it is a bad idea.


More to come on the BlueTooth Module as I get there.


[ A fool must now and then be right by chance. ]

Comments:

Dave,

Thanks for the post. I'll be really interested to see the post on Bluetooth.

Posted by Bruce Hopkins on January 09, 2009 at 02:57 PM EST #

Post a Comment:
Comments are closed for this entry.
About

user9157252

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today