Optimizing code for treasure box

I have created code for a treasure chest which randomly changes LED colors, creates a periodic twinkle across the LEDs, and plays a random mp3 track from a folder of mp3 tracks. This code must operate with a switch, that plays back these effects when the switch is high and shuts them off when the switch is low. From earlier versions of my code, I have optimized the code to enable a random track to be played. The base random play function of the dfPlayer does not play a random track, always beginning with track 1 and then randomizes tracks when playing the next track. It was more desirable to have the treasure chest play a random track when initially opened.

Early in my development, before random track playback, the code ran quickly such that the change from low to high and high to low resulted in a closer to instantaneous effect. When you opened the treasure box, the lights were on and twinkling before you could actually see the lights as example.

The time it takes to lift the lid to an open position where you could see the lights is about 250 milliseconds. My current code is running at approximately 750 - 1250 milliseconds before the LEDs are lit, hence the lid can be fully open when the lights turn on.

As I am fairly new to this, I would appreciate guidance on how I might optimize the code or change my coding approach to accomplish the desired effects in a faster time-frame. I have left the print lines and the comments within the code for my development reminders and testing. I have tried removing these to see if the speed improves, but do not see any substantial improvement. I do plan to remove these when my code is final.

#include <Adafruit_NeoPixel.h>

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN 13  // change to 7 for beta chest
 
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 24

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

//DF Player configuration
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(10, 9); // RX, TX - change to 10, 9 for beta chest, 11, 10 for v1 pcb
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

//Global variables
long n;
long timing;
long mix;
long count = 0;
long track;
uint32_t set;
int i;
long twinkle;
int inputPin = 2;
int buttonState;
int pauseState = 0;
int lastState = LOW;  // the previous state from the input pin
int val;     // the current reading from the input pin

void setup() {
  // put your setup code here, to run once:
  
  pinMode(inputPin, INPUT);
  digitalWrite(inputPin, HIGH);

  Serial.begin(115200);  //debug using serial monitor
  randomSeed(analogRead(A0)); //necessary to get randomization
  mySoftwareSerial.begin(9600);

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
  
  buttonState = digitalRead(inputPin); // store initial button state (should be high)
  Serial.print("Initial button state is ");
  Serial.println(buttonState);

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  
  Serial.println(F("DFPlayer Mini online."));
  myDFPlayer.setTimeOut(500); //Set serial communictaion time out 500ms
     
  val = digitalRead(inputPin);

  if (val==LOW) {
    Serial.println("Button - Low");
    
    LEDoff();
  }
  
  else {
    Serial.println("Button - High");

    LEDon();
  }      
    
  myDFPlayer.volume(25);  //Set volume value. From 0 to 30
}

void loop() {
  // put your main code here, to run repeatedly:
  val = digitalRead(inputPin);
  
  if (val == LOW) {
    Serial.println("Button - Low");
    
    Serial.print("Pause State: ");
    Serial.println(pauseState);
    
    LEDoff();
      
    myDFPlayer.stop();
    pauseState = 0;
  }
  
  else {
    Serial.println("Button - high");

    Serial.print("Pause State: ");
    Serial.println(pauseState);
    
    //DF Player serial monitor activity
    if (myDFPlayer.available()) {
      printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      
      //DF Player to play random track if no track is playing
      if (myDFPlayer.readType()==DFPlayerPlayFinished) {
        Serial.println("Song ended, selecting new song.");
        randomTrack();
      }
    }
    
    if (pauseState == 0) {

      LEDon();
      randomTrack();
      pauseState=1;
    }
    
    //Twinkle white
    timing=random(300, 1200); //generate random timing between twinkles
    delay (timing); //wait between twinkles
    n=random(0,LED_COUNT-1); //generate a random pixel number
    uint32_t color=strip.getPixelColor(n); //store random pixel current color data

    Serial.print("LED number ");
    Serial.print(n);
    Serial.print(" is currently set to this color: ");
    Serial.println(color, HEX); //debugging serial monitor
    strip.setPixelColor(n, 255, 255, 255, 0);  //change the random pixel color data to white, adjust brightness to desired
    strip.show(); //display pixel color
    twinkle=random(40,120);
    delay (twinkle); //pause before returning to original pixel color
    strip.setPixelColor(n, color); //change the random pixel back to its original color
    strip.show(); //display pixel color
  }  
  buttonState = val;
  
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

void LEDon () {
  //Turns LEDs on to a random color
    strip.begin();
    strip.setBrightness(255); //Overall Brightness must be kept at 255 for reading the color of LED
    
    //set brightness by adjusting the color pallet
    //Brightness of the colors can be set using the following scale: 100% is 255, 80% is 204, 60% is 153, 40% is 102, 20% is 51
    //defines the desired color pallet
    uint32_t red=strip.Color(153, 0, 0, 0); //HEX 990000
    uint32_t green=strip.Color(0, 153, 0, 0); //HEX 009900
    uint32_t blue=strip.Color(0, 0, 153, 0); //HEX 000099
    uint32_t purple=strip.Color(75, 0, 153, 0); //HEX 4b0099
    uint32_t yellow=strip.Color(153, 153, 0, 0); //HEX 999900
    uint32_t cyan=strip.Color(0, 153, 153, 0); //HEX 009999
    uint32_t lime=strip.Color(66, 153, 0, 0); //HEX 994200
    uint32_t orange=strip.Color(153, 48, 0, 0); //HEX 993000
    uint32_t magenta=strip.Color(153, 0, 153, 0); //HEX 999999
    uint32_t myArray[9]={red, green, blue, purple, yellow, cyan, lime, orange, magenta};

    for (i=0; i <= LED_COUNT-1; i++) {
    mix=random(0,8);  //Generate random number in a range ewual to the number of pallet colors
    set=myArray[mix];
  
    strip.setPixelColor(i, set); //set each pixel to a random color from color pallet
  
    uint32_t color=strip.getPixelColor(i); //store random pixel current color data
  
    Serial.print("Set LED ");
    Serial.print(i);  //debugging check
    Serial.print(" to color: ");
    Serial.println(set, HEX); //debugging serial monitor
    Serial.print("LED number ");
    Serial.print(i);
    Serial.print(" read color: ");
    Serial.println(color, HEX);
  }
}

void LEDoff ()  {
  for (i=0; i <= LED_COUNT-1; i++) {   
    strip.setPixelColor(i, 000000); //set each pixel to a random color from color pallet
  }
        
  strip.show();  //LEDs all black
}

void randomTrack () {
  
  Serial.print("Count: ");
  Serial.println(count);
  if (count == 0)  {
    count = myDFPlayer.readFileCounts(); //Count the number of tracks on the SD card
    Serial.print("Number of tracks on SD card: ");
    Serial.println(count);
    count = count +1;
  }
  
  track = random(1, count);
  myDFPlayer.play(track);  //Play the random mp3
  Serial.print("Playing Track: ");
  Serial.println(track);
}

If you bypass this, does the code run fast again?

I would separate the LED code and the dfplayer code into their own functions and call the LED function first when the box is opened.
Also get rid of the delays by implementing a millis() timer.

Non-blocking timing using millis() tutorials:
Blink without delay().
Beginner's guide to millis().
Several things at a time.

1 Like
#include <Adafruit_NeoPixel.h>

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN 13  // change to 7 for beta chest

// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 24

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

//DF Player configuration
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(10, 9); // RX, TX - change to 10, 9 for beta chest, 11, 10 for v1 pcb
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

//Global variables
//long mix = 0;
//long count = 0;
long track = 0;
//uint32_t set = 0;
const byte inputPin = 2;
bool buttonState = false;
bool pauseState = false;
//bool lastState = false;  // the previous state from the input pin

void setup() {
  pinMode(inputPin, INPUT_PULLUP);
  Serial.begin(115200);  //debug using serial monitor
  randomSeed(analogRead(A0)); //necessary to get randomization
  mySoftwareSerial.begin(9600);

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while (true);
  }

  Serial.println(F("DFPlayer Mini online."));
  myDFPlayer.setTimeOut(500); //Set serial communictaion time out 500ms
  if (digitalRead(inputPin) == LOW) LEDoff();
  else LEDon();
  myDFPlayer.volume(25);  //Set volume value. From 0 to 30
  strip.begin();
  strip.setBrightness(255); //Overall Brightness must be kept at 255 for reading the color of LED
}

void loop() {
  buttonState = digitalRead(inputPin) == LOW;
  Serial.print("Pause State: ");
  Serial.println(pauseState);
  if (buttonState ) {
    Serial.println("Button - Low");
    LEDoff();
    myDFPlayer.stop();
    pauseState = 0;
  }
  else {
    Serial.println("Button - high");
    if (myDFPlayer.available()) {
      printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      if (myDFPlayer.readType() == DFPlayerPlayFinished) { //DF Player to play random track if no track is playing
        Serial.println("Song ended, selecting new song.");
        randomTrack();
      }
    }

    if (!pauseState ) {
      LEDon();
      randomTrack();
      pauseState = true;
    }

    //Twinkle white
    delay (random(300, 600)); //wait between twinkles  //generate random timing between twinkles
    num = random(0, LED_COUNT ); //generate a random pixel number
    uint32_t color = strip.getPixelColor(num); //store random pixel current color data
    Serial.print("LED number ");
    Serial.print(num);
    Serial.print(" is currently set to this color: ");
    Serial.println(color, HEX); //debugging serial monitor
    strip.setPixelColor(num , 255, 255, 255, 0);  //change the random pixel color data to white, adjust brightness to desired
    strip.show(); //display pixel color
    delay (random(40, 120)); //pause before returning to original pixel color
    strip.setPixelColor(num, color); //change the random pixel back to its original color
    strip.show(); //display pixel color
  }
}

void printDetail(uint8_t type, int value) {
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

void LEDon () {
  //Turns LEDs on to a random color
  uint32_t red = strip.Color(153, 0, 0, 0); //HEX 990000
  uint32_t green = strip.Color(0, 153, 0, 0); //HEX 009900
  uint32_t blue = strip.Color(0, 0, 153, 0); //HEX 000099
  uint32_t purple = strip.Color(75, 0, 153, 0); //HEX 4b0099
  uint32_t yellow = strip.Color(153, 153, 0, 0); //HEX 999900
  uint32_t cyan = strip.Color(0, 153, 153, 0); //HEX 009999
  uint32_t lime = strip.Color(66, 153, 0, 0); //HEX 994200
  uint32_t orange = strip.Color(153, 48, 0, 0); //HEX 993000
  uint32_t magenta = strip.Color(153, 0, 153, 0); //HEX 999999
  uint32_t myArray[9] = {red, green, blue, purple, yellow, cyan, lime, orange, magenta};

  for (byte i = 0; i < LED_COUNT; i++) {
    set = myArray[random(0, 9)];
    strip.setPixelColor(i, set); //set each pixel to a random color from color pallet
  }
}

void LEDoff ()  {
  strip.clear();
  strip.show();  //LEDs all black
}

void randomTrack () {
  if (count == 0)count = myDFPlayer.readFileCounts(); //Count the number of tracks on the SD card
  track = random(0, count) + 1;
  myDFPlayer.play(track);  //Play the random mp3
}

Thank you all for your suggestions. As this is a new concept for me, it was very helpful to be pointed in the right direction on use of millis() in place of delay. It took me a little bit to have the millis() timer working for both the LED change to bright white and then back to the original color, but through some state tracking I was able to achieve near instant on/off functionality with twinkling and randomization of LED color and MP3 playback. The only outstanding bug - if I plug in the circuit using an external power supply while the switch state is HIGH, no MP3 track will play. Plugging in while switch state is LOW works perfectly. If I call my randomTrack function in void Setup during the HIGH condition, I lose all randomization of the MP3 tracks (just plays the first track over and over). I think I can live with the bug as it is unlikely to occur and quickly remedied by closing the switch and opening the switch a second time. Thank you Hutkikz and groundFungus for pointing me in the correct direction. Here is my cleaned up code.

//Arduino Libraries
#include "Arduino.h"
#include "SoftwareSerial.h" // Used for Serial communication with DFPlayer Mini
#include <Adafruit_NeoPixel.h> // Used for WS2812 LED light strip control
#include "DFRobotDFPlayerMini.h"  // Used for DFPlayer Mini control

// LED light strip configuration
// Which pin on the Arduino is connected to the NeoPixels?
#define LED_PIN 13  // change to 7 for beta chest
 
// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 24

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

// DFPlayer Mini Serial Communication Pin, Device, and Command Configuration
SoftwareSerial mySoftwareSerial(10, 9); // (RX, TX) - change to (10, 9) for alpha chest, (11, 10) for pcb v1
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

// Global variables
// Variables associated to the LED light control
int i;  // Variable for counting in For Loops
int wait = 0;  // Variable for tracking twinkle state
long ranPix;  // Variable for storing a randomly select LED in the LED strip
long prevPix;  // Variable for storing the previous randomly selected LED in the LED strip
long timing;  // Variable for storing a randomly generated time between each LED twinkle
long twinkle;  // Variable for storing a randomly generate time for the twinkle duration (how long an LED is bright white)
long mix;  // Variable for storing a random number from the range of available pallet colors
uint32_t color;  // Variable for storing the hexidecimal color code used to set the color of an LED
uint32_t prevcolor;  // Variable for storing the hexidecimal color code used to set the color of an LED
unsigned long previousMillis = 0;  // Store the last time LED was updated, initialize duration as 0 milliseconds
unsigned long currentMillis;  // Variable to count the current milliseconds

// Variables associated to the DFPlayer Mini control 
long count = 0;       // Variable for storing the total number of files on the microSD card inserted into the DFPlayer Mini
long track;           // Variable for storing a random track number
int pauseState = 0;   // Variable for monitoring DFPlayer Mini MP3 audio playback state, initially paused

// Variables associated to the treasure chest switch
int inputPin = 2;     // Arduino input pin for the treasure chest switch
int val;              // Variable for storing the current switch state of the the inputPin

void setup() {
  // put your setup code here, to run once:

  //  Initialize and configure the treasure chest switch
  pinMode(inputPin, INPUT);
  digitalWrite(inputPin, HIGH);

  //  Initialize serial communication and serial debug monitor baud rates
  Serial.begin(115200);  //  Serial com baud rate
  randomSeed(analogRead(A0));  // Reads noise of open pin to improve randomization
  mySoftwareSerial.begin(9600);  // Serial monitor baud rate

  Serial.println(F("Starting the Pieces of Eight Treasure Chest"));
  Serial.println();
  Serial.println(F("Initializing DFPlayer Mini ... (May take 3~5 seconds)"));
  
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Check serial communication with DFPlayer Mini
    Serial.println(F("Unable to begin:"));  
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  
  Serial.println(F("DFPlayer Mini online."));  //Serial communication with DFPlayer Mini estabilished
  
  myDFPlayer.setTimeOut(500);  //Set serial communictaion time out 500ms


  //  Switch State 
  val = digitalRead(inputPin);  // Read initial switch state (HIGH/LOW)
  
  Serial.println();
  Serial.print("Initial switch state is ");  // Print initial switch state to the serial monitor
  Serial.println(val);

  if (val==LOW) {  // Switch state is LOW, treasure chest lid is closed
    LEDoff();  // Run function to turn LED lights off
  }
  
  else {  // Switch state is HIGH, treasure chest lid is open
    LEDon();  // Run function to turn LED lights on with a random color pattern
    timing=random(100, 500);  // Generates a random time in milliseconds
  }      
}

void loop() {
  // put your main code here, to run repeatedly:
  val = digitalRead(inputPin);  // Read current switch state

  currentMillis = millis();
  
  if (val == LOW) {  // Switch state is LOW, treasure chest lid is closed
    LEDoff();  // Run function to turn LED lights off 
    myDFPlayer.stop();  // Stop MP3 audio playback on DFPlayer Mini
    pauseState = 0;  // Set DFPlayer Mini MP3 audio playback state to paused
  }
  
  else {  // Switch state is HIGH, treasure chest lid is open
   
    // Check DFPlayer Mini serial monitor for activity
    if (myDFPlayer.available()) {
      printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
      
      //DFPlayer Mini serial activity indicates the track is finished, play a random track
      if (myDFPlayer.readType()==DFPlayerPlayFinished) {
        Serial.println ();
        Serial.println("Song ended, selecting new song.");
        randomTrack();  // Run function to play a random MP3 track located within the MP3 file folder
      }
    }

    //Check the DFPlayer Mini MP3 audio playback state, if the last state was paused - turn LED lights on and play a random track 
    if (pauseState == 0) {

      LEDon();  // Run function to turn LED lights on with a random color pattern
      randomTrack();  // Run function to play a random MP3 track located within the MP3 file folder
      pauseState=1;  // Set DFPlayer Mini MP3 audio playback state to playing
    }

    LEDtwinkle ();  // Run function to randomly turn an LED bright white and then back to it's original color state
  }
  
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

void LEDon () {
  //Turns LEDs on to a random color pattern
  strip.begin();  // Initialize communication with LED strip
  strip.setBrightness(255); // Set the overall LED strip brightness to full, necessary for reading the strip color
  
  //Declare the color pallet to be used in RGB code (red, green, blue, white) and convert to Hexidecimal code
  //Brightness of the colors can be set using the following scale: 100% is 255, 80% is 204, 60% is 153, 40% is 102, 20% is 51
  uint32_t red=strip.Color(153, 0, 0, 0); //HEX code equivelant 990000
  uint32_t green=strip.Color(0, 153, 0, 0); //HEX code equivelant 009900
  uint32_t blue=strip.Color(0, 0, 153, 0); //HEX code equivelant 000099
  uint32_t purple=strip.Color(75, 0, 153, 0); //HEX code equivelant 4b0099
  uint32_t yellow=strip.Color(153, 153, 0, 0); //HEX code equivelant 999900
  uint32_t cyan=strip.Color(0, 153, 153, 0); //HEX code equivelant 009999
  uint32_t lime=strip.Color(66, 153, 0, 0); //HEX code equivelant 994200
  uint32_t orange=strip.Color(153, 48, 0, 0); //HEX code equivelant 993000
  uint32_t magenta=strip.Color(153, 0, 153, 0); //HEX code equivelant 999999
  uint32_t myArray[9]={red, green, blue, purple, yellow, cyan, lime, orange, magenta};  // Creates an array for looking up color code

  for (i=0; i <= LED_COUNT-1; i++) {  // Cycles thru loop until all LED lights have been configured
    mix=random(0,8);  // Generates a random number based on the range of available pallet colors, (0, total number in array - 1) 
    color=myArray[mix];  // Set the color variable value to the color hex code of the random number using an array to look up the color code
  
    strip.setPixelColor(i, color); // Sets LED to a random color from the color pallet

    // Below print commands can be added back for debugging.
      //Serial.println ();
      //Serial.print("LED number ");
      //Serial.print(i);  //debugging check
      //Serial.print(" is SET to color: ");
      //Serial.println(color, HEX); //debugging serial monitor
      //uint32_t color=strip.getPixelColor(i); //Reads LED color data
      //Serial.println ();
      //Serial.print("LED number ");
      //Serial.print(i);
      //Serial.print(" color is read to be: ");
      //Serial.println(color, HEX);
  }

  strip.show();  // Displays LED settings, all LEDs should be a color from the color pallet
}

void LEDoff ()  {
  strip.clear();      
  strip.show();  // Displays LED settings, all LEDs should be black
}

void LEDtwinkle ()  {
  //Randomly selects an LED to turn bright white for a short period of time and then back to it's original color

  if (currentMillis - previousMillis >= timing) {
    // save the last time you blinked the LED
    if (wait == 0) {
    
      ranPix=random(0,LED_COUNT-1);  // Sets a random number within the total number of LEDs in the strip
      
      uint32_t color=strip.getPixelColor(ranPix); // Stores the LEDs current color hex code (original color)
      strip.setPixelColor(ranPix, 255, 255, 255, 0);  // Changes the random LED color data to bright white
      strip.show();  // Displays LED settings, an LED should become bright white

      previousMillis = currentMillis;
      
      prevPix = ranPix;  // Store randomly selected LED for changing color back to the original color
      prevcolor = color;  // Store the color code of the randomly selected LED for changing color back to the original color
      
      twinkle=random(15,80);  // Generates a random time in milliseconds, the duration an LED is bright white
      wait = 1;  // Set variable to wait for twinkle to complete
    }
  }

  if ((currentMillis - previousMillis) >= (timing + twinkle)) {
    
    if (wait == 1) {
      // save the last time you blinked the LED
      strip.setPixelColor(prevPix, prevcolor);  // Changes the LED back to its original color
      strip.show();  // Displays LED settings, an LED should turn from bright white to it's original color

      timing=random(100, 500);  // Generates a random time in milliseconds
      
      wait = 0;  // Set variable to start a new twinkle
    }
  }
}

void randomTrack () {
  // Play a random MP3 track from the microSD card inserted into the DFPlayer Mini
  if (count == 0)  {
    count = myDFPlayer.readFileCounts(); //Count the number of files on the microSD card
    Serial.println ();
    Serial.print("Number of tracks on SD card: ");
    Serial.println(count);
  }
  
  track = random(1, count+1);  // Generate a random number from the total number of files on the microSD card
  myDFPlayer.play(track);  //Play the random MP3 file
  Serial.println ();
  Serial.print("Now Playing Track: ");
  Serial.println(track);
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.