0

I am fairly new to Java, but with a rather complicated question.

We are looking at reading some bytes coming in from an Arduino. The Arduino sends bytes in the form:

 Serial.print(Voltage1);
 Serial.print(voltage2);

Since these voltages are numbers of the format "1.62", two digits after the decimal point, the Arduino sends 8 bytes, 4 for each voltage.

Previously in a MATLAB test we managed that by making the inputbuffer=8, and then splitting the bytes by doing something of the sort A=buffer(1:4) B=buffer(5:8), and as such we could plot or read the signals from the Arduino.

Is there a way to achieve this in Java? At the moment we are creating an input stream, and we tried to limit that to a buffer of the correct size, but we do not get anything even close to the expected. Most of the time our input from inputstream.read() gives us negatives, but not even something that we can understand or work with.

I hope this is well explained, and I really wish someone knows how to deal with this problem.

closed as off-topic by Mattia, Dat Ha, KIIV, jfpoilpret, Roberto Lo Giacco Nov 8 '16 at 23:58

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – Mattia, KIIV, jfpoilpret
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Not easily and reliably - your whole methodology is flawed from the start. – Majenko Oct 24 '16 at 10:07
  • 1
    Read and digest - the theory (if not the actual code) is valid for all programming languages, including Java. hackingmajenkoblog.wordpress.com/2016/02/01/… – Majenko Oct 24 '16 at 10:08
  • You should read till the next newline, and then convert the read data to a decimal value. – Gerben Oct 24 '16 at 12:50
  • Can you give little more explanation Are you asking how to receive Serial messages from JAVA If that's the case you may use JAVA COMM API This isn't an cross platform API. I have done it on windows OS (10 & 7) they worked fine and still are. – Adarsh R Jayan Oct 25 '16 at 20:36
  • Your question seems to be more about Java programming (out of scope of this site) than Arduino. – jfpoilpret Oct 26 '16 at 7:15
1

The standard way of doing this is to use delimiters. Serial is a streaming protocol, you don't necessarily get data in fixed size chunks. Something suitable would be like:

<1.23,4.56>

Notice the delimiters "<", "," and ">".

The receiving end ignores incoming data until it gets "<". Then it reads until it gets a comma. Between those two are the first number. Then it reads again until it gets a ">". Between those are the second number. Now you validate that what you got are in fact numbers.

This allows you to easily expand in the future to larger numbers, and more decimal places, eg.

<42.213,674.50326>

Not the answer you're looking for? Browse other questions tagged or ask your own question.