Question

This question refers to writing an application that communicates with the NXT block on a lego mindstorms robot.

What I want to do

NXC (not exactly C, a language for writing programs for the NXT) supplies a function until(condition) that waits until condition evaluates to true. I want to implement this using the bluetooth messaging protocol, talking to the NXT via bluetooth from an android application.

What I can do so far:

I'm able to send an input query message (getInputValue(int in)), which sends a message to the NXT asking for the current status of the input in. The NXT then sends back a message with this information, which is then written to a global variable that holds the most recently asked input value (let's call it myValue).

What the problem is:

I'm using bits and pieces from the lego MINDroid application - in this class I have a separate communication thread which handles direct communication with the NXT. When it receives a message, it forwards it on to the main thread, via a Handler. The problem occurs when I try to busy wait for a reply - doing:

while(myValue != valueIWant) {
  sleep(100);
  getInputValue(in);
}

ends up busying the main thread, so that the handler never actually gets to receive any messages. The communication thread receives the messages from the NXT, forwards them to the main thread, but the handler never gets called because it's doing other stuff.

What's the best way to get around this? I can't get the thread to wait in any way because that would stop it receiving messages also :(

Any suggestions would be appreciated! I'll also happily elaborate on any bits of code.

Links that may be useful

http://bricxcc.sourceforge.net/nbc/nxcdoc/nxcapi/main.html

http://github.com/NXT/LEGO-MINDSTORMS-MINDdroid

http://mindstorms.lego.com/en-us/support/files/default.aspx (for the bluetooth docs)

Was it helpful?

Solution

Solved, using callbacks :) Happy to elaborate if needed.

Edit: (sorry for late reply!)

I ended up implementing a callback procedure, where I attached a 'callback' function to some list. When the handler receives a message, it would look in the list of callbacks and see if the message received matched any of the callback functions that are present - if so, it would execute the method inside the callback.

I then made a class around these callbacks, where I could create execution queues (doA; doB; doC;) and it would wrap those up into a callback chain (callBack({doA; callBack({doB; call...})})), which gave the impression that I was operating in a synchronous environment, when in fact it was operating asynchronously.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top