4. Identify the error in this pyserial code snippet:
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write('Hello')
ser.close()
medium
A. The close method should be called before write
B. The Serial constructor is missing the timeout parameter
C. The port name '/dev/ttyUSB0' is invalid
D. The write method requires bytes, not a string
Solution
Step 1: Check the write method argument type
pyserial's write() expects bytes, but 'Hello' is a string, causing a TypeError.
Step 2: Verify other parts of the code
Timeout is optional, port name can be valid, and close() should be after write().
Final Answer:
The write method requires bytes, not a string -> Option D
Quick Check:
write() needs bytes, encode strings first [OK]
Hint: Always encode strings to bytes before write() [OK]
Common Mistakes:
Passing string directly to write() without encoding
Thinking timeout is mandatory
Closing port before writing data
5. You want to read lines from a serial device that sends text ending with newline characters. Which pyserial method and parameters should you use to read a full line safely with a 2-second timeout?
hard
A. Use serial.Serial('/dev/ttyUSB0', 9600, timeout=None) and ser.readline()
B. Use serial.Serial('/dev/ttyUSB0', 9600, timeout=2) and ser.readline()
C. Use serial.Serial('/dev/ttyUSB0', 9600) and ser.read(100)
D. Use serial.Serial('/dev/ttyUSB0', 9600, timeout=0) and ser.readline()
Solution
Step 1: Set timeout for safe reading
Setting timeout=2 seconds ensures readline() waits up to 2 seconds for a line, avoiding blocking forever.
Step 2: Use readline() to read full lines
readline() reads until newline character, perfect for line-based text from serial devices.
Final Answer:
Use serial.Serial('/dev/ttyUSB0', 9600, timeout=2) and ser.readline() -> Option B
Quick Check:
timeout + readline() = safe line read [OK]
Hint: Use timeout with readline() to avoid blocking [OK]
Common Mistakes:
Using read() instead of readline() for lines
Setting timeout=None causes blocking
Setting timeout=0 causes non-blocking read with no wait
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.