Serial: Sending Ints

Hi,

I'm pretty new to arduino an playing a bit around with it. Currently, I kind of fail interpreting ints I send via Serial to my PC. Thats my arduino code:

int interval = 1000;  
unsigned int count = 0;

void setup() {
  Serial.begin(9600);

}

void loop() {
  Serial.write(count);
  count++;
  delay(interval);
  
}

So I just send an increasing int via Serial. Unfortunately, I am not able to interpret the values I receive if count is greater then 127. Here is what I get (i just print each byte I receive to stdout using Java, first in binary (lsb first!) and then the number interpreted as signed byte).

00000000, 0
10000000, 1
01000000, 2
....
10111110, 125
01111110, 126
11111110, 127
01000011, -62
00000001, -128
01000011, -62
10000001, -127

So up to 127 my Arduino device sends one byte, if its greater then 127 two. But I do not see where is the 128 resp 129 in the 2 bytes. Can any body help me out?

What I would like best if i could send always two bytes representing my int in a way I can interpret is somehow on the other side.

Hope somebody can help, cya

SomeNewGuy

Have you tried using Serial.println(count); instead? The reason I ask is the serial monitor doesn't seem to like .write which you are using above, and it spits out what I assume to be the ascii table instead.

01000011, -62

01000011 is most definitely NOT negative.

a.d: Have you tried using Serial.println(count); instead? The reason I ask is the serial monitor doesn't seem to like .write which you are using above, and it spits out what I assume to be the ascii table instead.

Yes, I tried Serial.println(count) and this is working perfectly fine. But actually, I do not want do have a string representation for my int (e.g. 4947 is taking 4 bytes, one for each digit) whereas it is totally sufficient to spend 2 bytes for it. So I thought Serial.write() is doing this job and send the raw bytes that represent the int. I do not use the serial monitor but my own java application that is - for now - just grabbing the input from the serial port and writing it to the console. But what I want is parsing the int I send out of this data stream - but the received data looks quiet strange to me, so I do not know how to handle this.

AWOL:

01000011, -62

01000011 is most definitely NOT negative.

Note that the first bit is the least significant bit. Having this byte interpreted as Java-Byte, you wil end up with -62, since Java do not have any unsigned data types. So this seems correct to me. Please tell me if I am wrong.

If you are going to use a function that sends a byte (Serial.write()) you must not be surprised that it does not behave the way you expect when you pass it some other type.

You can use the Serial.write() method to send ints, but you must do it by making two calls, and sending the least significant byte and the most significant byte. Look at the highByte() and lowByte() functions.