Skip to content

Instantly share code, notes, and snippets.

@neckro
Created May 19, 2016 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neckro/b97e9651809aca1afddbc09169e01e6d to your computer and use it in GitHub Desktop.
Save neckro/b97e9651809aca1afddbc09169e01e6d to your computer and use it in GitHub Desktop.
/* Runs Conway's Life cellular automata simulation on an 8x8 LED matrix.
6 January 2012 - neckro@gmail.com - No license. Do what thou wilt.
Requires a Maxim MAX7221 or MAX7219 LED controller IC.
Also requires LedControl library: http://www.arduino.cc/playground/Main/LedControl
*/
#include <LedControl.h>
// Number of ms to wait between frames
#define DELAY 45
// Number of iterations to run simulation
#define GROWTH 50
// LED array size
#define DIMX 8
#define DIMY 8
// LEDControl parameters
#define DATA_PIN 10
#define CLOCK_PIN 11
#define LOAD_PIN 12
#define ADDRESS 0
#define INTENSITY 15
// data, clock, load, number of devices
LedControl lc = LedControl(DATA_PIN, CLOCK_PIN, LOAD_PIN, 1);
uint8_t leda[DIMX][DIMY];
uint8_t ledb[DIMX][DIMY];
void setup() {
// set up LED controller
lc.shutdown(ADDRESS, false);
lc.setIntensity(ADDRESS, INTENSITY);
lc.clearDisplay(ADDRESS);
seedGrid();
}
void seedGrid() {
// initialize RNG
delay(100);
randomSeed(analogRead(0));
// generate random array
for(byte y=0; y<DIMY; y++) {
for(byte x=0; x<DIMX; x++) {
int r = boolean(random(0, 2) == 1);
leda[x][y]=r;
ledb[x][y]=r;
}
}
}
void loop() {
int live_cells = 0;
// check each cell
for(byte y=0; y<DIMY; y++) {
for(byte x=0; x<DIMX; x++) {
// count living neighbor cells
int count = 0;
for(int cx=-1; cx<2; cx++) {
for(int cy=-1; cy<2; cy++) {
byte lx = ((x+cx+DIMX) % DIMX);
byte ly = ((y+cy+DIMY) % DIMY);
if (leda[lx][ly])
count++;
}
}
boolean lin = leda[x][y];
boolean lout;
if (lin) count--; // don't count the current cell
// implement Life rules
ledb[x][y] = lout =
// if living and 2 or 3 neighbors, stay alive
(lin && (count == 2 || count == 3)) ||
// if dead and exactly 3 neighbors, become alive
(!lin && count == 3)
// else die or stay dead
;
if (lout) live_cells++;
}
}
// send array to display
for (byte y=0; y<DIMY; y++) {
int rowval = 0;
for (byte x=0; x<DIMX; x++) {
if (ledb[x][y]) bitSet(rowval, x);
// copy array value for next iteration
leda[x][y] = ledb[x][y];
}
lc.setRow(0, y, rowval);
}
delay(DELAY);
// reseed if no living cells remaining
if (live_cells == 0) seedGrid();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment