Hello Forum Members,
I’m working on a serial communication project where I’m facing a few challenges. In the project, I’m trying to establish communication using the RS485 protocol between a Raspberry Pi 4 and a Raspberry Pi Pico.
Here are the basic code structures I’m using:
Raspberry Pi 4:
python code
import serial
ser = serial.Serial('/dev/serial0', baudrate=9600, timeout=1) # Serial port settings
def read_data_from_slave():
data = ser.read(1) # The first byte contains the slave address
slave_address = int.from_bytes(data, byteorder='big') # Get the slave address
data = ser.read(ser.in_waiting) # Get the remaining data
return slave_address, data
try:
slave_address, data = read_data_from_slave() # Receive data from the slave device
print(f"Slave Address: {slave_address}")
print(f"Received Data: {data.decode()}")
except KeyboardInterrupt:
ser.close() # Close the serial port when the program is terminated
Raspberry Pi Pico:
python code
import uos
import uos, machine
import ustruct as struct
from machine import Pin
import time
uart_tx = machine.Pin(4) # TX pin: GPIO 0
uart_rx = machine.Pin(5) # RX pin: GPIO 1
# Create a UART object
UART = machine.UART(1, baudrate=9600, tx=uart_tx, rx=uart_rx)
def send_data(data):
UART.write(data)
slave_address = 7 # Set the slave address as 2
def send_data_to_master():
send_data(struct.pack('b', slave_address)) # Send the slave address
data="m"
send_data(data) # Send the data
while True:
time.sleep(1)
send_data_to_master()
Currently, I’m facing an issue in the project: I’m unable to receive data from the Raspberry Pi 4 device. The serial communication codes seem to be working correctly, but the data receiving function is not yielding the expected results. Does anyone have any insights on this?
Thank you!