#include <SPI.h>
//#define DATA_PIN 2
//#define CLOCK_PIN 3
#define LATCH_PIN PD3
#define NUM_REGISTERS 3
volatile bool gombNyomva = false;
uint8_t bits[NUM_REGISTERS] = {0};
//mely ledeket - shift reg biteket kezeli az updateshifregister
bool usedByLedGroup[NUM_REGISTERS * 8] = {false};
struct LedGroup {
bool* leds; // pointer a LED állapot tömbhöz
const uint8_t* map; // a globális bitpozíció minden LEDhez
uint8_t size; // hány LED van a csoportban
};
bool J2[3] = {false, false, false}; // 2 LED
bool J3[3] = {false, false, false}; // 3 LED
bool J4[3] = {false, false, false}; // 4 LED
// Melyik LED hányadik bithez tartozik
const uint8_t J2map[3] = {0, 1, 2}; // 595 #0: Q0, Q1
const uint8_t J3map[3] = {3, 4, 5}; // 595 #0: Q2-Q4
const uint8_t J4map[3] = {6, 7, 8}; // 595 #1: Q0-Q3
LedGroup groups[] = {
{J2, J2map, 3},
{J3, J3map, 3},
{J4, J4map, 3}
};
const uint8_t numGroups = sizeof(groups)/sizeof(groups[0]);
void markLedGroupBits() {
for (int g = 0; g < numGroups; g++) {
for (int i = 0; i < groups[g].size; i++) {
uint8_t bitIndex = groups[g].map[i];
usedByLedGroup[bitIndex] = true;
}
}
}
void setShiftBit(uint8_t bitIndex, bool value) {
if (value)
bits[bitIndex / 8] |= (1 << (bitIndex % 8));
else
bits[bitIndex / 8] &= ~(1 << (bitIndex % 8));
}
void updateShiftRegisters() {
// Csak a LED által kezelt biteket nullázzuk
for (int i = 0; i < NUM_REGISTERS * 8; i++) {
if (usedByLedGroup[i])
bits[i / 8] &= ~(1 << (i % 8));
}
// végigmegyünk a csoportokon
for(int g=0; g<numGroups; g++) {
for(int i=0; i<groups[g].size; i++) {
if(groups[g].leds[i]) {
uint8_t bitIndex = groups[g].map[i];
bits[bitIndex/8] |= (1 << (bitIndex%8));
}
}
}
// kiküldés a shift register láncba
digitalWrite(LATCH_PIN, LOW);
for(int i=NUM_REGISTERS-1;i>=0;i--) SPI.transfer(bits[i]);
digitalWrite(LATCH_PIN, HIGH);
}
void setup() {
// pinMode(DATA_PIN, OUTPUT);
// pinMode(CLOCK_PIN, OUTPUT);
pinMode(LATCH_PIN, OUTPUT);
pinMode(PB13, INPUT_PULLUP);
pinMode(PB14, INPUT_PULLUP);
pinMode(PB15, INPUT_PULLUP);
digitalWrite(LATCH_PIN, LOW);
// digitalWrite(CLOCK_PIN, LOW);
// digitalWrite(DATA_PIN, LOW);
SPI.begin();
// Hardver SPI sebesség beállítása: 24 MHz, MSB first, Mode 0
SPI.beginTransaction(SPISettings(24000000, MSBFIRST, SPI_MODE0));
attachInterrupt(digitalPinToInterrupt(PB13), erz3, FALLING);
attachInterrupt(digitalPinToInterrupt(PB14), erz2, FALLING);
attachInterrupt(digitalPinToInterrupt(PB15), erz1, FALLING);
J2[2] = true;
J4[0] = true;
markLedGroupBits();
}
void loop() {
// put your main code here, to run repeatedly:
//J2[0] = true;
//J3[0]= true;
//J4[0]= true;
//J4[3]= true;
updateShiftRegisters();
}
void erz3() {
if(J4[0]) {
setShiftBit(23, true);
}
gombNyomva = true;
}
void erz2() {
if (J2[2]) {
J2[2] = false;
J2[0] = true;
}
gombNyomva = true;
}
void erz1() {
if(!J2[2]) {
setShiftBit(22, true);
}
gombNyomva = true;
}