/*
 * Board:   Arduino Uno
 * Target:  PE Series on LED Effects
 * Author:  Clive "Max" Maxfield (max@clivemaxfield.com) 
 * License: The MIT License (See full license at the bottom of this file)
 *
 * Notes:   Switch -> On;  LED -> Fade-On (smoothly)
 *          Switch -> Off; LED -> Fade-Off (smoothly)
 */

#define SWITCH_ON          LOW
#define SWITCH_OFF        HIGH

#define LED_ON            HIGH
#define LED_OFF            LOW

#define NUM_FADE_STEPS      50
#define MAX_FADE_VALUE     255
#define FADE_ON_DELAY     1000
#define FADE_OFF_DELAY    1000


int PinSwitch = 4;
int PinLed    = 9;

int OldSwitchState;
int NewSwitchState;


void setup ()
{
    pinMode(PinSwitch, INPUT);
    pinMode(PinLed,   OUTPUT);

    OldSwitchState = digitalRead(PinSwitch);

    if (OldSwitchState == SWITCH_ON)
    {
        digitalWrite(PinLed, LED_ON);
    }
    else
    {
        digitalWrite(PinLed, LED_OFF);
    }
}


void loop ()
{
    unsigned long fadeValue;

    NewSwitchState = digitalRead(PinSwitch);

    if (NewSwitchState != OldSwitchState)
    {
        if (NewSwitchState == SWITCH_ON)
        {
            for (int iFade = 1; iFade <= NUM_FADE_STEPS; iFade++)
            {
                fadeValue = (MAX_FADE_VALUE * iFade) / NUM_FADE_STEPS;
                analogWrite(PinLed, fadeValue);
                delay(FADE_ON_DELAY / NUM_FADE_STEPS);
            }
        }
        else
        {
            for (int iFade = (NUM_FADE_STEPS - 1); iFade >= 0; iFade--)
            {
                fadeValue = (MAX_FADE_VALUE * iFade) / NUM_FADE_STEPS;
                analogWrite(PinLed, fadeValue);
                delay(FADE_OFF_DELAY / NUM_FADE_STEPS);
            }
        }

        OldSwitchState = NewSwitchState;
    }
}


/*
 * Copyright (c) 2019 Clive "Max" Maxfield
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and any associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHOR(S) OR COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */