Bird
0
0
Raspberry Piprogramming~5 mins

Communicating with Arduino over UART in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Communicating with Arduino over UART
O(n)
Understanding Time Complexity

When a Raspberry Pi talks to an Arduino using UART, it sends and receives data byte by byte. Understanding how long this communication takes helps us know how the program behaves as data grows.

We want to see how the time to send or receive data changes when the amount of data changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600)
data = b"Hello Arduino!"

for byte in data:
    ser.write(bytes([byte]))
ser.close()

This code opens a UART connection, sends each byte of a message one by one to the Arduino, then closes the connection.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Sending each byte over UART inside a loop.
  • How many times: Once for every byte in the data message.
How Execution Grows With Input

As the message gets longer, the number of bytes sent grows, so the time to send grows too.

Input Size (n)Approx. Operations
1010 writes
100100 writes
10001000 writes

Pattern observation: The time grows directly with the number of bytes; doubling bytes doubles the time.

Final Time Complexity

Time Complexity: O(n)

This means the time to send data grows in a straight line with the size of the data.

Common Mistake

[X] Wrong: "Sending data over UART happens instantly no matter how much data there is."

[OK] Correct: Each byte takes time to send, so more bytes mean more time. It's like mailing letters one by one; more letters take longer.

Interview Connect

Knowing how communication time grows helps you design programs that handle data efficiently and avoid slowdowns, a useful skill in many real projects.

Self-Check

"What if we sent data in larger chunks instead of byte by byte? How would the time complexity change?"