Consider this Python code using pyserial to open a serial port and read data:
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
data = ser.readline()
print(data)Assuming the device sends the bytes b'Hello\n', what will be printed?
import serial ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) data = ser.readline() print(data)
Remember that readline() returns bytes, not a string.
The readline() method returns a bytes object including the newline character. So the output is b'Hello\n'.
In the serial.Serial() constructor, which parameter controls the communication speed (baud rate)?
Think about the term that defines bits per second.
The baudrate parameter sets the speed of communication in bits per second.
What error will this code raise?
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write('Hello')import serial ser = serial.Serial('/dev/ttyUSB0', 9600) ser.write('Hello')
Check the type of data write() expects.
The write() method requires bytes, not a string. Passing a string causes a TypeError.
Choose the correct code to open a serial port /dev/ttyS0 at 115200 baud with a 2-second timeout.
Check parameter names and types carefully.
Option B uses correct parameter names and types. Option B passes timeout as string, which is invalid. Option B is valid syntax but timeout as float is accepted, but the question expects integer 2. Option B uses wrong parameter name baud.
You want to clear any old data in the input buffer before reading fresh data from the serial port. Which method should you call?
Look for the modern method name to reset input buffer.
The reset_input_buffer() method clears the input buffer. flushInput() is deprecated. flush() flushes output buffer. clear() does not exist.
