Skip to content

Instantly share code, notes, and snippets.

@MarinaPascual
Created February 12, 2020 20:05
Show Gist options
  • Save MarinaPascual/3ea6791267a2b60713d376808342396a to your computer and use it in GitHub Desktop.
Save MarinaPascual/3ea6791267a2b60713d376808342396a to your computer and use it in GitHub Desktop.
Code for Artificial Candle
#include <Adafruit_NeoPixel.h>
#include <ColorConverter.h>
int currentLevel = 1;
int change = 1;
byte levelTable[256]; // pre-calculated PWM levels
const int neoPixelPin = 5; // control pin
const int pixelCount = 7; // number of pixels
//float change = 1; // increment to change hue by
const int buttonPin = 2;
int buttonState = 0;
// set up strip:
Adafruit_NeoPixel strip = Adafruit_NeoPixel(pixelCount, neoPixelPin, NEO_GRBW + NEO_KHZ800);
ColorConverter converter;
int h = 10; // hue
int s = 100; // saturation
int i = 100; // intensity
void setup() {
Serial.begin(9600);
// pre-calculate the PWM levels from the formula:
fillLevelTable();
strip.begin(); // initialize pixel strip
strip.clear(); // turn all LEDs off
strip.show(); // update strip
pinMode(neoPixelPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
// create a single color from hue, sat, intensity:
RGBColor color = converter.HSItoRGB(h, s, i);
buttonState = digitalRead(buttonPin);
// loop over all the pixels:
for (int pixel = 0; pixel < pixelCount; pixel++) {
strip.setPixelColor(pixel, color.red, color.green, color.blue); // set the color for this pixel
strip.show(); // update the strip
// delay(random(0,1000));
}
// increment hue to fade from red (0) to reddish orange (15) and back:
h = h + change;
if (h <= random(8, 14) || h >= 15) {//15
change = -change;
}
currentLevel += change;
//PWM output the result:
delay(random(3, 20));
analogWrite(9, levelTable[currentLevel]);
Serial.println(levelTable[currentLevel]);
if (buttonState == HIGH) {
digitalWrite(neoPixelPin, LOW);
} else {
// turn LED off:
digitalWrite(neoPixelPin, HIGH);
}
Serial.print(buttonState);
}
void fillLevelTable() {
// set the range of values:
float maxValue = 255;
// iterate over the array and calculate the right value for it:
for (int l = 0; l <= maxValue; l++) {
// square the current value:
float lightLevel = pow(l, 2);
// map the result back to a 0-255 range:
lightLevel = map(lightLevel, 0, 65535, 0, 255);
levelTable[l] = lightLevel;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment