// Pin definitions
int latchPin = 9; // Pin connected to ST_CP (Latch Pin) of 74HC595
int clockPin = 10; // Pin connected to SH_CP (Clock Pin) of 74HC595
int dataPin = 8; // Pin connected to DS (Data Pin) of 74HC595
int potPin = A0; // Pin connected to the middle pin of the potentiometer
int numOfRegisters = 2; // Global variable for the number of shift registers (e.g., 2 registers = 16 LEDs)
int numLeds = numOfRegisters * 8; // Total number of LEDs controlled
int bitOrderPin = 12;
void setup() {
// Set up the control pins for the 74HC595
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(bitOrderPin, INPUT_PULLUP);
// Set up serial monitor for debugging (optional)
Serial.begin(9600);
}
void loop() {
// Read potentiometer value (0 to 1023)
int potValue = analogRead(potPin);
int bitOrderState = digitalRead(bitOrderPin);
// Map the potentiometer value to a range of 0 to numLeds
int numLedsOn = map(potValue, 0, 1023, 0, numLeds);
// Display the mapped value on the LEDs using the specified bit order
if (bitOrderState == HIGH) {
updateLEDs(numLedsOn, LSBFIRST);
}
else {
updateLEDs(numLedsOn, MSBFIRST);
}
// Optional: Print the number of LEDs on for debugging
Serial.print("Potentiometer value: ");
Serial.print(potValue);
Serial.print(" | Number of LEDs ON: ");
Serial.println(numLedsOn);
// Small delay to smoothen the potentiometer reading
delay(100);
}
//Function to update LEDs based on the number to be lit, using the global numOfRegisters
void updateLEDs(int numLedsOn, int bitOrder) {
// Create a value with all bits for the LEDs to be on, and ensure it fits in the available space
unsigned long long ledState = (1ULL << numLedsOn) - 1; // Use a 64-bit variable to hold the LED states for larger numbers of LEDs
// Start sending data to the shift registers
digitalWrite(latchPin, LOW); // Prepare to send data
// Iterate through the registers and send data for each one
if (bitOrder == MSBFIRST) {
for (int i = numOfRegisters - 1; i >= 0; i--) {
byte currentByte = (ledState >> (i * 8)) & 0xFF; // Extract 8 bits for each register
shiftOut(dataPin, clockPin, MSBFIRST, currentByte); // Send the byte to the shift register
}
} else {
for (int i = 0; i < numOfRegisters; i++) {
byte currentByte = (ledState >> (i * 8)) & 0xFF; // Extract 8 bits for each register
shiftOut(dataPin, clockPin, LSBFIRST, currentByte); // Send the byte to the shift register
}
}
digitalWrite(latchPin, HIGH); // Latch the data to the output pins
}