Sunday, December 14, 2014

Arduino/Trinket - Controlling a 5 state program with a button and a led - Part II

The Trinket is $6.95 micro controller from Adafruit that is compatible with the Arduino.
First see Part I.

See Video

In part II, I created a class name MultiStateButton that can 
  • Manage the 5 multi states associated with the button
  • Handle the user input
  • Handle the user interface AKA the LED
I also created a class Led dedicated to abstract a LED. The real utility of the class Led is that it can blink the led, without using the delay() function.

I still need to add a second Switch to handle moving backward among the states.
For now I could not make it work.
I also need to do some cleaning some of my coding convention are off.

The source code is on github at fArduino

#include "fArduino.h"

const int SWITCH_PIN                  = 0;
const int SWITCH_PIN_PREVIOUS         = 1;
const int LED_PIN                     = 1;  // Red LED on the Trinket
const int LED_LIGTH_STEP_VALUES[]     = { 0, 20, 200, 255, 255 }; // Define the led intensity, 255 we will blink
const int LED_BLINKING_RATES[]        = { 100, 400 }; 

const int   _blinking1LevelIndex      = 3;
const int   _blinking2LevelIndex      = 4;

Led              _onBoardLed(LED_PIN); // The led representing the User Interface

MultiStateButton _5StatesButton(SWITCH_PIN, &_onBoardLed, ArraySize(LED_LIGTH_STEP_VALUES), &LED_LIGTH_STEP_VALUES[0]);

void setup() {

    Board.SetPinMode(SWITCH_PIN,            INPUT);
    Board.SetPinMode(SWITCH_PIN_PREVIOUS,   INPUT);
    Board.SetPinMode(LED_PIN,               OUTPUT);
}

void CheckToActivateBlinkingMode() {

    if ((_5StatesButton.StateIndex == _blinking1LevelIndex) || (_5StatesButton.StateIndex == _blinking2LevelIndex)) {

        _5StatesButton.LedInstance->SetBlinkMode(LED_BLINKING_RATES[_5StatesButton.StateIndex - 3]);
    }
    else {
        if (_5StatesButton.LedInstance->IsBlinking()) {

            _5StatesButton.LedInstance->SetBlinkModeOff();
        }
    }
}

void loop() {

    boolean buttonPressed = _5StatesButton.GetButtonStateDebounced();

    if (buttonPressed == true && _5StatesButton._buttonLastStateInLoop == false) {

        _5StatesButton.NextState();
        CheckToActivateBlinkingMode();
    }
    _5StatesButton._buttonLastStateInLoop = buttonPressed;
     // Update the led associated with the MultiStateButton including managing the
     // blinking without using delay()
    _5StatesButton.UpdateUI(); 
}




No comments:

Post a Comment