Bird
0
0

What is the fix?

medium📝 Debug Q6 of 15
Raspberry Pi - Serial UART Communication
Identify the error in this Python code snippet reading GPS data: import serial ser = serial.Serial('/dev/serial0', 9600) while True: line = ser.readline().decode('utf-8') print(line) The program crashes with UnicodeDecodeError. What is the fix?
ARemove decode() call
BChange baudrate to 115200
CUse decode('utf-8', errors='replace') to handle bad bytes
DUse ser.read() instead of readline()
Step-by-Step Solution
Solution:
  1. Step 1: Understand cause of UnicodeDecodeError

    GPS data may contain invalid UTF-8 bytes causing decode failure.
  2. Step 2: Fix decoding with error handling

    Using errors='replace' in decode prevents crash by replacing bad bytes.
  3. Final Answer:

    Use decode('utf-8', errors='replace') to handle bad bytes -> Option C
  4. Quick Check:

    Decode errors handled = Use decode('utf-8', errors='replace') to handle bad bytes [OK]
Quick Trick: Add errors='replace' to decode to avoid crashes [OK]
Common Mistakes:
MISTAKES
  • Changing baudrate unnecessarily
  • Removing decode causes bytes print
  • Using read() loses line structure

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes