2
votes

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

1 Answers

2
votes

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]);