Last active
September 20, 2020 15:17
-
-
Save benjamintanweihao/eb12d03ec034fdc404a9883855961125 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "FastLED.h" | |
#include "limits.h" | |
#define NUM_LEDS 60 // How many leds in your strip? | |
#define DATA_PIN 5 // led data transfer | |
#define MICROPHONE_PIN A0 | |
long sensorMax = 0; | |
long sensorMin = LONG_MAX; | |
const int numReadings = 100; | |
CRGB leds[NUM_LEDS]; // Define the array of leds | |
CRGBPalette16 currentPalette; | |
TBlendType currentBlending; | |
long readings[numReadings]; // the readings from the analog input | |
int readIndex = 0; // the index of the current reading | |
int total = 0; // the running total | |
int average = 0; | |
float exponent = 3.2; // increase the difference between high and low. | |
void setup() | |
{ | |
Serial.begin(9600); | |
pinMode(MICROPHONE_PIN, INPUT); | |
for (int i = 0; i < numReadings; i++) { | |
readings[i] = -1; | |
} | |
delay(1000); // power-up safety delay | |
currentPalette = RainbowColors_p; | |
currentBlending = LINEARBLEND; | |
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); | |
FastLED.setBrightness(64 ); | |
FastLED.show(); | |
} | |
void loop() | |
{ | |
long soundVal = pow(analogRead(A0), exponent); | |
readings[readIndex] = soundVal; | |
if (readIndex >= numReadings) { | |
readIndex = 0; | |
} | |
sensorMin = findMin(readings, numReadings); | |
sensorMax = findMax(readings, numReadings); | |
readIndex++; | |
int numLeds = (((soundVal-sensorMin)*1.)/(sensorMax-sensorMin))*(NUM_LEDS/2); | |
Serial.println(numLeds); | |
fillLEDSwithColor(numLeds); | |
FastLED.show(); | |
delay(50); | |
} | |
void fillLEDSwithColor(uint8_t currLeds) | |
{ | |
int colorIndex = 0; | |
int firstRightIdx = NUM_LEDS / 2; | |
for (int i = 0; i < firstRightIdx; i++) { | |
if (i < currLeds) { | |
leds[firstRightIdx+i-1] = ColorFromPalette(currentPalette, colorIndex, 255, currentBlending); | |
leds[firstRightIdx-i] = ColorFromPalette(currentPalette, colorIndex, 255, currentBlending); | |
} | |
else { | |
leds[firstRightIdx+i-1].fadeToBlackBy(100); | |
leds[firstRightIdx-i].fadeToBlackBy(100); | |
} | |
colorIndex += 10; | |
} | |
FastLED.show(); | |
} | |
long findMin(long* arr, int sz) | |
{ | |
long minimum = arr[0]; | |
for (int i = 0; i < sz; i++) { | |
if (arr[i] == -1) | |
continue; | |
if (arr[i] < minimum) { | |
minimum = arr[i]; | |
} | |
} | |
return minimum; | |
} | |
long findMax(long* arr, int sz) | |
{ | |
long maximum = arr[0]; | |
for (int i = 0; i < sz; i++) { | |
if (arr[i] > maximum) { | |
maximum = arr[i]; | |
} | |
} | |
return maximum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment