Raspberry pie 4B connects the computer through CH340 to realize USART serial communication (C language and Python version)

preface

The peripheral of raspberry Pie 3/4b contains two serial ports, one is called hardware serial port (/ dev/ttyAMA0) and the other is called mini serial port (/ dev/ttyS0). The hardware serial port is realized by hardware. There is a separate baud rate clock source with high performance and reliability. The mini serial port has low performance and simple function. There is no special clock source for baud rate, but is provided by the CPU core clock. In the 4th generation of raspberry pie, due to the on-board Bluetooth module, the hardware serial port is assigned to communicate with the Bluetooth module by default, and the mini serial port is assigned to the GPIO Tx Rx led by the row pin by default.

Tip: the following is the main content of this article. The following cases can be used for reference

1, Start serial port

On the command line, enter the following:

ls -l /dev

If it is not configured, you should see:

serial1 -> ttyAMA0

At this time, enter:

sudo nano /boot/config.txt

Add at the end of the open file:

#ENABLE UART
enable_uart=1

After saving and exiting, restart raspberry pie;

reboot

Enter at the terminal:

sudo raspi-config

Set up according to the following steps:
Select interface options - > serial - > no - > Yes to close the serial port debugging function and open the serial port
Select Interfacing Options

Select serial

Then select no to disable the serial port login function and use the serial port for communication.
Then select yes to start the serial port hardware.

On the command line, enter the following:

ls -l /dev

After enabling the serial port in the settings, you will find that the / dev directory becomes two:

serial0 -> ttyS0 and serial1 ->ttyAMA0

2, Disable Bluetooth (exchange the default mapping between hardware serial port and mini serial port)

Enter at the terminal:

sudo nano /boot/config.txt

Add at the end of the open file:
(Note: Raspberry pie 4b is also pi3, but I don't know the specific reason)

dtoverlay=pi3-disable-bt 

Restart raspberry pie after modification and saving:

reboot

3, Find out if there is a package with serial

Enter at the terminal:

pip list

Find out whether there is a serial package. If not, enter in the terminal:

pip install serial

4, CH340 connects raspberry pie and computer respectively

  1. The USB port of CH340 is connected to the USB port of the computer
  2. The 5P pin of CH340 is respectively connected with the serial port pin of raspberry pie
  3. VCC <-> VCC,RXD <-> TXD,TXD <-> RXD,GND <-> GND

5, python serial communication program

# -*- coding: utf-8 -*
import serial
import time
# Open the serial port, configure the baud rate to 9600, and the baud rate of data received by the computer should also be the same
ser = serial.Serial("/dev/ttyAMA0", 9600)
def main():
    while True:
        # Get receive buffer characters
        count = ser.inWaiting()
        if count != 0:
            # Raspberry pie reads the data sent by the computer and sends the data back to the computer
            recv = ser.read(count)
            ser.write(recv)
        # Clear receive buffer
        ser.flushInput()
        # Necessary software delay
        time.sleep(0.1)
    
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if ser != None:
            ser.close()

6, C language communication program

//Use ch340 to realize the communication between raspberry pie and computer, and the file name is "uartex.c"
#include<stdio.h>
#include<stdlib.h>
#include<wiringSerial.h>
 int main(void)
{
    int fd,n;
    char a;
    if((fd = serialOpen("/dev/ttyAMA0",115200))<0)//If communication fails, check and change the baud rate of the serial port
    {
        printf("serial ERROR!!!\n");
    }
    printf("This is just for test================== BY WAN\n");

    serialPuts(fd,"START NOW====>");
    while(1)
    {
        printf("Please input:\n");
        //Enter the data you want to send with the keyboard and send it
        scanf("%c",&a);
        if(a>0)
        {
            serialPutchar(fd,a);
        }
        //Check whether there is data sent from the opposite end. If so, print it out
        while(n=serialDataAvail(fd)>0)//Check whether there is data at the counter
        {
            printf("====The returned data is===>%c\n",serialGetchar(fd));//If there is return data, print out
        }
    }
    return 0;
}

summary

Connect the raspberry pie with the computer through CH340, run Python or C language program in the raspberry pie, and open the serial port assistant on the computer side to verify whether the communication is successful.

Tags: Python C Raspberry Pi

Posted on Sat, 09 Oct 2021 23:13:15 -0400 by syacoub