I have successfully interfaced my Arduino Mega and accelerometer with Java, however I have a problem.
As the clocks aren't synced when I write to the USB and read from USB, I don't get the whole 'packet' i.e. I sometimes read half of it ( its probably being read as its being written).
I tried implementing some sort of ACK type packet switching, but thats not working too well. Just wondered if you guys have any bright ideas?
I think the problem is that the Arduino board has a clock that ticks independantly from my computers clock. Therefore my java program reads indepentantly to the Arduino board tht is writing to the same place, therefore it 'reads' before all the data has been written to the USB.
My question is, what is a good way of buffering this, or just anything that might get around this problem: I need to process this data in its full form.
I think the problem is that the Arduino board has a clock that ticks independantly from my computers clock.
What ever your problem is it is not this. This is totally irrelevant for an asynchronous communication system. That is communication between arduino and PC.
Do you know what it could be why Im reading say 3 lots of results rather than 1? This indicates to me that the Arduino has pushed on 3 lots of data, and is read off at a slower rate. I understand Im probably barking up the wrong tree with the clock rate, however there must be something wrong here, i.e. I dont understand why the Arduino won't wait until their is no data left on the output stream before sending more data.
Could that instead be the problem? i.e. I need to implement a check to make sure the output stream is clear?
I dont understand why the Arduino won't wait until their is no data left on the output stream before sending more data.
Serial communication is asynchronous. That means that one side does not wait for the other side. It works like a postal system. I can send you a letter. I can wait a couple days, and send you another letter. Then, I could wait for you to reply to both letters before sending another one.
You could reply to the first letter, and then reply to the second letter, or you could wait until you got both letters, and reply to both in one letter.
If you want the Arduino to wait until the Java application has processed the first packet, you can do that.
Have the Arduino send a packet. Then, have it wait for a reply from the Java application.
Have the Java application send a message when it has completed processing a packet.
Buffer the data from the serial input, then split the buffer at the linefeed and process the data before the LF, then wait for the buffer to fill with data for the next LF (hex 0x13 iirc)
"SerialPortEvent.DATA_AVAILABLE" doesn't mean it has got all the data you want, only that "some data" is available. The serial code at