Bird
0
0

What is the issue in this Raspberry Pi Python code for serial communication?

medium📝 Debug Q6 of 15
Raspberry Pi - Serial UART Communication
What is the issue in this Raspberry Pi Python code for serial communication?
import serial
ser = serial.Serial('/dev/ttyS0', 9600)
data = ser.read(5).decode()
print(data)
AThe decode() method is used incorrectly
BThe code may block if 5 bytes are not available to read
CThe serial port is not opened properly
DThe print statement syntax is wrong
Step-by-Step Solution
Solution:
  1. Step 1: Understand ser.read(5)

    This call blocks until 5 bytes are received, which may cause the program to hang if data is slow.
  2. Step 2: Check decode usage

    decode() without arguments defaults to 'utf-8', which is correct here.
  3. Step 3: Verify serial port and print

    Serial port is opened correctly and print syntax is valid.
  4. Final Answer:

    The code may block if 5 bytes are not available to read -> Option B
  5. Quick Check:

    Read blocks until requested bytes arrive [OK]
Quick Trick: read() blocks until requested bytes received [OK]
Common Mistakes:
MISTAKES
  • Assuming decode() is incorrect without arguments
  • Thinking serial port is not opened
  • Believing print syntax is wrong

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes