The following exercise might help you to understand between print() and write() methods.
1. Given the following:
byte y1 = 0x41;
char y2 = 0x41;
2. Now execute the following codes on the variables of Step-1 and observe the results on the Serial Monitor.
Serial.println(y1); //shows: 65
Serial.println(y2); //shows: A
3. Why are the outputs different in Step-2 while the contents of the variables (y1, y2) are same?
Ans:
The data types are checked by the print() method.
Serial.println(y1); is not executed; rather it is broken down to two write() methods as shown below, which are executed.
==> Serial.println(0x41, DEC); //not executed
==> Serial.println(65, DEC); //not executed
==> Serial.write(0x36); //executed and 6 appears on SM
==> Serial.write(0x35); // executed and 5 appears on SM
Serial.prinln(y2); is not executed; rather, it is broken down to the following write() method which is executed.
==> Serial.write(0x41); //executed and A appears on SM
4. Now execute the following codes on the variables of Step-1 and observe the results on the Serial Monitor.
Serial.write(y1); //shows: A
Serial.write(y2); //shows: A
5. Why are the outputs same while the data types are different?
Ans:
Serial.write() method sends the 8-bit content of the variables to the Serial Monitor, which are 0x41. The Serial Monitor is an ASCII-type Monitor and 0x41 is the ASCII code for the character A; as a result, A appears on SM.
6. You can execute the following code to verify the above proposition:
int y = 0x4241;
Serial.print(y);
==> Serial.write(0x41); //shows: A