I agree with both previous answers. Nick Gammon gives excellent advise
on how to handle this situation, and Rohit Gupta gives you the gist of
print(). I would like to elaborate on this
print() distinction though.
These methods of the Arduino API can be confusing, as they have many
Let's look at
write() first, as it is the simplest of them:
size_t write(const uint8_t *buffer, size_t size);
These are meant to send a single byte and an array of bytes
respectively. You can send arbitrary bytes, which is usually termed
“binary data”. Note that any data, including text, is binary data: the
term binary here simply means that there is no restriction on the
bytes you can send.
size_t write(const char *buffer, size_t size);
This is the same as the previous one, for the case when the buffer is of
type “array of char”. It can still send arbitrary data.
size_t write(const char *str);
This is a version for sending C-strings, i.e. NUL-terminated buffers.
This one cannot send a zero byte, as that byte is interpreted as a
string terminator. It is thus inappropriate for sending binary (in the
sense of “arbitrary”) data. For this reason, I believe the inclusion of
this overload is a mistake made by the designers of the API, and I would
avoid it in preference of
print() which, for this type of argument,
does exactly the same thing.
Note that, in every instance,
write() takes the data you give it and
sends it as-is. There is no attempt at formatting it in any manner.
As stated by Rohit Gupta,
print() is meant for sending text. If you
have some data to send that is text to start with (like a literal
print() sends it as-is, and is thus quite similar to
write(). This is the case for the following overloads:
size_t print(const String &); // sends a String object
size_t print(const char); // sends a C-string
size_t print(char); // sends a single character
Then you have some overloads for printing various kinds of numbers. All
of these involve a binary-to-text conversion. The two remaining
overloads, which involve
Printable, are a
bit too technical and I will not discuss them here.
All the statements below do the same thing, they send "A" through the
Serial.write(65); // sends a byte with binary value 65
Serial.write('A'); // the ASCII code of 'A' is 65
Serial.print('A'); // a char is print()ed by sending it as-is
Serial.print(char(65)); // 'A' is a shortcut for char(65)
Serial.print("A"); // a one-character string
All the statements below send "65" through the serial port:
Serial.write(54); Serial.write(53); // send two binary values
Serial.write('6'); Serial.write('5'); // ASCII('6') = 54...
Serial.write("65"); // sends text in a pre-formatted buffer
Serial.print("65"); // same
Serial.print(65); // print() does the number-to-text conversion
Serial.print(int('A')); // same
As a general rule, I recommend to always use
print() for sending text,
write() only for sending data that is not (reliably known to