How to shift out 16 bits fast on arduino board

74hc595arduinoatmegashift-register

I'm coding a system that need to shift out 16 bits fast from a uint16_t variable to two paired 74HC595 shift registers. I'm running the code on an Arduino (atmega328@16Mhz) and the shiftOut in the Arduino is way too slow. The librarys digitalWrite function is slow as well.

The best idea I came up with is a for loop that loops through all the 16 bits of the variable and writes 1/0 to data pin, set the clock bit high as short as possible and then goes to the next bit of the variable.

Is this the fastest solution and if so, how do I loop through a uint16_t variables bits in c++?

Best Answer

This is simple enough with the SPI library.

Connect your shift register input to the MOSI pin (Master Out, Slave In) - Digital pin 11 - and you will have nice fast transfers.

There will be a very slight delay between the upper and lower 8 bits of each word transmitted.

For example:

#include <SPI.h>

void begin()
{
    SPI.begin();
}

void loop()
{
    unsigned int val;

    val = rand()%0xFFFF; // Generate a random 16 bit number

    SPI.transfer(val >> 8);  // Output the MSB first
    SPI.transder(val & 0xFF); // Followed by the LSB

    delay(1000);  // Wait a sec...
}