Why serial communication connects to external devices in Raspberry Pi - Performance Analysis
When Raspberry Pi communicates with external devices using serial communication, it sends and receives data step by step.
We want to understand how the time it takes grows as the amount of data increases.
Analyze the time complexity of the following code snippet.
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
data = b"Hello, device!"
for byte in data:
ser.write(bytes([byte]))
response = ser.read(1)
ser.close()
This code sends data one byte at a time to an external device and waits for a one-byte response for each sent byte.
- Primary operation: Loop over each byte in the data to send and receive response.
- How many times: Once for every byte in the data.
Each byte sent requires one write and one read operation, so the total steps grow directly with data size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 (10 writes + 10 reads) |
| 100 | 200 (100 writes + 100 reads) |
| 1000 | 2000 (1000 writes + 1000 reads) |
Pattern observation: The number of operations grows in a straight line as data size increases.
Time Complexity: O(n)
This means the time to send and receive data grows directly in proportion to the number of bytes.
[X] Wrong: "Sending data over serial is instant and does not depend on data size."
[OK] Correct: Each byte must be sent and acknowledged, so more data means more time spent.
Understanding how communication time grows with data size helps you design efficient device interactions and shows you can think about real-world performance.
"What if we sent data in larger chunks instead of byte by byte? How would the time complexity change?"
