Bird
0
0
Raspberry Piprogramming~20 mins

pyserial library usage in Raspberry Pi - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PySerial Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
What is the output of this pyserial code snippet?

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?

Raspberry Pi
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
data = ser.readline()
print(data)
Ab'Hello\n'
B'Hello\n'
CHello
Db'Hello'
Attempts:
2 left
💡 Hint

Remember that readline() returns bytes, not a string.

🧠 Conceptual
intermediate
1:00remaining
Which parameter sets the baud rate in pyserial?

In the serial.Serial() constructor, which parameter controls the communication speed (baud rate)?

Abaudrate
Bport
Ctimeout
Dparity
Attempts:
2 left
💡 Hint

Think about the term that defines bits per second.

Predict Output
advanced
1:30remaining
What error does this pyserial code raise?

What error will this code raise?

import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write('Hello')
Raspberry Pi
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.write('Hello')
ANo error, writes successfully
BValueError: invalid port
CAttributeError: 'Serial' object has no attribute 'write'
DTypeError: a bytes-like object is required, not 'str'
Attempts:
2 left
💡 Hint

Check the type of data write() expects.

📝 Syntax
advanced
1:30remaining
Which option correctly opens a serial port with a 2-second timeout?

Choose the correct code to open a serial port /dev/ttyS0 at 115200 baud with a 2-second timeout.

Aserial.Serial('/dev/ttyS0', 115200, timeout='2')
Bserial.Serial(port='/dev/ttyS0', baudrate=115200, timeout=2)
Cserial.Serial('/dev/ttyS0', baudrate=115200, timeout=2.0)
Dserial.Serial(port='/dev/ttyS0', baud=115200, timeout=2)
Attempts:
2 left
💡 Hint

Check parameter names and types carefully.

🚀 Application
expert
2:00remaining
How to flush input buffer before reading data?

You want to clear any old data in the input buffer before reading fresh data from the serial port. Which method should you call?

Aser.flushInput()
Bser.clear()
Cser.reset_input_buffer()
Dser.flush()
Attempts:
2 left
💡 Hint

Look for the modern method name to reset input buffer.