#define CLK 13
#define DIN 11
#define CS 10
#define X_SEGMENTS 4
#define Y_SEGMENTS 4
#define NUM_SEGMENTS (X_SEGMENTS * Y_SEGMENTS)
byte fb[8 * NUM_SEGMENTS];
void shiftAll(byte send_to_address, byte send_this_data)
{
digitalWrite(CS, LOW);
for (int i = 0; i < NUM_SEGMENTS; i++) {
shiftOut(DIN, CLK, MSBFIRST, send_to_address);
shiftOut(DIN, CLK, MSBFIRST, send_this_data);
}
digitalWrite(CS, HIGH);
}
void setup() {
Serial.begin(115200);
pinMode(CLK, OUTPUT);
pinMode(DIN, OUTPUT);
pinMode(CS, OUTPUT);
shiftAll(0x0f, 0x00);
shiftAll(0x0b, 0x07);
shiftAll(0x0c, 0x01);
shiftAll(0x0a, 0x0f);
shiftAll(0x09, 0x00);
}
void loop() {
static uint32_t t = 0;
t++;
clear();
drawTree(16, 2, 26);
drawTrunk(16, 26, 6);
if ((t >> 4) & 1) {
set_pixel(16, 1, 1);
set_pixel(15, 2, 1);
set_pixel(17, 2, 1);
set_pixel(16, 3, 1);
}
for (int i = 0; i < 4; i++) {
twinkle(16, 2, 26);
}
show();
delay(40);
}
void drawTree(int cx, int top, int height) {
for (int y = 0; y < height; y++) {
int halfWidth = y / 2 + 1;
for (int x = cx - halfWidth; x <= cx + halfWidth; x++) {
safe_pixel(x, top + y, 1);
}
}
}
void drawTrunk(int cx, int top, int height) {
for (int y = 0; y < height; y++) {
for (int x = cx - 1; x <= cx + 1; x++) {
safe_pixel(x, top + y, 1);
}
}
}
void set_pixel(uint8_t x, uint8_t y, uint8_t mode) {
byte *addr = &fb[x / 8 + y * X_SEGMENTS];
byte mask = 128 >> (x % 8);
switch (mode) {
case 0:
*addr &= ~mask;
break;
case 1:
*addr |= mask;
break;
case 2:
*addr ^= mask;
break;
}
}
void safe_pixel(uint8_t x, uint8_t y, uint8_t mode) {
if ((x >= X_SEGMENTS * 8) || (y >= Y_SEGMENTS * 8))
return;
set_pixel(x, y, mode);
}
void clear() {
byte *addr = fb;
for (byte i = 0; i < 8 * NUM_SEGMENTS; i++)
*addr++ = 0;
}
void show() {
for (byte row = 0; row < 8; row++) {
digitalWrite(CS, LOW);
byte segment = NUM_SEGMENTS;
while (segment--) {
byte x = segment % X_SEGMENTS;
byte y = segment / X_SEGMENTS * 8;
byte addr = (row + y) * X_SEGMENTS;
if (segment & X_SEGMENTS) {
shiftOut(DIN, CLK, MSBFIRST, 8 - row);
shiftOut(DIN, CLK, LSBFIRST, fb[addr + x]);
} else {
shiftOut(DIN, CLK, MSBFIRST, 1 + row);
shiftOut(DIN, CLK, MSBFIRST, fb[addr - x + X_SEGMENTS - 1]);
}
}
digitalWrite(CS, HIGH);
}
}
void twinkle(int cx, int top, int height) {
int y = random(top, top + height);
int halfWidth = (y - top) / 2 + 1;
int x = random(cx - halfWidth, cx + halfWidth + 1);
safe_pixel(x, y, 2);
}