As the title says... Chat on...

User avatar
By Markus Gritsch
#4701 Hi,

just in case someone is interrested, I'd like to share my findings on improving the performance on pin toggling used e.g. when bit-banging some data:

timings.png

The screen shot above shows some measurements I made with my Logic Pirate. The corresponding Lua code is shown below:

Code: Select allpin = 9 -- 8 .. GPIO 0, 9 .. GPIO 2
gpio.mode(pin, gpio.OUTPUT)

-- 1
for i = 1, 2 do
  gpio.write(pin, gpio.HIGH)
  gpio.write(pin, gpio.LOW)
end

-- 2
for i = 1, 2 do
  gpio.write(pin, 1)
  gpio.write(pin, 0)
end

-- 3
gpio_write = gpio.write
for i = 1, 2 do
  gpio_write(pin, 1)
  gpio_write(pin, 0)
end

-- 4
for i = 1, 2 do
  gpio_write(9, 1)
  gpio_write(9, 0)
end

As one would expect, table lookups make things quite slow. The 1st loop has two lookups per pin state change, taking about 100 us. In the 2nd loop, when eliminating the lookup for gpio.HIGH and gpio.LOW and using 1 and 0 instead, the speed roughly doubles to 50 us. The 3rd loop uses a variable instead of the table lookup for gpio.write which leads to about 11 us, and in the 4th loop the variable lookup for pin is also eliminated shaving off another us.

So from 100 us to 10 us is quite some improvement, I would say :)

Cheers and have fun,
Markus