/*
 * By: Andrew Tuline
 *
 * Using FastLED's inoise8() function to simulate sound, but NOW WITH SOUND!!! thanks to urish!!
 * 
 * Issue: I perform ---> yVal = 16-yVal;             // where yVal is between 0 and 16.
 * 
 *        when I do so, it affects xVal.
 *
 */

#include <FastLED.h>

#define matrixWidth 24
#define matrixHeight 16
#define matrixSerpentineLayout false           // Hmm, these LED's don't seem to be serpentine.
#define NUM_LEDS matrixWidth*matrixHeight

#define DATA_PIN 6

CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(115200);
    FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
} // setup()

void loop() {

  EVERY_N_MILLIS(100) {
    sounder();
  }
  FastLED.show();

} // loop()



void sounder() {

  static float micLev;                // Used to zero out average signal strength.

  fadeToBlackBy(leds, NUM_LEDS, 16);


// xVal is time, which is a fixed rate and should not be changed further.
  uint8_t xVal = (millis()/50);
  xVal = xVal % matrixWidth;

// yVal is our sound level, which goes from 0 to 255 when using iNoise8().
  int16_t yVal = inoise8(millis(), millis());              // 16 bit for later use with ADC's.
 // int16_t yVal = analogRead(A0)/4;


  float yWeight = .1;
  micLev = yWeight * (float)yVal + (1.0-yWeight) * (float)micLev;
  yVal -= (int)micLev;
  yVal = abs(yVal);                                           // We have zeroed out the signal here. Now, we just need positive values.

  yVal = map(yVal,0,128,0,matrixHeight-1);                      // It's a low signal, so let's map the interesting part of it.
  yVal = constrain(yVal,0,(matrixHeight-1));
  yVal = matrixHeight-yVal; 

  leds[XY(xVal, yVal)] = CHSV(millis()/50,255,255);    

} // sounder()




uint16_t XY( uint8_t x, uint8_t y) {               // Standard XY translation routine.

  uint16_t i;

  if ( matrixSerpentineLayout == false) {
    i = (y * matrixWidth) + x;
  }

  if ( matrixSerpentineLayout == true) {
    if ( y & 0x01) {
      uint8_t reverseX = (matrixWidth - 1) - x;
      i = (y * matrixWidth) + reverseX;
    } else {
      i = (y * matrixWidth) + x;
    }
  }
  return i;

} // XY()