I have written the following Arduino code to turn on LEDs one by one using a shift register. However, I have a few questions regarding the implementation and would appreciate any guidance or clarification. I am new to Arduino development.
Why is the shiftOut() function called twice — once for lowLED and once for highLED?
I would like to understand the reasoning behind using two calls instead of a single one.
Why are two separate byte variables (lowLED and highLED) used?
Is it possible to achieve the same result using only a single variable?
Can we use shiftOut(dataPin, clockPin, LSBFIRST, 0B0001000000000000); directly to control a specific LED?
For example, if I want to turn on the 10th LED, can I shift out a 16-bit binary value like 0B0001000000000000 directly?
Thank you in advance for your assistance. I truly appreciate your support and look forward to your insights.
Yes, but not using shiftOut(), as already explained.
This code (untested) uses hardware SPI and can send all 16 bits in a single call.
With shiftOut(), you can use any pins you like, but with hardware SPI the pins are fixed and depend on the model of Arduino you are using. I have assumed you are using Uno R3 or similar Arduino based on ATMEGA328.
#include <SPI.h>
// ST_CP pin 12
const int latchPin = 10;
// SH_CP pin 11
const int clockPin = 13;
// DS pin 14
const int dataPin = 11;
void setup() {
// Configure pins as outputs
pinMode(latchPin, OUTPUT);
SPI.begin();
SPI.beginTransaction(SPISettings(10000000, LSBFIRST, SPI_MODE0));
}
void loop() {
for (int i = 0; i < 16; i++) {
uint16_t LED = 1 << i;
digitalWrite(latchPin, LOW);
SPI.transfer16(LED);
digitalWrite(latchPin, HIGH);
delay(1000);
}
}
See this page for the pins to use for other models of Arduino: