mmarchetti / DirectIO

Fast, simple I/O library for Arduino
GNU Lesser General Public License v3.0
116 stars 27 forks source link

Speed up OutputPort::write() #34

Open WestfW opened 1 year ago

WestfW commented 1 year ago

Current OutputPort::write() code:

        void write(port_data_t value) {
            atomic {
                // read-modify-write cycle
                port_data_t v = port::port_output_read();
                port_data_t shifted = value << start_bit;
                v |= shifted & mask;
                v &= (shifted | ~mask);
                port::port_output_write(v);
            }
        }

On chips that have an output toggle feature, this can probably be sped up significantly using the clever XOR-based trick that I first saw in the RPi Pico SDK (https://github.com/raspberrypi/pico-sdk/blob/master/src/rp2_common/hardware_gpio/include/hardware/gpio.h#L719 )

the new code would not need "atomic", and would look something like:

        void write(port_data_t value) {
              port_data_t v = port::port_output_read();
              port_data_t shifted = value << start_bit;
              v ^= shifted;
              port::port_output_toggle(v & mask);
        }