Bird
0
0

Find the bug in this Raspberry Pi Python code for serial communication:

medium📝 Debug Q7 of 15
Raspberry Pi - Serial UART Communication
Find the bug in this Raspberry Pi Python code for serial communication:
import serial
ser = serial.Serial('/dev/ttyS0', 9600)
data = ser.read(5).decode('utf-8')
print(data.upper())
The output is always empty.
ASerial port is not opened before reading
Bread(5) may block if less than 5 bytes available
Cdecode('utf-8') is incorrect usage
Dprint(data.upper()) causes error
Step-by-Step Solution
Solution:
  1. Step 1: Understand ser.read(5) behavior

    read(5) waits until 5 bytes are received; if device sends fewer bytes, it blocks or returns empty.
  2. Step 2: Connect blocking to empty output

    If device sends less than 5 bytes or none, read blocks or returns empty bytes, so output is empty string.
  3. Final Answer:

    read(5) may block if less than 5 bytes available -> Option B
  4. Quick Check:

    read() blocks if requested bytes unavailable [OK]
Quick Trick: read(n) waits for n bytes; may block if not ready [OK]
Common Mistakes:
MISTAKES
  • Assuming port must be opened explicitly
  • Thinking decode('utf-8') is wrong
  • Believing print(data.upper()) causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes