Raspberry Pi sends and receives data through serial port (serial version)

    This time, I want to send data to the computer through the serial port of Raspberry Pi 3B, but the Raspberry Pi only has one serial port ttyAMA0 that can be used, and the other is a mini serial port, which cannot be used normally.

    Then we will use my previous article . Since the serial port is to be used, we cannot use the serial port connection to log in to the Raspberry Pi. We can use a network cable to log in or ssh to log in.


1. Modify the file

Type sudo vim /boot/cmdline.txt

Delete the console=serial1,115200 and kgdboc=serial1,115200 in it, so that you can use the serial port normally, otherwise Permission denied will appear later

which eventually becomes:

dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2  rootfstype=ext4 elevator=deadline fsck.repair=yes  rootwait

2. Install the python-serial module

Type sudo apt-get install python-serial  

When I installed it, I found that it was there, laughing and crying

Why didn't I start the installation from python. . .

The Raspberry Pi is still relatively complete, both python2 and 3 are available, and many modules are also carried with you. I like it here.


3. Start python IDE

enter python3

Create a serial instance ser, the port is '/dev/ttyAMA0', the baud rate is set to 115200bps, and the third is the check digit, which can be omitted.

>>> import serial
>>> ser = serial.Serial('/dev/ttyAMA0',115200)

Check whether the serial port is open, if not, enter ser.open() to open it

>>> ser.isOpen()  
True


4. Open the serial port debugging assistant

I use the friendly serial debugging assistant under Baidu. After the port is set up, we click the start button above, and the green word "opened" will appear below.



Then we send a message in the python of the Raspberry Pi to check whether the sending is normal:

>>> ser.write(b'Raspberry pi')
12

Received successfully!



Finally, we write a python script code to realize the sending and receiving of the serial port:

# -*- coding: utf-8 -*
import serial
import time
ser = serial.Serial('/dev/ttyAMA0', 115200)
if ser.isOpen == False:
    ser.open() # Open the serial port
ser.write("Raspberry pi is ready")
try:
    while True:
        size = ser.inWaiting() # get buffer characters
        if size != 0:
            response = ser.read(size) # read content and display
            print response        
            ser.flushInput() # Clear the receive buffer
            time.sleep(0.1) # software delay
except KeyboardInterrupt:
    ser.close()


Running the python program on the raspberry pi side, we try to send a string of messages to the past



Raspberry Pi successfully received, you're done!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325617017&siteId=291194637