2

I am trying to use the arduinon Serial.write(buf, leng). here is my code

byte buf[] = {125, 126, 127, 128, 129};

void setup() {
  // initialize serial:
  Serial.begin(9600);

}

void loop() {
  int i = Serial.write(buf, sizeof(buf));
  Serial.println(i);
  delay(1000);
}

However, when I open up the serial monitor this is what it prints out

}~   5
}~   5
}~   5
}~   5

First off, I read that write writes binary data to the serial port and that print is the ascii characters. How come I see ascii characters?

The second question is how come nothing over 127 appears?

Whenever I Serial.write(>127) it always shows in the serial monitor a goofy output?

Is it because of the computer's side of serial?

My main goal is to write 32 bytes to serial all at once so they are all in the same payload of my xbee transmitting package. ??

1 Answer 1

2

The output is correct. You are writing binary data, but you are trying to see them as ASCII, that's why you see for example } instead of 125, because the one byte 125 represents } in ASCII. 125 would take 3 bytes to show as ASCII.

You are seeing weird stuff when you write an byte greater than 127, because ASCII only includes definitions for 128 characters (0 to 127).

If on the receiving circuit you want to read the exact same array you have on your code here, then your sketch is fine. You'll just have to use some kind of "serial read", and use the numbers as you want, keeping in mind each number has a byte size.

On the other hand, if you want to see the numbers on a serial monitor, represented as ASCII characters, you will either have to convert these numbers to ASCII code, or just use a loop printing the numbers as integers with the println function:

int numbers[] = {125, 126, 127, 128, 129};
for(int i = 0; i < (sizeof(numbers) / sizeof(numbers[0])); i++)
    Serial.println(numbers[i]);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it makes sense that the actuall functionality is fine, just the serial monitor that starts screwing it all up. cheers
I have the same problem. When I use Serial.print(124), In Arduino I get three separate values. I get the ascii code for "1", the ascii code for "2" and the ascii code for "4". How can I just send a simple value from arduino, and then read it with processing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.