Ch-5 UART Port Based Serial Data Communication

5.1 Introduction
1. In ATmega328P MCU, there is a UART Port (Fig-5.1) to transfer data in serial format (bit-by-bit) to PC using TXD (transmit data line) and to receive data in serial format from the same PC using RXD (receive data line). UART Port stands for "Universal Asynchronous Reception and Transmission" Port.

ATmega328P MCU-এর মধ্যে, UART নামে একটি পোর্ট আছে (ছবি-৫.১)। MCU, এই পোর্টের TXD লাইন ব্যবহার করে PC-র কাছে ডাটা পাঁঠায় ১-বিট করে করে; আর, RXD লাইন ব্যবহার করে PC-র কাছ থেকে ডাটা গ্রহণ করে ১-বিট করে করে। তাহলে, বুঝা গেলো যে UART পোর্ট একটা Serial Communication পোর্ট।

unonano.png
Figure-5.1: UART and SUART Ports of Atmega328P MCU

2. There is only one hardware/electronic UART Port (UART) inside the MCU. It is permanently engaged with the PC and with the Serial Monitor (Fig-5.4) for data input/output purposes and with the IDE (Fig-5.1a) for sketch uploading.
ide.png
Figure-5.1a: IDE (integrated Development Environment) of Arduino Platform

3. If it is desired to exchange data between UNO and NANO (Fig-5.1) in UART protocol, then there is no more UART Port left. Under this circumstance, it is possible to create a software UART Port (SUART) (Fig-5.1) by which the two Arduinos of Fig-5.1 can exchange data serially. To create a SUART Port, the following codes are included in the appropriate places of a sketch.

#include<SoftwareSerial.h>
SoftwareSerial SUART(2, 3);  //SRXD = DPin-2, STXD = DPin-3 ; S stands for Software
SUART.begin(9600);      //SUART Port works well at this bit speed = bit/sec

4. In S/UART (SUART and UART) communication, data exchange takes place one byte (8-bit) at a time (byte-by-byte or character-by-character), which could be a natural binary number or an ASCII code of a printable character (Fig-5.2) of the English Language Alphabet (a-z, A-Z, punctuation marks like ! and others, special characters like $ and others). When ASCII codes are being transmitted and received, it is said that data exchange takes place character-by-character.


Figure-5.2: ASCII Codes Table

5. In Fig-5.3, it is shown how the ASCII code (0x41 in hex = 01000001 in binary) of character A travels over the TX-line of the UART Port. There is a 'START bit' (LOW), then the LSB bit, ..., and then 'STOP bit (HIGH)'. The parity bit is optional. These 10-bit (ignoring the parity bit) data is known as asynchronous frame; where: the frame length is 10-bit, the character length is 8-bit and the wastage of time is 20% (2/10*100).
asyncFrame.png
Figure-5.3: Asynchronous frame for character A

6. In UART communication, Bd (Buad) refers to number of bits being transmitted/received in one second (bits/sec). For example: Bd = 9600 means that the bit transfer rate is 9600 bits/sec which ie equal to 960 (9600/10) characters/bytes per sec. (In fact, Bd and bit/sec are not the same things; only in UART communication they stand to be the same things. The discussion is beyond the scope of present context.)

5.2 Data Exchange among InputBox, OutputBox and UNO
1. Fig-5.4 depicts the layout of the Serial Monitor of Arduino Platform, which comes in when a click is made on this smIcon.png icon located at the upper-right corner of the IDE.


Figure-5.4: Layout of Serial Monitor

2. Connect UNO with the PC and select the Board and COMX Port as needed. Launch the IDE and bring in the Serial Monitor. Select 'No len ending' in the 'Line ending tab'. Focus the cursor (bring the cursor) in the InputBox (Fig-5.4) of the Serial Monitor. Enter A from keyboard of PC and then click on the Send button. As a result, the frame of Fig-3 will be travelling towards UNO over the TXD line (Fig-5.5).
uartblkA.png
Figure-5.5: FIFO type Serial BUFFer of Arduino Platform

3. When the frame of Step-2 arrives to UNO, the UNO is automatically interrupted; it (the UNO) goes to a side job (called ISR = Interrupt Sub Routine) and receives the frame; the START and STOP bits are discarded and then the ASCII code (0x41) of A is automatically saved into Location-0 of the unseen FIFO (first-in first-out) type Serial Buffer (Fig-5.5).

4. To bring out the ASCII code of A from the BUFFer and save it into a user variable, the following steps are taken:
(1) Check if the BUFFer contains data items by executing these codes:

byte n = Serial.available();
if(n != 0)   //BUFFer contains at least one data item; here the ASCII code of A
{
    //bring out ASCII code of A from serial BUFFer of Fig-5 and save into user variable
}

(2) Bring out/raed the ASCII code of A from BUFFer and save into a user variable by executing this code:

char x = Serial.read();   //x holds 0x41 = ASCII code of A;

5. To show the character (whose ASCII code we have got in Step-4(2) into OutputBox of Serial Monitor, the following code is executed:

Serial.print(x);   //the data type of x must be char

The above code is converted to the following code in order to put the ASCII code (0x41) of A on the TXD line. As a result, A will appear on the Serial Monitor.

Serial.print(x);
==> Serial.write(0x41);  //A appears on the OutputBox of Serial Monitor

6. Exit the Serial Monitor and bring it again. Select Newline option in the Line ending tab of Serial Monitor of Fig-5.4. Enter A and then click on the Send button. Answer to the following questions:
(1) How many frames will be travelling towards UNO?
Ans: Two frames.
One frame for character A whose ASCII code is 0x41.
Second frame is for the Newline character whose ASCII code is 0x0A and the C- code is '\n'.

(2) Which location of the FIFI BUFFer of Fig-5.5 will hold the ASCII code of the Newline charcater?
Ans: Location-1.

(3) What will be the value of n after the execution of the following code?

byte n = Serial.available();

(4) Write codes to empty the BUFFer of Fig-5.5. (There will be no more data item in the BUFFer to read.)
Ans: ?

char x = Serial.read();  //X = 0x41 = the ASCII code of A charcater
char y = Serial.read(); //y = 0x0A= the ASCII code of Newline character

5.3 Questions and Answers
1. The following sketch is uploaded in the UNO. The word Arduino is entered in the InputBox of the Serial Monitor (No line ending option) and then the Send button is clicked. What charcaters (all the 7 charcaters of the word Arduino or a few of them) will appear on the OutputBox of the Serial Monitor?

void setup()
{
   Serial.begin(9600);  //hardware UART Port is active/enabled with a speed of 9600 bits/sec
}

void loop()
{
    byte n = Serial.available();
    if(n == 3)
    {
        char x = Serial.read();
        Serial.print(x);
        Serial.print(Serial.read());
        Serial.print(Serial.read()):
    }
}

2. What will appear on Serial Monitor when the following code is executed?

Serial.write(0x41);

Ans: The MCU will put 0x41 on the TXD line. Because, 0x41 matches with the ASCII code of A, the image A (character A) will appear on the OutputBox of Serial Monitor.

3. What will appear on Serial Monitor when the following code is executed?

Serial.print('A');

Ans: Let us note that it is the Serial.write() method that ultimately puts 'numerical data byte' on the TXD line. Therefore, the given code will be broken down to the following:

Serial.print('A');  //opening/closing single quotes are used to refer a single character.
==> Serial.write(0x41);    //character A will appear on Serial Monitor

... see next post.

smIcon.png

asyncFrame.png

uartblkA.png

unonano.png

ide.png

Ch5-UARTOnline.pdf (546 KB)

4. What will appear on Serial Monitor when the following code is executed?

Serial.print("AB");

Ans: Opening/closing double quotes are used to refer a series of char characters called string. The given code will be broken down to the following:

Serial.print("AB");
==> Serial.print('A');
==> Serial.write(0x41); //ASCII code of A; hence A will appear
//--and then
==> Serial.print('B');
==> Serial.write(0x42);   //ASCII code of B; hence B will appear

AB will appear on the OutputBox of Serial Monitor.

5. What will appear on Serial Monitor after the execution of the following code?

Serial.print(12);

Ans: Because the argument is not a string (no opening/closing double quotes around 12), the code will be immediately formatted to: (As a result, 12 will appear on Serial Monitor.)

Serial.print(12);
==> Serial.print(12, DEC);    //DECimal base of 10; 12 will appear n Serial Monitor
==> Serial.print('1');
==> Serial.write(0x31);   //0x31 is ASCII code of 1; 1 will appear on Serial Monitor
//---- and then----
==> Serial.print('2');
==> Serial.write(0x32);    // 2 will appear on Serial Monitor

6. What will appear on Serial Monitor after the execution of the following code?

Serial.print(123, HEX);

Ans: Because the 1st argument (123) is not a string (no opening/closing double quotes around the argument), the code will be immediately formatted to:

Serial.print(123, HEX);
==> Serial.print(0x7B, HEX);    //123 will be converted to value in HEX (16) base ;

7B will appear on Serial Monitor

7. What will appear on the Serial Monitor after the execution of the following codes:

char x = 0x43;     //ASCII code of C declared with data type char
Serial.print(x);

Ans: The compiler checks if the data type is char; if it is char, then the given code is formatted to as follows and the character (here C) corresponding to ASCII code 0x43
appears on the Serial Monitor.

Serial.print(x);
==> Serial.write(0x43);   //C appears on Serial Monitor

8. What will appear on the Serial Monitor after the execution of the following codes:

byte x = 0x43;     //ASCII code of C declared with data type byte
Serial.print(x);

Ans: The compiler checks if the data type is char or byte; if it is byte, then the given code is formatted to as follows and the characters (67) corresponding to decimal value of 0x43 appear on the Serial Monitor.

Serial.print(x);
==> Serial.print(0x43, DEC);   //DECimal = base 10
==> Serial.print(67, DEC);
==> Serial.print('6');
==> Serial.write(0x36); //6 appears on Serial Monitor
//---- and then---
7 appears on Serial Monitor

9. How many frames will travel from Serial Monitor to UNO when ABC is entered in the InputBox and Newline option is selected for the Line ending tab?

10. Write codes to send this floating point number (a decimal number with integer part and fractional part): 12.73.

float x = 12.73;
Serial.print(x, 2);   //2nd argument 2 says that 2-digits would be sent after the decimal point

The compiler checks the data type; it it is float, then the given Serial.print() method is broken down to the following codes: (As a result, 12.73 appears on the Serial Monitor.)

Serial.print(x, 2);
==> Serial.print('1');
==> Serial.write(0x031);   // 1 appears on Serial Monitor
//--- and then------------
==>Serial.print('2');
==> Serial.write(0x32);  //2 appears on Serial Monitor
//--- and then -------
==> Serial.print('.');
==> Serial.write(0x2E);  //. (decimal point) appears on Serial Monitor
//-----and then-----
7 will appear on Serial Monitor; the 3 will appear on Serial Monitor

11. The Line ending tab of the Serial Monitor of Fig-4 has the following options and the corresponding ASCII codes and C-codes are shown against their names:
(1) No line ending tab; no ASCII code; no C-code.
(2) Newline; ASCII Code = 0x0A; C-code = '\n'.
(3) Carriage return; ASCII code = 0x0D; C-code = '\r'.
(4) Bothe NL & CR (Both Newline and Carriage return); ASCII code = 1st CR, 0x0D and then NL, 0x0A).

12. What does happen when the following two lines of codes are executed? Write single line code for the given two lines.

char x = Serial.read();
Serial.print(x);

Ans: The ASCII code from BUFFer will be saved in x and then the character corresponding to this ASCII code will appear on the Serial Monitor.

13. Given byte x = 0x41; where, x holds the ASCII code of the character A. Write codes using Serial.print() and Serial.write() methods to see A on the OutputBox of Serial Monitor.

Ans:
(1) In the given code, the data type id byte; therefore, we must tell the compiler to 'forcibly impose char data type' (known as casting) on the variable x so that the execution of Serial.print() method will show the character A on the Serial Monitor. The code is:

Serial.print((char)x);     //A will appear on Serial Monitor
==> Serial.write(0x41);

(2) Using Serial.write() method--

Serial.write(x);    //A will appear on Serial Monitor
==> Serial.write(0x41);

14. How many characters are being transferred (from UNO to Serial Monitor) by the following code?

Serial.println('D'); //ln is for Newline

15. Wite code to show 0x7B on the Serial Monitor.
Ans:

Serial.print("0x7B");

16. Write all possible codes to show 7B on Serial Monitor.
Ans:
(1)

Serial.print("7B");

(2)

Serial.print(0x7B, HEX);

(3)

Serial.print(123, HEX);

17. In Fig-6, we observe that there are two separate modules inside the ATmega328P MCU of Arduino UNO Board, and these are: UART and PORTD. There are DPin-0 and 1 which can be connected either with UART Module or PORTD Module. Write down the name of the instruction which when executed, the DPin-0 and 1 get connected with UART Port; as a result, DPin-0 becomes TXD Line and DPin-1 becomes TXD Line.
TXDRXD.png
Figure-6: UART and PORTD structure of ATmega328P MCU

Ans:

Serial.begin(9600); //bit transfer rate = 9600 bits/sec

18. An array contains a series of data items/elements/members which are of the same 'data types'. Given below an array which contains characters; where, the compiler automatically inserts a null-character (0x00) at the end of the last item after compilation. write code to transfer the data items of this array to the OutputBox of the Serial Monitor using Serial.write() method.

char myData[] = "12AB";
==> char myData[] = {0x31, 0x32, 0x41, 0x42, 0x00};

Ans:

for(int i=0; i<sizeof(myData); i++)  //sizeof operator returns 4 = number of items in the array
{
    Serial.write(myData[i]);  //null-character (0x00) is not transmitted
}

Or

Serial.write(myData, sizeof(myData));

19. When we decalre 'byte x = 123;', the value of x is stored in a memory location in binary and it is 0x7B (0111 1011). When we declare 'float x = 12.73;', how many bits are stored in memory location (s)? Write codes to find the values of these bits.

Ans: According to IEE-754 Rule, 32-bit value are stored into four consecutive memory locations (so, it is an array of locations) when a variable is declared to hold a floating point number. The following codes (using pointer variable) could be executed to know the values of these bits (32-bit = 4 byes).

float x = 12.73;
byte *ptr; //pointer variable ptr to hold beginning address of memory array that holds 32-bit (4-byte)
ptr = (byte*) &x;            //pointer variable ptr holds the address of 4-byte wise memory array
byte m0 = *ptr;              //getting the LSByte of the 32-bit value
Serial.println(m0. HEX);  //shows: 0x14
//------------------------------------------------------------------
ptr++;                           //pointing to the next location of the memory array
byte m1 = *ptr;             //getting the next significant byte of 32-bit value
Serial.println(m1, HEX); //shows: 0xAE
//-------------------------------------------------------------------
ptr++;
byte m2 = *ptr;             //getting the next significant byte of 32-bit value
Serial.println(m2, HEX); //shows: 0x4B
//-------------------------------------------------------------------
ptr++;
byte m3 = *ptr;              //gettimg the MSByte of 32-bit value
Serial.println(m3, HEX);  //shows: 0x41
//-------------------------------------------------------------------![/code

... see next post

floatArray.png

TXDRXD.png

20. Reduce the number of code lines of Q19.
Ans:

float x = 12.73;
long *ptr;
ptr = (long*) &x;
long m = *ptr;
Serial.println(m, HEX);  //shows: 414BAE14

21 The following declaration (an array of float numbers) automatically creates the data table of Fig-7 in the RAM memory area of ATmega328P MCU.

float data[] = {1,1, 0.5};

![/code

... see next post


![floatArray.png|320x227](upload://wz2pPn219cBFxBHXKq4wFS5ihis.png)
Figure-5.7: Memory map of float number storage

**22.** Repeat Q20 using **union** structure.

union
{
  float x;
  byte myData[4]; //to hold 32-bit data; lower byte in lower location
}data;

data.x = 12.73;     //initialization; 32-bit data (4-bytes) have automatically entered in myData array.
byte lsByte = data.myData[0];   //lsByte holds 0x14
byte ns1Byte = data.myData[1];  //ns1Byte holds 0xAE
byte ns2Byte = data.myData[2];  //ns2Byte holds 0x4B
byte msByte = data.myData[3];   //msByte holds 0x41


**23.** Let us assume that we have built the following circuit (Fig-12). Write sketch so that the LED will become ON when the MCU receives this string "1-2-3" from the InputBox of the Serial Monitor. The LED will go OFF when we press down the button K1, and the LED will still remain OFF when we release the button. 
![sw1led1.png|510x376](upload://uSvXZlxRVc7lZb3MscEbPkQKCJ4.png)
Figure-8: Connection diagram of LED, Button and SM with UNO

**Solution Hints:**
**1.** This is (Fig-9) is the solution of the problem in the Form of Flow Chart.
![sw1led1FC.png|359x462](upload://4350Kd5uZh3cp8QOiFu7rzDr4jR.png)
Figure-9: Flow Chart solution of Q23

**2.** This the coding of the Flow Chart of Fig-9.

char myData[10] = "";

void setup()
{
 Serial.begin(9600);   //L1:
 pinMode(11, OUTPUT);  //L1:
 digitalWrite(11, LOW); //LED is OFF; L1
 pinMode(10, INPUT_PULLUP); //L1: K1 is at DPin-10
}

void loop()
{
 byte n = Serial.available();  //L2:
 if (n !=0 ) //L2:
 {
   byte m = Serial.readBytesUntil('\n', myData, 10); //L2:
   myData[m] = '\0';  //insert null-byte //L2:
   if(strcmp(myData, "1-2-3") == 0) //L2:
   {
     digitalWrite(10, HIGH);   //L3: ; LED is ON
     while(digitalRead(10) != LOW)  //L4:
     {
       ;    //wait   L4:
     }
     digitalWrite(13, LOW);  //L5: LED is OFF
   }
 } //goto L2:
}


**3.** carry out the following steps.
**(1)** Upload the sketch of Step-3.
**(2)** Bring in the Serial Monitor (Fig-10) with the selection of Newline option in the Line ending tab.
![SerialMonitorX.png|746x474](upload://ekt4vqUAiGFuKMULT7uTZHW7sHg.png)
Figure-10:

**(3)** Enter 1-2-3 in the InputBox of the Serial Monitor and then click on the Send button.
**(4)** Check that LED is ON.
**(5)** Press down the button K1.
**(6)** Check that LED is OFF.
**(7)** Release the button K1.
**(8)** Check that LED is still OFF.

**4.** Goto Step-3(2) and repeat the process.

**24.** Write sketch for UNO of Fig-1 so that UNO accepts only two characters (say 1 and 2) from the Serial Monitor and sends them to NANO using SUART Port. Also, write sketch for NANO so that it receives the characters as ASCII codes (0x31 for1 and 0x32 for 2) coming from UNO and show them on SM2. Add codes with the sketch of NANO so that it extracts 1 from 0x31 and 2 from 0x32 and then saves the value 12 (0x0C) in variable **byte x;**. Use Newline option as the terminating character at Serial Monitor of UNO. (Use **atoi()** function.)

**25.** Write sketch for UNO of Fig-1 so that UNO accepts a floating point number (say: 132.75) from the Serial Monitor and sends them to NANO using SUART Port. Also, write sketch for NANO so that it receives the characters as ASCII codes for the digits/point of the float number coming form UNO and show them on SM2. Add codes with the sketch of NANO so that it extracts 132.75 from the received ASCII codes and save the number in variable **float y;**. Use Newline option as the terminating character at Serial Monitor of UNO. (Use **atof()** function.)

**Solution Hints:** The following sketch receives float number from the InputBox of Serial Monitor as ASCII codes and then converts the ASCII codes into numerical float number and then sends the number to the OutputBox of Serial Monitor.

char myFloat[10] = "";   //all  locations of array will hold 0x00
int i = 0;   //index pointer for myFloat array

void setup()
{
 Serial.begin(9600);  //UART Port of Fig-1 is connected with PC
}

void loop()
{
 byte n = Serial.available();  //checking how many charcaters are in BUFFer
 if (n != 0 )  //checking if BUFFer really holds a charcater
 {
   char x = Serial.read();
   if (x != '\n') //this is not Newline character
   {
     myFloat[i] = x; //save ASCII code of charcater in array
     i++;            //advanve array index
   }
   else
   {
     float y = atof(myFloat); //ASCII formated float number becomes numerical float
     Serial.println(y, 2);       //Serial Monitor shows:132.75
     memset(myFloat, 0, 10);   //all locations of myFloat array is reset to 0s.
     i = 0;                    //index pointer is reset
   }
 }
}


**Working Principle of the sketch:** We select Newline option in the Line ending tab of Serial Monitor. We enter 123.75 in the InputBox and then click on the Send button. As a result, the following ASCII codes travel towards UNO: 0x31 for1, 0x33 for 3, 0x32 for2, 0x2E for point (.), 0x37 for 7, 0x35 for 5, and 0x0A for Newline charcaters. The UNO receives one character at a time and saves them in an array until Newline character ('\n' = 0x0A) is detected. the ASCII code of the Newline character is not saved in the array. After that the **atof()** (Convert ASCII codes into a float number) function converts the ASCII formatted float number into numerical float number and saves into variable **y.** 

**26.** Re-write the 'Solution Hints Sketch' of Q24 using this function: **byte m = Serial.readBytesUntil('\n', myFloat, 10);**. (The defulat time-out period is 1 sec; it means that the function will terminate its execution phase if the user waits for more than 1-sec between successive entry of the charcaters in the InputBox of the Serial Monitor. The function will also terminate if it receives terminating character ('\n' = Newline character) or it receives 10 charcaters before getting the terminating character. In any case, the terminating character is ot saved in the myFloat[] array.)

**27.** Write code to change the time-out period of UART communication into 2-sec. (Consult: Arduino Reference Manual in the web.)

**28.** Write codes for UNO so that it will accept characters (string) from the Serial Monitor if the string starts with this symbol < (less than). The incoming characters will be accepted and stored in an array until this > (greater than) is detected. This means that the UNO will accept ABCD from the Serial Monitor if we place <ABCD> in the InputBox and then click on the Send button.

**Solution Hints:** Write codes to accomplish the following tasks:
**(1)** Check that a character has come from the Serial Monitor.
**(2)** Check that the character of Step-1 is this (<) character. 
**(3)** Read the next character. 
**(4)** Check that the character of Step-3 is not this (>) character. 
**(5)** If Step-4 is true, save the character in an array.
**(6)** If Step-4 is false (> is detected), then stop accepting character.
**(7)** Show the received string (ABCD) of the OutputBox of the Serial Monitor. 

**29.** Programming Project
Write sketch so that whenever you send 45 from Android Phone, the shaft of the Servo Motor of Fig-11 rotates by 45<sup>0</sup> an so on. **Hints:** Do some googling. 
![Hc5-BTServo.png|532x359](upload://a0y2m1ac77sLGz0NxsbMwqpZm9W.png)
Figure-11: Connection (physical and wireless) among UNO, Bluetooth, Servo Motor, and Android Phone.

![Hc5-BTServo.png|532x359](upload://a0y2m1ac77sLGz0NxsbMwqpZm9W.png)

![sw1led1.png|510x376](upload://uSvXZlxRVc7lZb3MscEbPkQKCJ4.png)

![sw1led1FC.png|359x462](upload://4350Kd5uZh3cp8QOiFu7rzDr4jR.png)

30. With the help of a diagram, discuss the following items:
(a) Serial Port
(b) Serial Buffer
(c) Serial.avialbale();
(d) Serial.read();
(e) Serial.readBytes();
(f) Serial.setTimeout();

Ans:
(1) In Arduino Platform, "Serial Port" and "Serial Buffer" are different things. Therefore, "read from Serial Port" and "read from Serial Buffer" should also be different.

(2) The following diagram (Fig-12) depicts the presence of "Serial Port" and "Serial Buffer" in the Arduino UNO at conceptual level.


Figure-12:

(3) When a character (data byte/asynchronous frame) arrives to the UNO, the MCU of the UNO Board gets interrupted in the background; it (the MCU) goes to the ISR routine, reads the character from the "Serial Port" and saves it in location-0 of the FIFO-type (first-in first-out) "Serial Buffer".

(4) The user checks that there is at least one data byte in the "Serial Buffer" by executing the following code in his sketch:

Serial.available();
if(n != 0)
{
      //Serial Buffer contains at least one character/data byte
}

(5) If n is non-zero in Step-4, the user includes the following code in his sketch to bring out the character/data byte from the "Serial Buffer' and keep it in a variable:

char x = Serial.read();

(6) What is about the following command --

byte m = Serial.readBytes(myBuffer, bytesToRead);
==> byte m = Serial.readBytes(myBuffer, 2);

(a) We have seen in Step-3 that the data bytes (charcaters) coming to the Serial Port were being received and saved in Serial Buffer by interrupt process. In Fig-1, we observe that 3 data bytes have been accumulated in the Serial Buffer.

(b) Serial.readBytes() command keeps reading data bytes/charcaters from the "Serial Buffer" until the reading of two data bytes/charcaters are done. That means that the method readBytes() will terminate when the requested number of data bytes (here it is 2) are read from the Serial Buffer. The myBuffer will hold only A and B although there are 3 three charcaters (A, B, C) in the Serial Buffer. The variable m is equal to 2 which is number of data bytes read from Serial Buffer and stored in myBuffer array.

(c) Serial.readBytes() command will also terminate after reading only 1 character (though 2 bytes are desired) if the delay between successive arrivals/storage (into Serial Port/Serial Buffer) of charcaters is greater than the "timeout period (default 1-sec)". The "timeout period" could be changed by executing the following code.

Serial.setTimeout(milliSeconds);

31. Describe the working principle of the following UART related method:

byte m = Serial.readBytesUntil('\n', myBuffer, 20);

32. Explain the working principle of Serial.parseInt() method.
Ans:
1. The characters/data byte that have arrived at the Serial Port (the hardware UART Port) are being collected and saved into "Serial FIFO Buffer" on interrupt basis at the end of sketch uploading.

2. When uploading is done, the Serial.parseIn() also begins to work.

3. The above two processes are asynchronous; there is no way to tell which one has started first.

4. As the parseIn() method looks for charcaters/data bytes into the Serial Buffer, the user must be sure that the Serial Buffer has accumulated data bytes in order to ensure that parseInt() method works correctly. This is done by executing the following code:

while(Serial.available() == 0)
{
    //wait until Serial Buffer has accumulated at least one character
}

//----------------------------------------------------------------------------------------------------------------
5. The parseInt() method will terminate with zero return value if it does not find a character in the Serial Buffer within the "timeout period" since it has started.

6. The parseInt() method will terminate with a non zero return value if it does not find a character in the Serial Buffer within next "timeout period" since it has finished reading one or more valid charcaters (0 to 9).

7. The parseIn() method will also terminate if it finds a non-digit character (outside 0 to 9). The return value will be 0 if the very first character so read is a non-digit character. The return value will be non-zero if a non-digit character is encountered after reading one or more valid charcaters (0 to 9).
//----------------------------------------------------------------------------------------------------------------

Example:

... to be continued.

GolamMostafa:
… this is reserved.

  1. There is only one hardware/electronic UART Port (UART) inside the MCU. It is permanently engaged with the PC and with the Serial Monitor

This is nonsense.
You’re describing a microcontroller.

I see airborne hay:

avialbale.png

The famous ( 8 ) versus smiley:

smiley.png

The same thing as in the other tutorial. A paragraph with an other language. Is this a UTF-8 copy/paste that has gone wrong ?

I am never sure with those functions such as Serial.readBytes() if the returned text has a zero-terminator after a timeout or when the buffer is completely filled.
Are you sure you solved every situation by adding that zero-terminator ?

smiley.png

avialbale.png

Those monsters disappaer with the following command whcih I learnt long ago from @AWOL.

[ nobbc ][ /nobbc ]

I will revise the texts.

Thanks.