0
\$\begingroup\$

I need to use a shift register to control multiple leds, but I need to control each one individually. The idea would be to send a buffer with the data, however I need to have several active leds and just want to change the state of each one at a time. For example: change state of led in PIN 1 of the PORTC to HIGH, then the led in PORTC PIN 2 to HIGH, then the led in PORTC PIN 1 to LOW etc ... Can someone give me and advice or some example code? Thanks for listening

\$\endgroup\$
2
\$\begingroup\$

That is doing it the hard way in my opinion. Manipulate a byte (8 bits) or two with the LED on/off states. Then just do a single SPI.transfer to send the data out. All outputs will update at the same time. If you shift out the same data, the output stays the same.

// time for an output change?
digitalWrite (ssPin, LOW); // SS goes to RCLK
SPI.transfer(dataToDisplay);  // SCK goes to SH_CLK, Data goes to Serial Data In
SPI.transfer(dataToDisplay2);  // use if have 2  shift registers.
digitalWrite (ssPin, HIGH); // all outputs update on this rising edge
\$\endgroup\$
0
\$\begingroup\$

The idea is to send the bits in the order in which the LEDs are attached to the shift register, meanwhile changing the clock pin for synchronisation.

You store one byte for each of the 8 LEDs (or less) you want to control. When you want to change one LED you change the appropriate bit, and send the bits to the shift register using the shiftOut function.

On an Arduino this is part of the library, otherwise you have to do it manually.

On this arduino shift out in native C question you can find the code, here is the fragment:

void shiftOut(GPIO dataPin, GPIO clockPin, bool MSBFIRST, uint8_t command)
{
   for (int i = 0; i < 8; i++)
   {
       bool output = false;
       if (MSBFIRST)
       {
           output = command & 0b10000000;
           command = command << 1;
       }
       else
       {
           output = command & 0b00000001;
           command = command >> 1;
       }
       writePin(dataPin, output);
       writePin(clockPin, true);
       sleep(1)
       writePin(clockPin, false);
       sleep(1)
    }
}

In case you want more than 8 LEDs to control, you can store 4 bytes (uint32_t) and change the command argument type from uint8_t to uint32_t and the for loop to run until 32. Of course the shift registers need to be chained (max 4 for max 32 LEDs).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.