0

I enabled the UART interface inside the /boot/config.txt file. I know I have correctly selected the serial port because ser.write(data_to_send.encode()) gets executed successfully. The line where my code gets stuck is received_data = ser.read(2).decode().

I have connected GPIO14(UART TX) with GPIO15(UART RX) using a physical wire. To receive the same data being sent. Please let me know what I am doing wrong.

I am also attaching my code as a reference. Thanks

import serial

serial_port = '/dev/ttyS0' baud_rate = 9600

 def send_data(serial_port, baud_rate, data_to_send):

    # Open the serial connection
    
    ser = serial.Serial(serial_port, baud_rate)

    try:
        # Send data serially
        ser.write(data_to_send.encode())  # Convert string to bytes before sending
        print("Sent: {}".format(data_to_send))

        # You may want to add a delay to allow time for data to be transmitted
        time.sleep(1)

    finally:
        # Close the serial connection
        ser.close()

def receive_data(serial_port, baud_rate):
    # Open the serial connection

    ser = serial.Serial(serial_port, baud_rate)

    try:
        # Read data serially
        received_data = ser.read(2).decode()
        print("Received: {}".format(received_data))

    finally:
        # Close the serial connection
        ser.close()



data_to_send = "Hello, Raspberry Pi!"

send_data(serial_port, baud_rate, data_to_send)

receive_data(serial_port, baud_rate)
1
  • I have updated it. Please check. Also, I have used dev/serial0 it's showing the same error. Also, can you give examples of "sensible" code? Commented Dec 11, 2023 at 12:33

1 Answer 1

0

Your program is behaving as expected.

You close ser in send_data which will discard any data in the buffer.
You open in receive_data, and except in the unlikely circumstance that something will be received before you read the buffer is empty.

Open the port ONCE!

If I wanted to do something simple like this I would use a few lines of code e.g. (untested)

with serial.Serial(serial_port, baud_rate, timeout=1) as ser:
    ser.write(data_to_send.encode())
    print("Received: ", ser.read(2).decode())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.