Micropython and Arduino latency comparison
How fast is an instant? In this post we’ll explore how the seemingly instant actions can have large latency differences when observed with more than just the eye.
This answer claims that everything above 50ms has an increased chance of being perceived as not instant. So let’s dive into the realm of latencies lower than 1ms where there isn’t a chance for the eye to perceive the difference.
We’re going to set up an app on the esp8266 which turns on a led on a button click and observe what are the latency differences between the Micropython and Arduino implementations for the same hardware setup.
Assumptions
The assumption is that if you’d like to reproduce the results, you can do so own given all the sources used for writing this post. :)
The experiment
Hardware setup
The board used is Wemos D1 mini powered through a USB. One GPIO a switch, other GPIO a LED. Digital oscilloscope probes connected to the pins which will be used to measure the latencies.
Software
Micropython
import machine
led = machine.Pin(D1, machine.Pin.OUT)
button = machine.Pin(D0, machine.Pin.IN)
while True:
if button.value() == 0:
led.value(1)
else:
led.value(0)
Arduino
const int button = 16;
const int led = 5;
void setup() {
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}
void loop() {
if (digitalRead(button) == LOW){
digitalWrite(led, HIGH);
}
else{
digitalWrite(led, LOW);
}
}
The code for both cases is conceptually the same. An endless loop checking what the state of the switch is and turning on the led accordingly.
Do note that there are some peculiarities regarding inverted boolean values. I didn’t go exploring why this is so for this post.
Measurement
We’re measuring how much time passes from the moment the switch is pressed until the led lights up. This is achieved with the two digital oscilloscope probes each measuring the voltage levels we’re interested in. The oscilloscope is set to trigger when the switch is pressed.
Results
The results show that there is more than meets the eye. The overhead of running an interpreted language takes it’s toll on the latencies. A roughly averaged value shows that using Micropython results in a slowdown of 50 times. Do note, the results of the experiment are as expected and weren’t meant to put down Micropython. As always the choice of the technological approach depends on the requirements.