/*
   Simple Wokwi Microphone Demo - hacked to include a frequency analyzer

   it doesn't work very well

  http://wiki.openmusiclabs.com/wiki/ArduinoFHT

*/

#define LOG_OUT 1 // use the log output function
#define FHT_N 256
#define NUM_LEDS 8
#include "FHT.h"
#include <FastLED.h>

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<NEOPIXEL, 5>(leds, NUM_LEDS);
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  // TIMSK0 = 0; // turn off timer0 for lower jitter  (hangs avr8js)
  ADCSRA = 0xe5; // set the adc to free running mode
  ADMUX = 0x40; // use adc0
  DIDR0 = 0x01; // turn off the digital input for adc0
}

void loop() {
  cli();  // UDRE interrupt slows this way down on arduino1.0

  if (1) {
    for (int i = 0 ; i < FHT_N ; i++) { // save 256 samples
      // while (!(ADCSRA & 0x10)); // wait for adc to be ready  (hangs avr8js)
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fht_input[i] = k; // put real data into bins
    }
  } else {
    for (int i = 0 ; i < FHT_N ; i++) { // save 128 samples
      int16_t k = (analogRead(A0) - 512) << 6;
      fht_input[i] = k; // put real data into bins
    }
  }
  fht_window(); // window the data for better frequency response
  fht_reorder(); // reorder the data before doing the fht
  fht_run(); // process the data in the fht
  fht_mag_log(); // take the output of the fht
  sei();

  for (uint8_t i = 0; i < NUM_LEDS; i++)
    leds[i] = HeatColor(fht_log_out[i]);
  FastLED.show();
}