// prima oara vom memora pozitiile la care este conectata matricea:
int MOSI_pin = 11; //din
int SlaveSelect_pin = 10;
int Clock_pin = 13;
// apoi stabilim cateva zone memorabile din max:
byte max7219_reg_noop = 0x00; // nu face nimic
byte max7219_reg_digit0 = 0x01; // seteaza primul rand
byte max7219_reg_digit1 = 0x02;
byte max7219_reg_digit2 = 0x03;
byte max7219_reg_digit3 = 0x04;
byte max7219_reg_digit4 = 0x05;
byte max7219_reg_digit5 = 0x06;
byte max7219_reg_digit6 = 0x07;
byte max7219_reg_digit7 = 0x08;
byte max7219_reg_decodeMode = 0x09;
byte max7219_reg_intensity = 0x0a;
byte max7219_reg_scanLimit = 0x0b;
byte max7219_reg_shutdown = 0x0c;
byte max7219_reg_displayTest = 0x0f;
void putByte(byte data) { // trebuie sa scriem bitii din data pe rand, de la stg la dreapta, sincronizat
for (int i=15; i>=0; i--)
{
digitalWrite(Clock_pin, LOW); // incepe o scriere sincronizata
digitalWrite(MOSI_pin, data & (0x01 << i)); // cand i=7 scriu cel mai din stg bit din data...
digitalWrite(Clock_pin, HIGH); // a terminat sincronismul
}
}
void toMax( byte reg, byte col) {
digitalWrite(SlaveSelect_pin, LOW); // selectez slaveul
putByte(reg); // ii zic in ce zona de memorie scriu
putByte(col); // si scriu valoarea
digitalWrite(SlaveSelect_pin,HIGH); // deselectez slaveul ca sa activez ce am scris
}
void setup() {
Serial.begin(9600);
pinMode(MOSI_pin, OUTPUT);
pinMode(Clock_pin, OUTPUT);
pinMode(SlaveSelect_pin, OUTPUT);
digitalWrite(Clock_pin, HIGH);
// cateva setari:
toMax(max7219_reg_scanLimit, 0x07);
toMax(max7219_reg_decodeMode, 0x00);
toMax(max7219_reg_shutdown, 0x01); // nu e in shutdown
toMax(max7219_reg_displayTest, 0x00); // nu testez nimic
for (int i=1; i<=8; i++) {
toMax(i,0); // curat fiecare rand
}
toMax(max7219_reg_intensity, 0x00); // setez intensitatea la minim
}
byte a[10][10];
uint64_t h[10]; // history
byte ph=0;
byte lineToByte(byte a[][10], byte ln){
byte v = 0;
for(byte i=1; i<=8; i++)
v |= (a[ln][i] << (i-1));
return v;
}
void displayMatrixOnMAX(byte a[][10]){
for(byte i=1; i<=8; i++)
toMax(i,lineToByte(a,i));
}
void generatePopulation(byte a[][10]){
for(byte i=1; i<=8; i++)
for(byte j=1; j<=8; j++)
a[i][j]=(rand() % 2);
}
uint64_t nextPopulation(byte a[][10]){
uint64_t vh=0;
byte pozBit=0;
int dir[8][2] ={{-1,-1},{-1,1},{1,-1},{1,1},{-1,0},{1,0},{0,-1},{0,1}};
byte b[10][10];
for(byte i=0; i<=9; i++)
for(byte j=0; j<=9; j++)
b[i][j]=a[i][j];
for(byte i=1; i<=8; i++)
for(byte j=1; j<=8; j++)
{
byte cnt=0;
for(byte d=0; d<8; d++)
cnt+=b[i+dir[d][0]][j+dir[d][1]];
if (cnt<2 || cnt>3) a[i][j]=0;
if (cnt==3) a[i][j]=1;
vh |= (a[i][j]<<pozBit);
Serial.print(a[i][j]);
pozBit++;
}
Serial.println();
return vh;
}
void loop() {
byte newPop=0;
generatePopulation(a);
while(newPop==0)
{
displayMatrixOnMAX(a);
delay(200);
uint64_t x = nextPopulation(a);
for(byte z=0; z<10; z++)
if (h[z]==x){
delay(10000);
newPop=1;
}
h[ph]=x;
ph++;
ph%=10;
}
}