Bird
0
0

Identify the error in this pyserial code snippet:

medium📝 Debug Q14 of 15
Raspberry Pi - Serial UART Communication
Identify the error in this pyserial code snippet:
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write('Hello')
ser.close()
AThe close method should be called before write
BThe Serial constructor is missing the timeout parameter
CThe port name '/dev/ttyUSB0' is invalid
DThe write method requires bytes, not a string
Step-by-Step Solution
Solution:
  1. Step 1: Check the write method argument type

    pyserial's write() expects bytes, but 'Hello' is a string, causing a TypeError.
  2. Step 2: Verify other parts of the code

    Timeout is optional, port name can be valid, and close() should be after write().
  3. Final Answer:

    The write method requires bytes, not a string -> Option D
  4. Quick Check:

    write() needs bytes, encode strings first [OK]
Quick Trick: Always encode strings to bytes before write() [OK]
Common Mistakes:
MISTAKES
  • Passing string directly to write() without encoding
  • Thinking timeout is mandatory
  • Closing port before writing data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes