Serial communication

From the relevant information of Raspberry Pi, we can see that the physical pins 8 and 10 of Raspberry Pi can be mapped to two serial ports, one of which is the hardware serial port (/dev/ttyAMA0) and the other is the mini serial port (/dev/ttyS0). The hardware serial port has a separate baud rate clock source, which has good performance and strong stability; The mini serial port has simple functions and poor stability. The baud rate is provided by the CPU kernel clock and is affected by the kernel clock.

Raspberry Pi (3rd/4th generation) onboard Bluetooth module, the default hardware serial port is assigned to the Bluetooth module, while the poor performance mini serial port is assigned to the GPIO serial ports TXD0 and RXD0.

image.png

Run the following command to view the default serial port allocation method:

image.png

 

Due to the hardware serial port being assigned to onboard Bluetooth, we need to release it and set the hardware serial port to be assigned to GPIO serial port.

1.After SSH logs into the Raspberry Pi system

Enter the Raspberry Pi system configuration interface and select Interfacing Options:

image.png

Choose P6 Serial

image.png

Select to turn off the serial port login function and turn on the hardware serial port debugging function.

image.png

image.png

After completion, prompt the following interface and press OK

image.png

Exit raspi config settings and follow the prompts to restart Raspberry Pi.

 

2.Set the hardware serial port to GPIO serial port

Edit the config.txt file in the/boot directory

Add the following two lines to the end:

The modified image is shown below.

image.png

Save: Ctrl+O,Exit: Ctrl+X。

Reboot Raspberry Pi.

After restarting the Raspberry Pi, enter ls/dev - al again, and you can see that the two serial ports have switched positions with each other:

image.png

 

  1. Minicom serial port assistant testing

    Installing Minicom

Start Minicom after installation is complete

Among them, - D represents selecting serial port/dev/ttyAMA0, and - b sets the baud rate to 9600. This parameter can be set without any need, with a default of 115200.

image.png

Open the serial port to transfer data through the USB to TTL module.

The operation of exiting Minicom is quite complicated. According to the prompt, you need to first press Ctrl+A, then press Z to pop up the following menu.

image.png

Next, press X, and finally select YES and press Enter to confirm.

4.C language test code

Print hello world

The code is as follows:

image.png

Create a new testCom. c file and copy the above code into it

Save: Ctrl+O, exit Ctrl+X

Use the gcc compiler to compile programs:

Run a program

image.png

You can also send data to Raspberry Pi through the serial port, and Raspberry Pi will directly return it to the serial port for display.

Note: If there is a display of garbled code, please check the baud rate and set it to 9600, which corresponds to the above code.