简体   繁体   中英

Communicate between 2 Raspberry Pi with UART

I want to send data from one pi to another with UART communication. The first Raspberry model is Raspberry Pi 4, and the second one Raspberry Pi 3. To do this communication Im connecting both Raspberry pins in this way:

Pi 4 -> Pi 3

Tx -> Rx

Rx -> Tx

Ground -> Ground

I have already activated both Pis serial connection on the raspberry configuration following the steps of this link: https://iot4beginners.com/raspberry-pi-configuration-settings/ . In order to write and send the data I have created the next python program:

import time
import serial

ser = serial.Serial(
        port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
        baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.SEVENBITS)
counter=0
while True: 
    ser.write(str.encode(str(counter))) 
    time.sleep(1) 
    counter += 1

To read and print the data received I have created the next program:

import time
import serial

ser = serial.Serial(
        port='/dev/ttySO', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
        baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.SEVENBITS
)
counter=0

while 1:
    x = ser.readline()
    print(x)

Finally when I run the reading program I get the next error:

Traceback (most recent call last):
  File "serial_read.py", line 14, in <module>
    x = ser.readline()
  File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 501, in read
    'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

I'm new to Raspberry communication and I will be thankful for any suggestion.

Python 2.7 is officially dead, so I would recommend using Python3 - especially for new projects such as yours.

So, rather than run your script with:

python3 YourScript.py

you could put a proper shebang at the start so it automatically uses the correct Python version you intended:

#!/usr/bin/env python3

import ...

Then make the script executable with:

chmod +x YourScript.py

Now you can run it with:

./YourScript.py

and be happy it will use Python3, and also even if someone else uses it.


The actual issue, I think, is that the readline() on the receiving end is looking for a newline that you didn't send. So I would try adding one:

ser.write(str.encode(str(counter) + '\n')) 

Personally, I find f-strings to be much easier than the older % and .format() stuff, so maybe try:

ser.write(str.encode(f'{counter}\n'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM