/*
* 74HC595 LED Chase Effect
*
* Wiring Connections:
* ┌─────────────────┬──────────┬─────────────────────────┐
* │ 74HC595 │ Pin │ Arduino Connection │
* ├─────────────────┼──────────┼─────────────────────────┤
* │ DS (Data) │ 14 │ D8 │
* │ SHCP (Clock) │ 11 │ D12 │
* │ STCP (Latch) │ 12 │ D11 │
* │ MR (Reset) │ 10 │ 5V │
* │ OE (Enable) │ 13 │ GND │
* │ VCC │ 16 │ 5V │
* │ GND │ 8 │ GND │
* └─────────────────┴──────────┴─────────────────────────┘
*
* LED Connections: Q0~Q7 -> 560Ω -> LED -> GND
*/
const int PIN_DATA = 8;
const int PIN_CLOCK = 12;
const int PIN_LATCH = 11;
const unsigned long INTERVAL_TIME = 500;
const int TOTAL_LEDS = 8;
unsigned long previous_millis = 0;
int current_led = 0;
bool led_state = true;
void setup()
{
initialize_pins();
turn_off_all_leds();
}
void loop()
{
if (is_time_to_update())
{
update_time_stamp();
if (is_led_on_state())
{
turn_on_current_led();
switch_to_off_state();
}
else
{
turn_off_all_leds();
switch_to_on_state();
move_to_next_led();
}
}
}
void initialize_pins()
{
pinMode(PIN_DATA, OUTPUT);
pinMode(PIN_CLOCK, OUTPUT);
pinMode(PIN_LATCH, OUTPUT);
}
bool is_time_to_update()
{
unsigned long current_millis = millis();
return (current_millis - previous_millis >= INTERVAL_TIME);
}
void update_time_stamp()
{
previous_millis = millis();
}
bool is_led_on_state()
{
return led_state;
}
void turn_on_current_led()
{
byte pattern = 1 << current_led;
update_shift_register(pattern);
}
void switch_to_off_state()
{
led_state = false;
}
void turn_off_all_leds()
{
update_shift_register(0x00);
}
void switch_to_on_state()
{
led_state = true;
}
void move_to_next_led()
{
current_led++;
if (current_led >= TOTAL_LEDS)
{
current_led = 0;
}
}
void update_shift_register(byte pattern)
{
digitalWrite(PIN_LATCH, LOW);
shiftOut(PIN_DATA, PIN_CLOCK, MSBFIRST, pattern);
digitalWrite(PIN_LATCH, HIGH);
}