#define analogPin A0 // used to seed random function #define runPin 12 // blink LED when running #define pinSwitch 2 // used when lighting/extinguishing #define minFlame 32 // lowest PWM value for 'flame' #define lastLED endLED[3] // convenient definition to simplify code #define myPause 12 // pause between candle levels #define levelchange 12 // amount to change when blowing out candles #define puffs 10 // loop when blowing out candles #define ON 1 // definitions in code for clarity // list of pins to which candles are attached/controlled byte LEDPIN[] = { 3, 5, 6, 9, 11, 10}; // For Nano // ================================== void setup() { // initialize random function randomSeed(analogRead(analogPin)); // set up candles/ display startup sequence for (byte candle = 0; candle < 6; candle++) { pinMode(LEDPIN[candle], OUTPUT); analogWrite(LEDPIN[candle], 0); } // set up control (switch) pin pinMode(pinSwitch, INPUT_PULLUP); } // ================================== void loop() { byte level[] = {0, 0, 0, 0, 0, 0}; byte candle, i, repeat; boolean Lit = true; showStatus(); // display candles if (candlesLit()) { Lit = true; // remember that it's ok to blow out the candles for (byte candle = 0; candle < 6; candle++) { // there are six candles on the Nano level[candle] = random(minFlame, 255); // flicker is chosen randomly analogWrite(LEDPIN[candle], level[candle]); delay(myPause); // pause a bit at each lvel } } // blow out candles if (! candlesLit() && Lit) { // blow them out once! Lit = false; // changing this variable only executes the 'blow out' code once for (repeat = 0; repeat < puffs; repeat++) { // dim candle to out slowly // 'blow out' candles for (candle = 0; candle < 6; candle++) { // for each candle in a 'group' // dim out each candle level[candle] = constrain((level[candle] - levelchange), 0, 255); analogWrite(LEDPIN[candle], level[candle] ); if(candlesLit())break; // Request to light candle received; get out quick delay(myPause); // short delay between changes } if(candlesLit())break; // Request to light candle received; get out quick } for (candle = 0; candle < 6; candle++) // turn off all candles analogWrite(LEDPIN[candle], 0); } } // ================================== void showStatus() { static unsigned long updateTime = 0; static unsigned int ledState = HIGH; int nextState = LOW; if (millis() >= updateTime) { if (ledState == HIGH) nextState = LOW; if (ledState == LOW) nextState = HIGH; ledState = nextState; digitalWrite(runPin, ledState); updateTime = updateTime + 500; } } // ================================== boolean candlesLit() { return (digitalRead(pinSwitch) == ON); }