I have not found any random numbers!
1. This is the layout (Fig-1) of the Serial Monitor.
2. This is the ASCII Code Table (Fig-2).
3. This is the sketch that you have uploaded in Arduino UNO.
value = Serial.read();
4. Choose 'No line ending" option for the "Line ending tab" of Serial Monitor (SM, Fig-1).
5. Enter 2 in the InputBox of SM and click on the Send button.
6. What do you you expect to see on the OutputBox of SM? 50 or random numbers?
(1) In response to the action of Step-5, the code 32 (ASCII Code of 2 in hex base, Fig-2) which is 8-bit (00110010) has arrived to the UNO and been stored in Serial Buffer.
(2) You have executed the following code to bring 32 (00110010) from Serial Buffer and keep it into integer type (16-bit) variable value. As you have declared value as a global variable, it has been initialized to 0x0000.
value = Serial.read();
(3) 32 (00110011) will occupy the lower 8-bit of value and the upper 8-bit of value variable will remain as 0s(00000000). (For the data source of upper 8-bit, see Note at the end of post.)
(4) You have executed the following line to show the content of the variable value onto the OutputBox of SM.
Serial.println(value); //default base is DECimal (10); so, 32 (hex base) will be shown as decimal 50
==> Serial.println(value, DEC);
(5) The OutputBox of SM shows: 50 in SM (Fig-3).
value = 0032 in hex
==> value = 3x161 + 2x160 = 48 + 2 = 50 in decimal.
(6) To see the character (that was entered in the InputBox) back on the OutputBox, the following code could be added in the sketch. The SM now shows (50) 2 (Fig-4).
Serial.println((char)value); //print the character for the ASCII value of 0x32 (50)
(7) The Serial.println(value) command is actually composed two subcommands:
==> Serial.print(value); //ASCII code 0x32 (0x means hex base) travels towards SM
==> Serial.println(); //ASCII code 0x0A (10) for Newline (non-printable char) goes to SM
The Serial.println() command brings the cursor at the next line (also called Line Feed = LF) position.
** **8)** **
To verify that Serial.println() really sends ASCII code 0x0A (10), choose Newline option for the Line ending tab of SM and then goto Step-4(5). We will observe the following output (Fig-5) on SM.
Note: The meaning of: int value = Serial.read() returns 16-bit value.
(1) Lower 8-bit of the variable value comes from the Serial Buffer (the ASCII code of 2 in this example).
(2) The upper 8-bit of the value variable comes from UCSR0A Register of MCU. It might have value other than 0 if there happens to be some errors in the received data byte that is coming from Serial Monitor. The errors could be framing error, data overrun etc.