// 7 segments perlin fire demo 
//Yaroslaw Turbin 15-05-2024
//https://vk.com/ldirko
//https://www.reddit.com/user/ldirko/
//https://twitter.com/ldir_ko
//https://www.youtube.com/c/ldirldir


#include <FastLED.h> // i use this for perlin noise

#define dataPin   2  
#define latchPin  0 
#define clockPin  4  

#define NUM_LEDS 8*3*2

byte leds_gray [NUM_LEDS];

byte pixelMapX_norm[NUM_LEDS + 1];
byte pixelMapY_norm[NUM_LEDS + 1];

byte output_bit_buff [NUM_LEDS/8];

#include "tables.h"
 

void setup() {
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}


void send_Number (byte segment, byte number){
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, segment); 
  shiftOut(dataPin, clockPin, MSBFIRST, number); 
  digitalWrite(latchPin, HIGH);
}


void fire2021 (byte *pixelMapX_norm, byte *pixelMapY_norm){
  int  a = millis();
  int  a1 = a/3; 
  byte _buffY = pixelMapY_norm[NUM_LEDS];
  for (int z = 0; z < NUM_LEDS; z++) {   //fastest method
    byte i = pixelMapX_norm[z]; 
    byte j = pixelMapY_norm[z];
    byte gray = qsub8 (inoise8 ((i<<5), (j<<5) +a, a1), abs8(j - (_buffY-1)) * (255 / (_buffY+15)));
    leds_gray[z] = gray;
  }
}


void convert_Leds_to_Bits (){
  int index = 0;
    for (byte i = 0; i < NUM_LEDS/8; i++) {
      byte outputBits = 255;  
      for (byte j = 0; j < 8; j++) {
        outputBits <<= 1;
        byte color = leds_gray[index];
        if (color<105) {outputBits|= 0b00000001;}  //dirty convert to BW 
        index++;
      }
      output_bit_buff [i] = outputBits;
    }
} 


void out_Bits(){
    for (byte i = 0; i < 6; i++) {
      send_Number (1<<i, output_bit_buff [i]);  
      delay(1);
    }  
}


void FPS(){
  static int frame = 0;
  static double currenttime = millis();

  if ((millis()-currenttime)>8000) {
    Serial.print("FPS: ");
    Serial.println(frame/8);
    frame = 0;
    currenttime = millis();
  }

  frame++;
}


void test_bit_output (){
    normMapsGenerator_From_Coords (14, 13, pixelMapX, pixelMapY);
    fire2021 (pixelMapX_norm, pixelMapY_norm);
    convert_Leds_to_Bits ();
    out_Bits();
}


void loop() {
  test_bit_output ();
  FPS();
}
74HC595
74HC595