Labs / Bipes + MicroPython / 5 Fundamentals of Communication Peripherals

5.1 Serial Communication (UART): One-to-One Chat

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

As we already know, communication refers to enabling devices to "talk" to each other. In this section, we will first get to know one of the most intuitive and easiest-to-understand communication methods —— UART (Universal Asynchronous Receiver/Transmitter) serial communication, which acts like a "private whisper telephone line" between devices.

1. Pull a "whisper telephone line"

Before we start the operation, let's first talk about a very familiar scenario in daily life.

1.1 Questions about daily life scenarios

Consider this question: when you and your deskmate pass secret notes in class, why can only the two of you understand what's written on them?

The reason is actually very simple:

This is a form of one-to-one information transmission. In fact, the communication between many electronic devices is very similar to passing notes.

1.2 Understanding UART in a Nutshell

UART (Universal Asynchronous Receiver/Transmitter, serial communication) can be understood in this way: it is just like a dedicated telephone line between you and your deskmate, which only supports one-to-one communication, being simple and private.

It has several very important characteristics:

In many beginner projects, serial communication is the first communication method to be used.

Young Maker's Observation: Now take a look at the devices around you and think about which ones are more suitable for this "one-on-one chat" approach?

Examples: computers and development boards, two Arduinos, sensors and main control boards, etc.

2. Understand the "Communication Rules" of UART

2.1 Baud Rate

The baud rate is just like the "speaking rate" of speech:

In programming, when setting the baud rate, we must ensure that the sender and the receiver use the same baud rate, otherwise communication errors will occur.

Interactive Mini Exercise: If two people speak at different rates (baud rate mismatch), what will happen?

Answer: The content received by the other party may be garbled or partially missing, just like mishearing a whisper from your deskmate.

2.2 TX/RX Pins

TX acts as your "mouth", responsible for transmitting information;RX acts as your "ears", responsible for receiving information.

Pro Tip: Always connect the TX pin to the other device's RX pin, and the RX pin to the other device's TX pin — otherwise it's like talking to a wall, and no one will receive your data correctly.

2.3 Data Format

Data in UART communication is transmitted in bytes, and each byte typically consists of:

Young creators’ understanding: Just like when writing a note, you write "Start" at the beginning, "End" at the end, and the content in between, to make sure the recipient can understand it.

3. Comprehensive Analysis of UART Blocks

5.1 Serial Communication (UART): One-to-One Chat

3.1 Initialization Block (Init UART Serial Port): Set the "speech rate" and the position of the "mouth/ear" for the telephone line

Young makers, if you want your development board to "chat" with your computer and sensors, the first step is to set rules for this "phone line" — the UART serial port — and that's exactly what the initialization block does! It's just like when you and your classmates use walkie-talkies: you have to tune to the same "channel" and set the same "speaking rate" first, otherwise you'll each be talking your own way and won't understand a word the other says~

5.1 Serial Communication (UART): One-to-One Chat

Chinese Meaning: Initialize the UART serial port (Init UART Serial Port), set the pins and baud rate (communication speed) used for communication, so as to get ready for subsequent data transmission and reception.

Core Features:

Example in daily life:

  1. Adjust your headset before making a call: Only when you put on the headset properly can your voice be heard by the other party;
  2. Adjust your speaking pace: if you speak too fast or too slow, others may not be able to hear you clearly;
  3. Match the connections correctly: If the phone line is plugged into the wrong port, no one will hear you no matter how clear your voice is.

Practical Example 1: Initialize the Computer's Serial Port

Practical Example 2: Initializing Another Development Board

Quick Reminder

  1. The initialization block can only be used once at the very beginning of a program, and repeated use may cause confusion;
  2. Make sure the TX and RX pins are connected correctly; otherwise, data transmission/reception will fail.
  3. The baud rates must match; otherwise, the data will be garbled.

✨ Exclusive Mini Interaction

  1. Quick Response Quiz 1: What is the core function of the initialization block? (Answer: Configure the pins and baud rate for serial communication to prepare for data transmission/reception)
  2. Think about it: What will happen if you send data directly without placing the initialization block first? (Answer: Most likely, the data will fail to be sent, or the receiver will not understand it.)
  3. Scenario judgment: If the baud rates of the two boards are different, what will happen to the data sent by the sending block? (Answer: The received data will be garbled or lost)

Summary:

  1. Initialization block: Specify the pins and baud rate for UART communication, which is the first step of serial communication;
  2. Must be used at the very beginning of the program to ensure that subsequent data sending blocks can take effect;
  3. This is just like adjusting the headset and speaking pace before making a phone call — without initialization, normal communication cannot be achieved.

3.2 Data Sending Block (Send data to UART): Sends out the content (text/numbers) you want to transmit

Young creators, once you have initialized the "telephone line", you can start speaking! The data sending block is used to make the development board transmit the content you want to send via UART. You can send text, numbers, or send the data read by the sensor to a computer or another development board through this "telephone line".

5.1 Serial Communication (UART): One-to-One Chat

Chinese meaning: Send the specified data (text or numbers) to an external device or another development board via the UART serial port.

Core Features:

Practical Examples:

  1. Making a phone call to pass a message: You need to get the call connected first before you can convey what you want to say to the other party;
  2. Write a letter and send it out: You have finished writing the letter (the data), but if you do not put it into an envelope (the sending block), others will not receive it;
  3. Microphone Relay: Only when you input your message into the microphone (the send block) can your voice be transmitted to others.

Practical Example 1: Send a sentence to the computer's serial port

Practical Example 2: Sending Sensor Data

Quick Reminder

  1. Initialize first, then send; the order must not be reversed.
  2. Make sure the TX and RX pins are connected correctly; otherwise, the receiver will not be able to receive data properly.
  3. The baud rate must match so that the transmitted data can be correctly interpreted by the receiving party;
  4. Do not send data too fast, otherwise the recipient may fail to process it in time and lose data.

✨ Exclusive Mini Interaction

  1. Quick Response 1: What is the function of the "Send Data" block? (Answer: Send text or numbers via UART)
  2. Think about it: What will happen if the "send block" is used before initialization? (Answer: There is a high probability that the sending will fail and the recipient will not receive it.)
  3. Scenario Judgment: When sending temperature data, if the baud rate does not match that of the receiving end, what will happen? (Answer: The received data will be garbled or lost.)
  4. Small challenge: Try changing the data sent from text to the value of the temperature sensor, and observe the changes in the serial port window.

Summary

  1. Data sending block: responsible for sending text or numbers via UART, which is the core step of "speaking";
  2. It must be used after initializing the building block, and ensure that TX/RX and baud rate match;
  3. Just as you can only speak after a call is connected, the sending block cannot function without prior initialization.

3.3 Data Reading Block (Read data to UART): Listen for messages sent by the peer (received byte by byte)

Young makers, if a development board wants to communicate with external devices, it must not only be able to "speak" but also know how to "listen"! The data reading block is the "ear" of the development board, responsible for receiving data sent via UART, reading one byte (the smallest unit of information) at a time, and then passing it to the program for processing.

5.1 Serial Communication (UART): One-to-One Chat

Chinese meaning: Read the received data (received byte by byte) via the UART serial port for the program to perform judgment, display or further processing.

Core Features:

Practical Examples:

  1. Telephone Listening Comprehension: The other party speaks one sentence at a time, and you listen accordingly, making sure to understand every single word of each sentence;
  2. Receiving and opening a letter: A letter is sent line by line and word by word, and you have to unpack each line to grasp its content;
  3. Microphone Message Delivery: The sounds picked up by the ear are transmitted to the brain one by one, so that the full meaning can be comprehended.

Practical Example 1: Reading Data from Computer Serial Port

Practical Example 2: Reading Data Sent by a Sensor or Another Board

Quick Reminder

  1. Initialize the UART first, then read the data — the sequence is critical;
  2. Read by byte: If the data to be sent is very long, the program needs to read and combine it in a loop;
  3. The TX/RX pins and baud rate must match, otherwise the received data may be garbled or lost;
  4. Reading the building blocks will not block the program for too long, but attention should be paid to the frequency of cyclic reading to avoid missing data.

✨ Exclusive Mini Interaction

  1. Quick Response Quiz 1: What is the function of the data reading block? (Answer: Receive the data sent via UART for program processing)
  2. Think about it: If the sender sends the number 65, which corresponds to the character 'A', how would you display it in a program? (Answer: Read one byte, then display it using the display block.)
  3. Scenario Judgment: When transmitting multi-byte information consecutively with one byte read each time, how to combine them into a complete message? (Answer: Use loop reading to concatenate the bytes one by one into a string or a number)
  4. Small Challenge: Try to read the text sent by the computer, then determine whether it contains a specific character, and if so, turn on the LED.

Summary

  1. Data reading block: the "ear" of the development board, which receives data sent from external devices in bytes;
  2. It must be used after UART initialization, and ensure that the TX/RX pins and baud rate match;
  3. When the data reading block and the sending block are used in combination, a complete serial port chat can be realized, and the development board can both "speak" and "listen".

3.4 Single-line Reading Block (Read one line from UART): Receives messages in units of "a single sentence"

Young makers, after the development board gets its "ears", it can not only receive information byte by byte, but also understand what others are saying in terms of "a complete sentence"! The single-line reading block acts as the "sentence receiver" of the development board: it reads an entire line of message at a time, and passes the whole line to the program only when it encounters a line break (Enter).

5.1 Serial Communication (UART): One-to-One Chat

Chinese meaning: Read the received data line by line through the UART serial port (terminate when a line break is encountered), which facilitates the program to obtain the complete information at one time for processing.

Core Features:

Example in daily life:

  1. On the phone, wait until a full sentence finishes before processing it: wait until you hear the complete sentence before responding;
  2. Open the letter and read it paragraph by paragraph: you can only grasp the full meaning after finishing each complete paragraph.
  3. The teacher instructs: First listen to the complete sentence, then take notes or answer the questions.

Practical Example 1: Read a line of text sent by a computer

Practical Example 2: Reading Sensor Information or Commands

Quick Reminder

  1. Initialize the UART before using it — the order is critical;
  2. Each line must end with a newline character; otherwise, the block will keep waiting and the program will pause;
  3. The TX/RX pins and baud rate must match, otherwise reception may fail or garbled data may occur;
  4. Suitable for sending relatively complete commands or text, not suitable for high-speed continuous byte data.

✨ Exclusive Mini Interaction

  1. Quick Response Quiz 1: What is the difference between the single-line reading block and the byte-by-byte reading block? (Answer: The single-line reading block retrieves an entire line at a time, while the byte-by-byte reading block retrieves one byte at a time.)
  2. Think about it: If the sender doesn't have a newline character, what will happen to the single-line reading block? (Answer: It will keep waiting and the program will pause.)
  3. Scenario Judgment: The computer sends three commands, each ending with a newline character. How can the development board read one command at a time? (Answer: Call the single-line reading block in a loop to receive one complete command each time)
  4. Small challenge: Try sending a line of "LED ON" to make the onboard LED light up once it's received.

Summary:

  1. Single-line reading block: the "one-line receiver" of the development board, which obtains an entire line of data at a time to facilitate processing commands or text information;
  2. It must be used after UART initialization, and ensure that the TX/RX pins and baud rate match;
  3. It ends when a line break is encountered, reading an entire line at a time to avoid the hassle of byte-by-byte concatenation and simplify serial port data processing.

3.5 Full Read Block (Read all data from UART): Receives all unread messages at one time

Young makers, the "ears" of the development board can not only listen byte by byte and line by line, but also "listen to all the words in one breath"! The full-read block is the "full listener" of the development board, which receives all unread data in the serial port at one time, making it convenient for the program to process a large amount of information in a single run.

5.1 Serial Communication (UART): One-to-One Chat

Chinese Meaning: Read all unread data in the current buffer at one time via the UART serial port, including text, numbers or commands, for unified processing by the program.

Core Features:

Example in daily life:

  1. Turn on the radio and listen to an entire broadcast segment : to obtain the complete content in one go without pausing to listen word by word;
  2. Open your inbox and take out all the messages at once: process multiple pieces of information in one go without missing any;
  3. Clear all files on your desktop in one go : Get all your materials at once for easy centralized organization.

Practical Example 1: Read all data sent by the computer at one time

Practical Example 2: Receiving Continuous Sensor Data

Quick Reminder

  1. Initialize the UART before using it — the sequence is critical;
  2. Read all unread messages at one time, and the buffer will be cleared after reading;
  3. The TX/RX pins and baud rate must match, otherwise the received data may be garbled or lost;
  4. Not suitable for fine-grained control requiring byte-by-byte processing, as message boundaries may otherwise be indistinguishable.

✨ Exclusive Mini Interaction

  1. Quick Response 1: What is the core function of the "read all" block? (Answer: Obtain all unread data in the serial port buffer at one time)
  2. Think about it: If three commands are sent consecutively, how will the full-read block receive them? (Answer: All three commands will be obtained into the program at one time.)
  3. Scenario Judgment: When a large amount of data is sent continuously, what problems may occur if the full-reading block is used? (Answer: Too much data at one time, leading to slow processing or a laggy program)
  4. Small challenge: Try to use the full-read block to read the multi-line temperature data sent by the computer, and then calculate the average value.

Summary

  1. Full Read Block: The "full listener" of the development board, which receives all unread data in the serial port at one time;
  2. It must be used after UART initialization, and ensure that the TX/RX pins and baud rate match;
  3. It is suitable for processing large batches of continuously sent information, and can obtain the data at one time to avoid repeated reading byte by byte or line by line.

3.6 New Data Detection Block (Check to see if the uart has data): Check whether there are any new messages in the "telephone line"

Young makers, if you want your development board to listen to the messages coming through the "phone line", it first needs to know if someone is calling. The new data detection block acts as the development board's "ear detector", helping you check whether there is any new unread data in the UART serial port, so you won't waste your effort.

5.1 Serial Communication (UART): One-to-One Chat

Chinese meaning: Check whether there is new data in the buffer of the UART serial port; if yes, return true; if no, return false for the program to decide whether to perform a read operation.

Core Features:

Example in daily life:

  1. Has the phone rung yet: First wait for the phone to ring, then go answer it;
  2. Is there any new mail in the inbox?: First check if there are any letters in the mailbox, then decide whether to go and collect them;
  3. New message notification for chat apps: A little red dot lights up on the screen to indicate a new message, and you tap into it to check.

Practical Example 1: Cyclically check for new messages

Practical Example 2: Smart LED Reminder

Quick Reminder

  1. Initialize the UART before using it — the sequence is critical;
  2. Detection only, no reading, the data remains in the buffer and needs to be retrieved using the reading block;
  3. Suitable for use in loops to determine in real time whether there is new data;
  4. The return value is a Boolean: which can be used directly in condition control blocks, such as the "if. .. then. .." block.

✨ Exclusive Mini Interaction

  1. Quick Response 1: What is the core function of the new data detection block? (Answer: Check whether there is a new message on the serial port and return true or false)
  2. Think about it: What will happen if data is detected but not read? (Answer: The data will remain in the buffer and still be available for the next read operation.)
  3. Scenario Judgment: When the block for new UART data returns false while frequently checking the UART in a loop, what should the program do? (Answer: Continue the loop to check and wait for new data)
  4. Small challenge: Use new data to test the block-controlled LED prompt, which only lights up when there is a new message and turns off automatically after the message is read.

Summary:

  1. New Data Detection Block: The "ear detector" of the development board, which first checks for new messages before deciding whether to read them;
  2. It must be used after UART initialization, and ensure that the TX/RX pins and baud rate match;
  3. Returns a Boolean value true / false, which is suitable for judging message status in loops to improve program efficiency.