#include <Arduino.h>
// Pin definitions for the shift register (74HC595)
const int dsPin = 26; // Serial data input
const int shcpPin = 27; // Shift register clock input
const int stcpPin = 28; // Storage register (latch) clock input
// Digital pins for buttons and LED
const int btnIncrementPin = 24; // Connected to btn1 (using one terminal; other is GND)
const int btnDecrementPin = 25; // Connected to btn2 (using one terminal; other is GND)
const int ledPin = 29;
// Debounce delay in milliseconds
const unsigned long debounceDelay = 150;
// Lookup table for digits 0-9 for a common anode 7-seg display.
// For common anode, a LOW (0) turns on the segment.
// Patterns are arranged as: DP G F E D C B A (bit7 to bit0)
// Standard patterns: 0=0xC0, 1=0xF9, 2=0xA4, 3=0xB0, 4=0x99,
// 5=0x92, 6=0x82, 7=0xF8, 8=0x80, 9=0x90.
const byte digitPatterns[10] = {
0xC0, // 0
0xF9, // 1
0xA4, // 2
0xB0, // 3
0x99, // 4
0x92, // 5
0x82, // 6
0xF8, // 7
0x80, // 8
0x90 // 9
};
int currentDigit = 0;
void updateDisplay(byte pattern) {
// Latch low to start shifting new data
digitalWrite(stcpPin, LOW);
// Use shiftOut to send the byte to the shift register.
// Using MSBFIRST so that Q7 (DP) gets the MSB.
shiftOut(dsPin, shcpPin, MSBFIRST, pattern);
// Latch high to update outputs.
digitalWrite(stcpPin, HIGH);
}
void updateLED(int digit) {
// Turn on LED if digit is even, off if odd.
if(digit % 2 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
void setup() {
// Setup shift register control pins
pinMode(dsPin, OUTPUT);
pinMode(shcpPin, OUTPUT);
pinMode(stcpPin, OUTPUT);
// Setup LED pin
pinMode(ledPin, OUTPUT);
// Setup pushbutton pins; use built-in pullup: button press reads LOW.
pinMode(btnIncrementPin, INPUT_PULLUP);
pinMode(btnDecrementPin, INPUT_PULLUP);
// Initialize display with digit 0 and update LED accordingly.
currentDigit = 0;
updateDisplay(digitPatterns[currentDigit]);
updateLED(currentDigit);
}
void loop() {
// Check if the increment button is pressed (active low).
if(digitalRead(btnIncrementPin) == LOW) {
delay(debounceDelay); // Debounce delay
// Wait for the button to be released to avoid multiple triggers.
while(digitalRead(btnIncrementPin) == LOW) { }
// Increment and wrap-around if greater than 9.
currentDigit++;
if(currentDigit > 9) {
currentDigit = 0;
}
updateDisplay(digitPatterns[currentDigit]);
updateLED(currentDigit);
}
// Check if the decrement button is pressed (active low).
if(digitalRead(btnDecrementPin) == LOW) {
delay(debounceDelay); // Debounce delay
// Wait for the button to be released to avoid multiple triggers.
while(digitalRead(btnDecrementPin) == LOW) { }
// Decrement and wrap-around if less than 0.
currentDigit--;
if(currentDigit < 0) {
currentDigit = 9;
}
updateDisplay(digitPatterns[currentDigit]);
updateLED(currentDigit);
}
// Optional small delay to ensure loop stability.
delay(10);
}