Juego de Luces para Bicicleta

Hola a todos :raising_hand_man:

Tengo un año de que realice un juego de luces para mi bicicleta
Como material principal utilice lo siguiente:

1 Atmega 328UP
1 Anillo Neopixel con 16 leds WS2812B
3 Leds WS2812B
1 Módulo Ttp223, Interruptor Táctil Capacitivo.
Bateria POWER BANK 5V~1A
1 Switch (Solo para desactivar la fuente de alimentación)

Este proyecto me a funcionado de maravilla y le he echo varias mejoras.
El codigo que utilizo cuenta con 4 modos utilizando una maquina de estados (case switch).

Ahora lo que pretendo es agregar a este proyecto es un acelerómetro GY-521 MPU6050 (bueno es que tengo a la mano :sweat_smile:)
El propósito de agregar este sensor es que para cuando yo me detenga se active el case 1 que lo tengo configurado como MODO STOP como verán en las siguientes lineas:

case 1:
Mode0(); //MODE STOP (RED SPEED LOW)
fade(0,0, 0,0,    0,0,   500); //4 RED DELAY PAUSE
fade(0,200, 0,0,    0,0,   1000); //4 RED PULSE STOP
pixels.setPixelColor(0, pixels.Color(255, 0, 0)); //RED
pixels.show();
break;

Y cuando avance de nuevo en mi bicicleta salga de este modo y se active de nuevo el case que ya tenia seleccionado (ya sea el Mode 1o Mode 2 segun el que aya seleccionado con el switch capacitivo).

El código lo tengo organizado por pestañas así que verán cada parte por separado

Les agradeceré que me puedan ayudar sobre que agregar o quitar al código.

Saludos.

BikeLightsV3.0_Acelerometro.ino (8.0 KB)
00_Mode_STOP.ino (67 Bytes)
02_Mode1.ino (2.6 KB)
03_Mode2.ino (299 Bytes)
11_LEDS_OFF.ino (95 Bytes)
BikeLightsV3.0_Acelerometro.zip (4.6 KB)

Aqui tambien les comparto el código completo que utilice aquí se los comparto en etiquetas

//Main Control Code//
//CODIGO CARGADO EN ATMEGA328PU
//Pines usados para programación
//PIN 1 = RESET (DTR)
//PIN 2 = RX
//PIN 3 = TX
//+5V y GND

#include <avr/sleep.h>         // library for sleep modes
#include <avr/power.h>         // library for power management
#include <avr/wdt.h>           // disable/enable WDT
#include <avr/interrupt.h>     // library for interrupts
#include <Adafruit_NeoPixel.h>

#include "FastLED.h"
#define NUM_LEDS 16 //TOTAL DE LEDS CONECTADOS
#define DATA_PIN 9  //D9 o (PIN 15)
#define BRILLO 150  //BRILLO 0 min ~ max 255 Brillo recomendado 100-150 para no deslumbrar y ahorrar bateria
CRGBArray<NUM_LEDS> leds;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);

#include "FastLED.h"
#define LED_PIXEL 1  // # of LEDS in the strip
CRGB PIXEL[LED_PIXEL];
#define DATA 8 // Output Pin to Data Line on Strip (PIN 14) LED STYBY
int fadeAmount = 5;  // Set the amount to fade I usually do 5, 10, 15, 20, 25 etc even up to 255.
int brightness = 0;

////////////////////////////////////////////////////////////////////////////////////// CODIGO LED MODE
#define PIN1  8 //Conectar pin DIN de led WS2812B (PIN 5)
#define NUMPIXELS 1 //Cantidad de leds ws2812b conectados
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN1, NEO_GRB + NEO_KHZ800); 
////////////////////////////////////////////////////////////////////////////////////// CODIGO LED MODE


unsigned long period=80;
unsigned long currentMillis=0;
unsigned long startMillis=0;
boolean ledOn=false;

unsigned long idleMillis;            // Measure idle time between button presses
unsigned long patternInterval = 5 ;  // time between steps in the pattern
unsigned long lastUpdate = 0;        // for millis() when last update occurred
unsigned long showSpeed [] = { 5, 30, 30, 30, 30} ; // speed for each pattern - add here when adding more cases 
int fadeStep = 0;                    // state variable for fade function
const byte BUTTON_PIN = 2; //D2 PIN4  Pin para Push Botton o TouchPAD capacitivo

void LEDS_OFF();
void Mode0(); //MODE STOP (RED SPEED LOW)
void Mode1(); //MODE RED STROBE FAST
void Mode2(); //MODE WHITE STROBE 

unsigned long currentMillis1 = 0;
                           
// Function to put Digispark to sleep
void sleep() 
{        
set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // Call for deepest sleep mode
ADCSRA = 0;                             // ADC off
power_all_disable();                    // Power off ADC, Timer 0 and 1, serial interface. avr/power.h
sleep_enable();                         // Sets the Sleep Enable (SE) bit in the MCUCR Register (SE BIT)
wdt_disable();                          // Disable watchdog timer to conserve power
sleep_bod_disable();                    // Disable brown out detection to conserve power. Auto-enables on wake
sei();                                  // Enable interrupts
sleep_cpu();                            // Sleep
// ISR starts here when button pressed
sleep_disable();                        // Clear SE bit
cli();                                  // Disable interrupts
//PCMSK &= ~_BV(PCINT2);                  // Turn off PB2 as interrupt pin
sei();                                  // Enable interrupts
power_all_enable();                     // Power everything on. avr/power.h
ADCSRA = 0;                             // Disable ADC because I don't need it
}
EMPTY_INTERRUPT(PCINT0_vect);           // Alternate use of ISR(PCINT0_vect){} since 
                                        // no action needed in the interrupt
void setup() 
{
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  digitalWrite(BUTTON_PIN, LOW);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); //NEOPIXELES PRINCIPALES
  FastLED.setBrightness(BRILLO);
  //FastLED.setBrightness(MAX_BRIGHTNESS); //Ajuste de brillo con potenciometro
  strip.setBrightness(150);  // Ajuste de Brillo Mode5 y Mode8 De 100~150 Default 120

  FastLED.addLeds<NEOPIXEL, DATA>(PIXEL, LED_PIXEL); //LED StyBy

  // CODIGO PARA LED MODE
  pixels.begin();  // This initializes the NeoPixel library.
  pixels.setBrightness(20); //Ajuste de brillo de LED Neopixel   0 = MIN   255 = MAX
  wipe();
  pixels.show();
  // CODIGO PARA LED MODE

}

void loop() 
{
currentMillis=millis();
  
// Start with case 0
static byte showType = 0; //En cual case desea iniciar? //Default 0
static bool oldState; 
// Get current button state
bool newState = digitalRead(BUTTON_PIN); 
// Check if state changed from high to low (button press)
if (newState == HIGH && oldState == LOW)    ///newState=LOW  oldState= HIGH //Default

{
showType++; // Move to next showType
fadeStep = 0;              // Reset fade state variable
idleMillis = millis(); // Reset idle timer
if (showType > 3) //Candtidad de case en el codigo?
{
showType = 0; // Reset showType to case 0
}
patternInterval = showSpeed[showType]; // Set speed for this pattern
wipe();     // Clear out pixel buffer
delay(100); //Tiempo para cambio de case //Default 5
}
oldState = newState; // Update state
if (millis() - lastUpdate > patternInterval)
{
startShow(showType);
}
}

void startShow(int showPattern) 
{
switch(showPattern) 
{
//LEDS OFF/STYBY
case 0: fade(0,0,0,0,0,0,0);
LEDS_OFF();
///MODE STYBY
   for(int i = 0; i < LED_PIXEL; i++ )
   {
   //PIXEL[i].setRGB(255,0,50); //RED DARK //Color RGB
   PIXEL[0]=CHSV(247,255,150);  //RED DARK //Color HSV
   PIXEL[0].fadeLightBy(brightness);
  }
  FastLED.show();
  brightness = brightness + fadeAmount;
  if(brightness == 0 || brightness == 255)
  {
    fadeAmount = -fadeAmount ;
  }  
  delay(15);  // This delay sets speed of the fade. I usually do from 5-75 but you can always go higher.
///MODE STYBY
break;

//////////////////////////MODE0 COLOR RED 
case 1:
Mode0(); //MODE STOP (RED SPEED LOW)

                       //SPEED [Aumentar el valor disminuye la velocidad]
fade(0,0, 0,0,    0,0,   500); //4 RED DELAY PAUSE
fade(0,200, 0,0,    0,0,   1000); //4 RED PULSE STOP
pixels.setPixelColor(0, pixels.Color(255, 0, 0)); //RED
pixels.show();
break;

////////////////////////MODE1 COLOR LIME
case 2:
Mode1();
pixels.setPixelColor(0, pixels.Color(100, 255, 0)); //LIME
pixels.show();
break;

////////////////////////MODE2 COLOR PINK
case 3:
Mode2();
pixels.setPixelColor(0, pixels.Color(230, 0, 100)); //PINK
pixels.show();
break;
}
}

// clear all LEDs
void wipe()
{
for(byte i=0;i<strip.numPixels();i++)
{
strip.setPixelColor(i, strip.Color(0,0,0));
strip.show();
}
}

void fade(byte redStartValue, byte redEndValue, byte greenStartValue, byte greenEndValue, byte blueStartValue, byte blueEndValue, int totalSteps)
{
static float redIncrement, greenIncrement, blueIncrement;
static float red, green, blue;
static bool fadeUp = false;

if (fadeStep == 0) // first step is to initialise the initial colour and increments
{
red = redStartValue;
green = greenStartValue;
blue = blueStartValue;
fadeUp = false;

redIncrement = (float)(redEndValue - redStartValue) / (float)totalSteps;
greenIncrement = (float)(greenEndValue - greenStartValue) / (float)totalSteps;
blueIncrement = (float)(blueEndValue - blueStartValue) / (float)totalSteps;
fadeStep = 1; // next time the function is called start the fade
}
else  // all other steps make a new colour and display it
{
// make new colour
red += redIncrement;
green +=  greenIncrement;
blue += blueIncrement;

// set up the pixel buffer
for (byte i = 0; i < strip.numPixels(); i++)
{
strip.setPixelColor(i, strip.Color((byte)red,(byte)green,(byte)blue));
}

// now display it
//strip.setBrightness(80);  // Ajuste de Brillo
strip.show();

// go on to next step
fadeStep += 1;

// finished fade
if(fadeStep >= totalSteps)
{
if(fadeUp) // finished fade up and back
{
fadeStep = 0;
return; // so next call recalabrates the increments
}

// now fade back
fadeUp = true;
redIncrement = -redIncrement;
greenIncrement = -greenIncrement;
blueIncrement = -blueIncrement;
fadeStep = 1; // don't calculate the increments again but start at first change
} 
}
}
//Mode0 STOP (RED SPEED LOW)
void Mode0() { //LED STATE RED
  }
//Mode1 RED STROBE
void Mode1() { //LED STATE LIME

  BlinkOuter(strip.Color(255, 0, 0), 40); //Red faster
  BlinkOuter(strip.Color(255, 0, 0), 40); //Red faster
  BlinkOuter(strip.Color(255, 0, 0), 40); //Red faster 
  BlinkOuter(strip.Color(0, 0, 0), 1000); //LED OFF DELAY

  ClearLights();
}
void ClearLights() {
  for (int i = 0; i < strip.numPixels(); i = i + 1) {
    strip.setPixelColor(i, 0);    //turn every pixel off
  }
  strip.show();
} 
void BlinkOuter(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    strip.setPixelColor(strip.numPixels() - 1, 0);
    strip.setPixelColor(strip.numPixels() - 2, 0);
    strip.setPixelColor(strip.numPixels() - 3, 0);
    strip.setPixelColor(strip.numPixels() - 4, 0);
    strip.setPixelColor(strip.numPixels() - 5, 0);
    strip.setPixelColor(strip.numPixels() - 6, 0);
    strip.setPixelColor(strip.numPixels() - 7, 0);
    strip.setPixelColor(strip.numPixels() - 8, 0);
    strip.setPixelColor(strip.numPixels() - 9, 0);
    strip.setPixelColor(strip.numPixels() - 10, 0);
    strip.setPixelColor(strip.numPixels() - 11, 0);
    strip.setPixelColor(strip.numPixels() - 12, 0);
    strip.setPixelColor(strip.numPixels() - 13, 0);
    strip.setPixelColor(strip.numPixels() - 14, 0);
    strip.setPixelColor(strip.numPixels() - 15, 0);
    strip.setPixelColor(strip.numPixels() - 16, 0);
    strip.setPixelColor(strip.numPixels() - 17, 0);
    strip.setPixelColor(strip.numPixels() - 18, 0); 
    strip.setPixelColor(18, 18);
    strip.show();
    delay(wait);
    strip.setPixelColor(strip.numPixels() - 1, c);
    strip.setPixelColor(strip.numPixels() - 2, c);
    strip.setPixelColor(strip.numPixels() - 3, c);
    strip.setPixelColor(strip.numPixels() - 4, c);
    strip.setPixelColor(strip.numPixels() - 5, c);
    strip.setPixelColor(strip.numPixels() - 6, c);
    strip.setPixelColor(strip.numPixels() - 7, c);
    strip.setPixelColor(strip.numPixels() - 8, c);
    strip.setPixelColor(strip.numPixels() - 9, c);
    strip.setPixelColor(strip.numPixels() - 10, c);
    strip.setPixelColor(strip.numPixels() - 11, c);
    strip.setPixelColor(strip.numPixels() - 12, c);
    strip.setPixelColor(strip.numPixels() - 13, c);
    strip.setPixelColor(strip.numPixels() - 14, c);
    strip.setPixelColor(strip.numPixels() - 15, c);
    strip.setPixelColor(strip.numPixels() - 16, c);
    strip.setPixelColor(strip.numPixels() - 17, c);
    strip.setPixelColor(strip.numPixels() - 18, c);
    strip.setPixelColor(18, 18);
    strip.show();
    delay(wait);
  }
}
//Mode2 WHITE STROBE
void Mode2() { //LED STATE PINK
  if(currentMillis-startMillis>=period){
    startMillis=currentMillis;
    ledOn=!ledOn;
    if(ledOn){
    leds(0,17) = CHSV(0,0,0);  // WHITE OFF
    }else{
    leds(0,17) = CHSV(0,0,180);  //WHITE
    }
    FastLED.show();
  }
}
void LEDS_OFF() { //MODE STYBY (LED STATE RED DARK)
  FastLED.clear();
  FastLED.show();
}