Jordy Moors
Published © CC BY-SA

Death Star Word Clock

A word clock resembling the Death Star. Edgelit acrylic and an RGB matrix provide for neat light effects. Good looking AND useful!

IntermediateFull instructions provided10 hours5,302

Things used in this project

Hardware components

Photon
Particle Photon
×1
DFRobot DFMini player MP3
×1
Adafruit neopixel
×1
Adafruit 32x32 RGB LED matrix 6mm pitch
×1
RGB matrix shield
×1

Software apps and online services

Particle.io

Hand tools and fabrication machines

Laser cutter (generic)
Laser cutter (generic)
Soldering iron (generic)
Soldering iron (generic)

Story

Read more

Custom parts and enclosures

Laser file for the front SVG

Load it up into a lasercutter, and hit "go". Most, if not all, lasercutter should be able to handle these formats.

Laser file for the back SVG

Load it up into a lasercutter, and hit "go". Most, if not all, lasercutter should be able to handle these formats.

Laser file for the front PLF

Format for VisiCut, might be useful to some.

Laser file for the back PLF

Format for VisiCut, might be useful to some.

Complete design in AutoCad (2D)

Load it up in AutoCad, and do whatever you like with it ;)

The Death Star

Laser it mirrored into 5mm acrylic, the same thickness as a neopixel.

Schematics

DFmini player hookup

A small MP3 module that allows you to easily play music from an SD card.

Neopixel hookup

How to hook up the neopixel. In actuality, this goes to the respective pin on the Matrix shield. Due to lack of a matching part, this should be sufficient.

Code

main.cpp

C/C++
It's the main code. Insert it into a new project in the web IDE and make sure you include the mentioned libraries through the library system. You'll have to add them manually, this won't happen automatically!
// This #include statement was automatically added by the Particle IDE.
#include "neopixel/neopixel.h"

// This #include statement was automatically added by the Particle IDE.
#include "snake.h"

// This #include statement was automatically added by the Particle IDE.
#include "SparkIntervalTimer/SparkIntervalTimer.h"

// This #include statement was automatically added by the Particle IDE.
#include "Adafruit_mfGFX/Adafruit_mfGFX.h"

// This #include statement was automatically added by the Particle IDE.
#include "RGBmatrixPanel/RGBmatrixPanel.h"

#include <math.h>



// =========================== Neopixel ===========================
#define PIXEL_COUNT 1
#define PIXEL_PIN A5
#define PIXEL_TYPE WS2812B
Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE);
// =========================== /Neopixel ==========================


// =========================== Snake code =========================
#include "snake.h"

void play_snake();

int length = 3;
bool update = true;
int Delay = 0;
unsigned long speed = game_speed;
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
// ========================== Snake code ==========================



// ========================== MATRIX ==============================
byte matrixBuffer [3] [16] [16]; // A 3 layer display buffer for the creation of various graphical effects

boolean intro = true;            // Indicates if mode has just been entered after mode change.

unsigned long FrameTime = 0;     // Keeps track of timeing between animation frames.
unsigned int  FrameRate = 0;     // Animation frame rate.
unsigned int frameCount = 0;     // Keeps counts of the number of frames since the begining of current transition.

byte field = 1;                 // Divides frames into fields to allow traces to move at different speeds

typedef struct                  // Traces are sprite like graphical elements that can be
{ // manipulated in a variety of ways.
  boolean active;               // Active or inactive.
  int regen;                    // Frame when the trace will regenerate.
  byte xPos;                    // X position
  byte yPos;                    // Y position
  byte speed;                   // Speed
  byte length;                  // Length
  byte terminate;               // Termination point, Should be at least 8 + Length
}  trace;
trace streamerTrace[16];        // 16 traces in struct array for streamer animations
// ===========================/MATRIX=================================




// Mode 0 = "Its MM minute(s) past/to HH"
// mode 1 = "Its HH oh 0M"
int timeMode = 0;

// displayMode
// 0 = clock
// 1 = Snake
// 2 = Matrix animation
// 3 = Digital
int displayMode = 0;

int specialModeNumber = -1;

int r = 255;
int g = 0;
int b = 0;
int sr = 255;
int sg = 0;
int sb = 255;
char pubstring[64];

char topLine[64] = {};

int8_t timeZone = 1;

unsigned long previousDisplayMillis = 0;
unsigned long delayTime = 5000;

// // allow us to use itoa() in this scope
extern char* itoa(int a, char* buffer, unsigned char radix);
void doWord(const uint8_t *w);
void blackOut();
void displayHour();
void doTime();
void displayMinute();
void mayTheForce();
void useTheForce();
void doOrDoNot();
int setMode(String command);
void lightLetter(int X, int Y, int red, int green, int blue);


/** Define RGB matrix panel GPIO pins **/
#if defined (STM32F10X_MD)  //Core
#define CLK D6
#define OE  D7
#define LAT A4
#define A   A0
#define B   A1
#define C   A2
#define D   A3
#endif

#if defined (STM32F2XX) //Photon
#define CLK D6
#define OE  D7
#define LAT A4
#define A   A0
#define B   A1
#define C   A2
#define D   A3
#endif

/****************************************/

//#define X_MAX 31    // Matrix X max LED coordinate (for 2 displays placed next to each other)
//#define Y_MAX 31


/***** Create RGBmatrix Panel instance *****
  Last parameter = 'true' enables double-buffering, for flicker-free,
  buttery smooth animation.  Note that NOTHING WILL SHOW ON THE DISPLAY
  until the first call to swapBuffers().  This is normal. */
//RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, true);
RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, true);
/*******************************************/



//  ======================== Snake code ========================
mysnake* temp;
mysnake snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 4]; //create snake matrix
mysnake* snakehead; //pointer to head of the snake
food apple;
food* applepointer;

Serpent Snake(&matrix);
//  ======================= /Snake code ========================

// All the word positions/lengths
//x, y, length, height
static const uint8_t wordIts[8] = {0, 0, 3, 1};
static const uint8_t wordHalf[8] = {4, 0, 4, 1};
static const uint8_t wordTwenty[8] = {10, 0, 6, 1};
static const uint8_t wordFive[8] = {1, 1, 4, 1};
static const uint8_t wordTwo[8] = {5, 1, 3, 1};
static const uint8_t wordEight[8] = {8, 1, 5, 1};
static const uint8_t wordEighteen[8] = {8, 1, 8, 1};
static const uint8_t wordOne[8] = {0, 2, 3, 1};
static const uint8_t wordThirteen[8] = {4, 2, 8, 1};
static const uint8_t wordTen[8] = {12, 2, 3, 1};
static const uint8_t wordEleven[8] = {1, 3, 6, 1};
static const uint8_t wordThree[8] = {10, 3, 5, 1};
static const uint8_t wordA[8] = {0, 4, 1, 1};
static const uint8_t wordQuarter[8] = {2, 4, 7, 1};
static const uint8_t wordTwelve[8] = {10, 4, 6, 1};
static const uint8_t wordSix[8] = {1, 5, 3, 1};
static const uint8_t wordSixteen[8] = {1, 5, 7, 1};
static const uint8_t wordFour[8] = {8, 5, 4, 1};
static const uint8_t wordFourteen[8] = {8, 5, 8, 1};
static const uint8_t wordSeven[8] = {0, 6, 5, 1};
static const uint8_t wordSeventeen[8] = {0, 6, 9, 1};
static const uint8_t wordNine[8] = {8, 6, 4, 1};
static const uint8_t wordNineteen[8] = {8, 6, 8, 1};
static const uint8_t wordMinute[8] = {1, 7, 6, 1};
static const uint8_t wordMinutes[8] = {1, 7, 7, 1};
static const uint8_t wordPast[8] = {9, 7, 4, 1};
static const uint8_t wordTo[8] = {12, 7, 2, 1};
static const uint8_t wordO[8] = {13, 7, 1, 1};
static const uint8_t wordOh[8] = {13, 7, 2, 1};
static const uint8_t wordFifty2[8] = {2, 8, 5, 1};
static const uint8_t wordTwenty2[8] = {9, 8, 6, 1};
static const uint8_t wordTwelve2[8] = {2, 9, 6, 1};
static const uint8_t wordTen2[8] = {8, 9, 3, 1};
static const uint8_t wordForty2[8] = {11, 9, 5, 1};
static const uint8_t wordThirty2[8] = {1, 10, 6, 1};
static const uint8_t wordThirteen2[8] = {7, 10, 8, 1};
static const uint8_t wordFifteen2[8] = {0, 11, 7, 1};
static const uint8_t wordThree2[8] = {10, 11, 5, 1};
static const uint8_t wordEight2[8] = {0, 12, 5, 1};
static const uint8_t wordEighteen2[8] = {0, 12, 8, 1};
static const uint8_t wordSix2[8] = {8, 12, 3, 1};
static const uint8_t wordSixteen2[8] = {8, 12, 12, 1};
static const uint8_t wordFive2[8] = {0, 13, 4, 1};
static const uint8_t wordTwo2[8] = {4, 13, 3, 1};
static const uint8_t wordOne2[8] = {6, 13, 3, 1};
static const uint8_t wordEleven2[8] = {8, 13, 6, 1};
static const uint8_t wordFour2[8] = {0, 14, 4, 1};
static const uint8_t wordFourteen2[8] = {0, 14, 8, 1};
static const uint8_t wordNine2[8] = {7, 14, 4, 1};
static const uint8_t wordNineteen2[8] = {7, 14, 8, 1};
static const uint8_t wordSeven2[8] = {0, 15, 5, 1};
static const uint8_t wordSeventeen2[8] = {0, 15, 9, 1};
static const uint8_t wordOclock[8] = {9, 15, 6, 1};
/* === May/Use the Force be with you === */
static const uint8_t wordUse[8] = {1, 4, 1, 3};
static const uint8_t wordMay[8] = {0, 3, 1, 3};
static const uint8_t wordThe[8] = {5, 1, 1, 3};
static const uint8_t wordForce[8] = {7, 0, 1, 5};
static const uint8_t wordBe[8] = {1, 8, 1, 2};
static const uint8_t wordWith[8] = {3, 9, 1, 4};
static const uint8_t wordYou[8] = {15, 13, 1, 3};
/* ===================================== */
/* === Do or do not, there is no try === */
static const uint8_t wordDo[8] = {0, 1, 1, 2};
static const uint8_t wordOr[8] = {7, 1, 1, 2};
static const uint8_t wordDo2[8] = {9, 4, 1, 2};
static const uint8_t wordNot[8] = {15, 1, 1, 3};
static const uint8_t wordThere[8] = {3, 11, 1, 5};
static const uint8_t wordIs[8] = {9, 10, 1, 2};
static const uint8_t wordNo[8] = {12, 8, 1, 2};
static const uint8_t wordTry[8] = {15, 7, 1, 3};
/* =================================== */
/* === Sith / Jedi / Yoda ============ */
static const uint8_t wordJedi[8] = {0, 7, 1, 4};
static const uint8_t wordSith[8] = {8, 7, 1, 4};
static const uint8_t wordYoda[8] = {15, 9, 1, 4};
/* =================================== */




// Make pixel 0,0 reflect the onboard RGB LED state when not connected to the
// cloud or an OTA update is occurring
void ledChangeHandler(uint8_t r, uint8_t g, uint8_t b) {
  bool do_it = false;

  if (!Particle.connected()) {
    do_it = true;
  }

  if (do_it) {
    mayTheForce();
  }

}


void setup() {
  // Initialize the panel
  matrix.begin();

  //neopixel setup
  strip.begin();
  strip.setPixelColor(0, strip.Color(sr, sg, sb));
  strip.show(); // Initialize all pixels to 'off'

  //Do stuff with the status RGB
  RGB.onChange(ledChangeHandler);

  //  Connect to the cloud
  Particle.connect();
  while (!Particle.connected()) {
    Particle.process();
    delay(1);
  }

  Particle.function("text", text);                      // scroll a text over the matrix
  Particle.function("handleparams",handleParams);         // handles all parameters.
  
  // ===== Snake =====
  snakehead = &snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3];
  apple.row = 5;
  apple.column = 5;
  applepointer = &apple;
  Snake.snake_intialization(snake); //initialize snake location and direction
  // ===== Snake =====

  Time.zone(timeZone);       // Set time zone
}



void loop() {
  currentMillis = millis();

  if (specialModeNumber >= 0) {
    delayTime = 5000;
    blackOut();

    switch (specialModeNumber) {
      case 0:
        useTheForce();                      //display "use the force"
        Particle.publish("musicPick","8");
        delayTime = 8500;
        break;
      case 1:
        mayTheForce();                      // display "may the force be with you"
        Particle.publish("musicPick","37");
        break;
      case 2:
        doOrDoNot();                        // display "Do ot do not, there is no try"
        Particle.publish("musicPick","32");
        delayTime = 6000;
        break;
      case 3:
        //lightLetter(14, 1, 0, 255, 0);      // light up the Ion cannon pixel
        shootCannon();
        delayTime = 18000;
        break;
      case 4:
        doWord(wordJedi);                   // display "Jedi"
        break;
      case 5:
        doWord(wordSith);                   // display "Sith"
        break;
      case 6:
        doWord(wordYoda);                   // display "Yoda"
        break;
    }

    matrix.swapBuffers(true);
    //delay(delayTime);
    specialModeNumber = -1;
  }

  if (currentMillis - previousDisplayMillis > delayTime){
    previousDisplayMillis = currentMillis;
  
      switch (displayMode) {
        case 0:   // display the 'normal' wordclock
          doTime();
          break;
    
        case 1:   // play Snake
          if (currentMillis - previousMillis > speed) {
            // save the last time you blinked the LED
            previousMillis = currentMillis;
            update ? snake_alive() : snake_dead();
          }
          break;
    
        case 2:   // display matrix animation
          if ( currentMillis >= FrameTime + FrameRate) {  // Runs animation function every frame time
            FrameTime = currentMillis;
            streamerAnimation();                          // Just streamer traces animation, no time.
          }
          matrix.swapBuffers(true);
          break;
    
        case 3:   // Show time in digital fashion
          printTimeBig();
          break;
    
        default:  // default to normal wordclock
          doTime();
          break;
      }
      delayTime = 0;
   }
}


void scrollBigMessage(char *m, int timeDelay = 50) {
  matrix.setTextSize(2);
  matrix.setTextWrap(false);
  
  matrix.setTextColor(matrix.Color333(r,g,b));

  int l = (strlen(m) * -12) - 32;

  for (int i = 32; i > l; i -= 2) {
    matrix.fillScreen(0);
    matrix.swapBuffers(true);
    matrix.setCursor(i, 8);

    matrix.print(m);
    matrix.swapBuffers(false);
    delay(timeDelay);
    Particle.process();
  }
}


int text(String command) {
  command.toCharArray(topLine, 64);

  scrollBigMessage(topLine);
  return 0;
}

// this function automagically gets called upon a matching POST request
int handleParams(String command)
{
  //look for the matching argument <-- max of 64 characters long
  int p = 0;
  while (p<(int)command.length()) {
    int i = command.indexOf(',',p);
    if (i<0) i = command.length();
    int j = command.indexOf('=',p);
    if (j<0) break;
    String key = command.substring(p,j).toUpperCase();
    String value = command.substring(j+1,i);
    int val = value.toInt();
    
    
    // Modes
    if (key=="SETTIMEMODE")         // 0 - 1
      timeMode = val;
    else if (key=="SPECIALS")       // 0 - 6
      specialModeNumber = val;
    else if (key=="DISPLAYMODE")    // 0 - 3
      displayMode = val;
    
    // text color
    else if (key=="R")              // 0 - 255
      r = val;
    else if (key=="G")
      g = val;
    else if (key=="B")
      b = val;    
    
    // Star color
    else if (key=="SR")
      sr = val;
    else if (key=="SG")
      sg = val;
    else if (key=="SB")
      sb = val;    
    
    // Snake    
    else if (key=="DIRECTION")
      Snake.set_new_direction(val); // 0 - 3
    else if (key=="SNAKESPEED")     // 50 - 250
      speed = val;
    
    else if (key=="SYSRESET")       // instant
      System.reset();
      
    else if (key=="MATRIXSPEED")
      FrameRate = val;

    p = i+1;
  }
  strip.setPixelColor(0, strip.Color(sr, sg, sb));
  strip.show();
  return 1;
}

void shootCannon(){
  int tempRed = sr;
  int tempGreen = sg;
  int tempBlue = sb;
  
  Particle.publish("musicPick", "1");
  delay(2000);
  
  Particle.publish("musicPick","2");
  
  strip.setPixelColor(0, strip.Color(255, 0, 0));
  strip.show();
  
  // X - X      - X -      - - -
  // - - -  ->  X - X  ->  - X -
  // X - X      - X -      - - -
  
  
  Particle.publish("shoot");
  for (int i = 0; i < 38; i++){
      blackOut();
      lightLetter(13, 0, 0, 255, 0);    // light up the top left
      lightLetter(15, 0, 0, 255, 0);    // top right
      lightLetter(13, 2, 0, 255, 0);
      lightLetter(15, 2, 0, 255, 0);
      matrix.swapBuffers(true);
      delay(100);
      blackOut();
      lightLetter(14, 0, 0, 255, 0);    
      lightLetter(14, 2, 0, 255, 0);    
      lightLetter(13, 1, 0, 255, 0);
      lightLetter(15, 1, 0, 255, 0);
      matrix.swapBuffers(true);
      delay(100);
  }
  blackOut();
  lightLetter(14, 1, 0, 255, 0);
  matrix.swapBuffers(true);
  delay(100);
  blackOut();
  lightLetter(14, 1, 0, 255, 0);
  matrix.swapBuffers(true);
  delay(100);
  blackOut();
  for (int i = 0; i < 15; i++){
      blackOut();
      lightLetter(13, 0, 0, 255, 0);    // light up the top left
      lightLetter(15, 0, 0, 255, 0);    // top right
      lightLetter(13, 2, 0, 255, 0);
      lightLetter(15, 2, 0, 255, 0);
      matrix.swapBuffers(true);
      delay(50);
      blackOut();
      lightLetter(14, 0, 0, 255, 0);    
      lightLetter(14, 2, 0, 255, 0);    
      lightLetter(13, 1, 0, 255, 0);
      lightLetter(15, 1, 0, 255, 0);
      matrix.swapBuffers(true);
      delay(50);
  }
  blackOut();
  lightLetter(14, 1, 0, 255, 0);
  matrix.swapBuffers(true);
  delay(500);
  blackOut();
  matrix.swapBuffers(true);
  delay(100);
  lightLetter(14, 1, 0, 255, 0);
  matrix.swapBuffers(true);
  delay(500);
  blackOut();
  matrix.swapBuffers(true);
  delay(100);
  lightLetter(14, 1, 0, 255, 0);
  matrix.swapBuffers(true);
  delay(3000);
  blackOut();
  
  strip.setPixelColor(0, strip.Color(tempRed, tempGreen, tempBlue));
  strip.show();
  delay(500);
  Particle.publish("musicPick", "3");
}


void doTime() {
    blackOut();

    doWord(wordIts);
    displayHour();
    displayMinute();
    matrix.swapBuffers(true);
    delay(1000);
}

void printTimeBig() {
  blackOut();
  matrix.setTextSize(2);

  matrix.setCursor(2 * 3, 0);
  matrix.setTextColor(matrix.Color333(0, 7, 0));
  switch (Time.hour()) {
    case 0:
      matrix.print("00");
      break;
    case 1:
      matrix.print("01");
      break;
    case 2:
      matrix.print("02");
      break;
    case 3:
      matrix.print("03");
      break;
    case 4:
      matrix.print("04");
      break;
    case 5:
      matrix.print("05");
      break;
    case 6:
      matrix.print("06");
      break;
    case 7:
      matrix.print("07");
      break;
    case 8:
      matrix.print("08");
      break;
    case 9:
      matrix.print("09");
      break;
    default:
      matrix.print(Time.hour());
  }

  matrix.setCursor(2 * 3, 2 * 8);
  matrix.setTextColor(matrix.Color333(0, 7, 7));
  switch (Time.minute()) {
    case 0:
      matrix.print("00");
      break;
    case 1:
      matrix.print("01");
      break;
    case 2:
      matrix.print("02");
      break;
    case 3:
      matrix.print("03");
      break;
    case 4:
      matrix.print("04");
      break;
    case 5:
      matrix.print("05");
      break;
    case 6:
      matrix.print("06");
      break;
    case 7:
      matrix.print("07");
      break;
    case 8:
      matrix.print("08");
      break;
    case 9:
      matrix.print("09");
      break;
    default:
      matrix.print(Time.minute());
  }
  matrix.swapBuffers(true);
  delay(1000);
}

//Display functions

void blackOut() {
  matrix.fillScreen(matrix.Color444(0, 0, 0));
}

void useTheForce() {
  doWord(wordUse);
  doWord(wordThe);
  doWord(wordForce);
}

void mayTheForce() {
  doWord(wordMay);
  doWord(wordThe);
  doWord(wordForce);
  doWord(wordBe);
  doWord(wordWith);
  doWord(wordYou);
}

void doOrDoNot() {
  doWord(wordDo);
  doWord(wordOr);
  doWord(wordDo2);
  doWord(wordNot);
  doWord(wordThere);
  doWord(wordIs);
  doWord(wordNo);
  doWord(wordTry);
}


void lightLetter(int X, int Y, int red = r, int green = g, int blue = b) {
  X *= 2;
  Y *= 2;
  matrix.drawPixel(X       , Y      , matrix.Color333(red, green, blue));
  matrix.drawPixel(X + 1   , Y      , matrix.Color333(red, green, blue));
  matrix.drawPixel(X       , Y + 1  , matrix.Color333(red, green, blue));
  matrix.drawPixel(X + 1   , Y + 1  , matrix.Color333(red, green, blue));
}

//(un)set Words
void doWord(const uint8_t *w) {
  int X = 0;
  int Y = 0;

  //finish loop per vertical row
  for (int i = 0; i < w[3]; i++) {
    //finish loops horizontally
    for (int j = 0; j < w[2]; j++) {
      X = (w[0] + j);
      Y = (w[1] + i);
      lightLetter(X, Y);
    }
  }
}

//set hours/minutes
void displayHour() {
  int h = Time.hourFormat12();
  int m = Time.minute();

  if (timeMode == 0) {
    if (m != 0 && m <= 30) {
      doWord(wordPast);
    }
    else if (m > 30) {
      h++;

      if (h == 13) {
        h = 1;
      }

      doWord(wordTo);
    }

    // hour
    switch (h) {
      case 1:
        (m != 0) ? doWord(wordOne2) : doWord(wordOne);
        break;
      case 2:
        (m != 0) ? doWord(wordTwo2) : doWord(wordTwo);
        break;
      case 3:
        (m != 0) ? doWord(wordThree2) : doWord(wordThree);
        break;
      case 4:
        (m != 0) ? doWord(wordFour2) : doWord(wordFour);
        break;
      case 5:
        (m != 0) ? doWord(wordFive2) : doWord(wordFive);
        break;
      case 6:
        (m != 0) ? doWord(wordSix2) : doWord(wordSix);
        break;
      case 7:
        (m != 0) ? doWord(wordSeven2) : doWord(wordSeven);
        break;
      case 8:
        (m != 0) ? doWord(wordEight2) : doWord(wordEight);
        break;
      case 9:
        (m != 0) ? doWord(wordNine2) : doWord(wordNine);
        break;
      case 10:
        (m != 0) ? doWord(wordTen2) : doWord(wordTen);
        break;
      case 11:
        (m != 0) ? doWord(wordEleven2) : doWord(wordEleven);
        break;
      case 12:
        (m != 0) ? doWord(wordTwelve2) : doWord(wordTwelve);
        break;
    }
  }

  else if (timeMode == 1) {
    switch (h) {
      case 1:
        doWord(wordOne);
        break;
      case 2:
        doWord(wordTwo);
        break;
      case 3:
        doWord(wordThree);
        break;
      case 4:
        doWord(wordFour);
        break;
      case 5:
        doWord(wordFive);
        break;
      case 6:
        doWord(wordSix);
        break;
      case 7:
        doWord(wordSeven);
        break;
      case 8:
        doWord(wordEight);
        break;
      case 9:
        doWord(wordNine);
        break;
      case 10:
        doWord(wordTen);
        break;
      case 11:
        doWord(wordEleven);
        break;
      case 12:
        doWord(wordTwelve);
        break;
    }
  }
}

void displayMinute() {
  int m = Time.minute();

  if (timeMode == 0) {
    switch (m) {
      case 0:
        doWord(wordOclock);
        break;
      case 1:
        doWord(wordOne);
        doWord(wordMinute);
        break;
      case 2:
        doWord(wordTwo);
        break;
      case 3:
        doWord(wordThree);
        break;
      case 4:
        doWord(wordFour);
        break;
      case 5:
        doWord(wordFive);
        break;
      case 6:
        doWord(wordSix);
        break;
      case 7:
        doWord(wordSeven);
        break;
      case 8:
        doWord(wordEight);
        break;
      case 9:
        doWord(wordNine);
        break;
      case 10:
        doWord(wordTen);
        break;
      case 11:
        doWord(wordEleven);
        break;
      case 12:
        doWord(wordTwelve);
        break;
      case 13:
        doWord(wordThirteen);
        break;
      case 14:
        doWord(wordFourteen);
        break;
      case 15:
        doWord(wordA);
        doWord(wordQuarter);
        break;
      case 16:
        doWord(wordSixteen);
        break;
      case 17:
        doWord(wordSeventeen);
        break;
      case 18:
        doWord(wordEighteen);
        break;
      case 19:
        doWord(wordNineteen);
        break;
      case 20:
        doWord(wordTwenty);
        break;
      case 21:
        doWord(wordTwenty);
        doWord(wordOne);
        break;
      case 22:
        doWord(wordTwenty);
        doWord(wordTwo);
        break;
      case 23:
        doWord(wordTwenty);
        doWord(wordThree);
        break;
      case 24:
        doWord(wordTwenty);
        doWord(wordFour);
        break;
      case 25:
        doWord(wordTwenty);
        doWord(wordFive);
        break;
      case 26:
        doWord(wordTwenty);
        doWord(wordSix);
        break;
      case 27:
        doWord(wordTwenty);
        doWord(wordEight);
        break;
      case 28:
        doWord(wordTwenty);
        doWord(wordEight);
        break;
      case 29:
        doWord(wordTwenty);
        doWord(wordNine);
        break;
      case 30:
        doWord(wordHalf);
        break;
      case 31:
        doWord(wordTwenty);
        doWord(wordNine);
        break;
      case 32:
        doWord(wordTwenty);
        doWord(wordEight);
        break;
      case 33:
        doWord(wordTwenty);
        doWord(wordSeven);
        break;
      case 34:
        doWord(wordTwenty);
        doWord(wordSix);
        break;
      case 35:
        doWord(wordTwenty);
        doWord(wordFive);
        break;
      case 36:
        doWord(wordTwenty);
        doWord(wordFour);
        break;
      case 37:
        doWord(wordTwenty);
        doWord(wordThree);
        break;
      case 38:
        doWord(wordTwenty);
        doWord(wordTwo);
        break;
      case 39:
        doWord(wordTwenty);
        doWord(wordOne);
        break;
      case 40:
        doWord(wordTwenty);
        break;
      case 41:
        doWord(wordNineteen);
        break;
      case 42:
        doWord(wordEighteen);
        break;
      case 43:
        doWord(wordSeventeen);
        break;
      case 44:
        doWord(wordSixteen);
        break;
      case 45:
        doWord(wordA);
        doWord(wordQuarter);
        break;
      case 46:
        doWord(wordFourteen);
        break;
      case 47:
        doWord(wordThirteen);
        break;
      case 48:
        doWord(wordTwelve);
        break;
      case 49:
        doWord(wordEleven);
        break;
      case 50:
        doWord(wordTen);
        break;
      case 51:
        doWord(wordNine);
        break;
      case 52:
        doWord(wordEight);
        break;
      case 53:
        doWord(wordSeven);
        break;
      case 54:
        doWord(wordSix);
        break;
      case 55:
        doWord(wordFive);
        break;
      case 56:
        doWord(wordFour);
        break;
      case 57:
        doWord(wordThree);
        break;
      case 58:
        doWord(wordTwo);
        break;
      case 59:
        doWord(wordOne);
        doWord(wordMinute);
...

This file has been truncated, please download it to see its full contents.

Snake.h

C/C++
Snake header file. Add this manually to the project by clicking the little '+' icon in the top of the web IDE. Make sure to name it 'snake', or else, change the include name in the main file.
#ifndef SNAKE_H_
#define SNAKE_H_

// This #include statement was automatically added by the Particle IDE.
#include "RGBmatrixPanel/RGBmatrixPanel.h"

#include "application.h"


#define ledmatrix_length 16
#define ledmatrix_width 16
#define game_speed 200


#define right 1
#define left 2
#define down 3
#define up 4
/*----------------definitions------------------*/


/*----------------structures------------------*/
typedef struct snakebit {
	char srow;
	char scolumn;
	char direction;
} mysnake;

typedef struct food {
	char row;
	char column;
} food;
/*----------------structures------------------*/

#pragma once
class Serpent
{
    
    RGBmatrixPanel* __matrix;
    int new_direction = 0;
    
public:
	Serpent();
	Serpent(RGBmatrixPanel* matrix);
	virtual ~Serpent();


    void set_new_direction(int val){
		this->new_direction = val;
	}
	int get_new_direction(){
		return this->new_direction;
	}
    

	void
	    snake_intialization(mysnake* snake),
		clear_matrix(),
		create_border(),
		light_bit(int row, int column, int color = 0),
		update_body(mysnake* snake, int length),
		show_body(mysnake* temp, int length),
		adapt_body(mysnake* snake, int length),
		change_direction(mysnake* snakehead),
		happy_meal(mysnake* listhead),
		renew_apple(food* applepointer, mysnake* listhead),
		update_head(mysnake* snakehead),
		clear(mysnake* snake);
		
	
		
	bool
	    check_collision(food* applepointer, mysnake* listhead),
	    body_crash(mysnake* listhead);
};



#endif /* SNAKE_H_ */

Snake.cpp

C/C++
Snake library. Add this in the same fashion as the .h file by clicking the little '+' icon in the top of the web IDE (if you haven't yet done so for the .h file). Then paste the code.
#include "snake.h"

Serpent::Serpent()
{
}
 
Serpent::Serpent(RGBmatrixPanel* matrix){
    __matrix = matrix;
}

Serpent::~Serpent()
{
}

void Serpent::snake_intialization(mysnake * snake) {
	int k;
	for (k = 0; k < ((ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 4); k++) {
		snake[k].srow = 0;
		snake[k].scolumn = 0;
		snake[k].direction = 0;
	}
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3].srow = 5;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3].scolumn = 5;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3].direction = right;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 2].srow = 5;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 2].scolumn = 4;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 2].direction = right;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 1].srow = 5;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 1].scolumn = 3;
	snake[(ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 1].direction = right;
    new_direction = right;
}

void Serpent::clear_matrix() {
    __matrix->fillScreen(0);
}

void Serpent::create_border() {
    __matrix->drawRect(0, 0, ledmatrix_width*2, ledmatrix_length*2, __matrix->Color333(255, 0, 0));
	__matrix->drawRect(1, 1, ledmatrix_width*2-1, ledmatrix_length*2-1, __matrix->Color333(255, 0, 0));
}

void Serpent::light_bit(int row, int column, int color) {
    //light bit
    
    int r = 0;
    int g = 0;
    int b = 0;
    
    switch (color){
        case 0:
            r = 0;
            g = 255;
            b = 50;
            break;
        case 1:
            r = 0;
            g = 255;
            b = 0;
            break;
        case 2:
            r = 255;
            g = 150;
            b = 0;
            break;
            
    }
	
	int X = row * 2;
	int Y = column * 2;
	
	
	__matrix->drawPixel(X       , Y      , __matrix->Color333(r, g, b));
	__matrix->drawPixel(X + 1   , Y      , __matrix->Color333(r, g, b));
	__matrix->drawPixel(X       , Y + 1  , __matrix->Color333(r, g, b));
	__matrix->drawPixel(X + 1   , Y + 1  , __matrix->Color333(r, g, b));
	
}

void Serpent::update_body(mysnake *snake, int length) {
	int i;
	for (i = (ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3 - length + 1; i < (ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3; i++){
    	switch (snake[i + 1].direction) {
    		case 1:
    			++(snake[i].scolumn);
    			break;
    		case 2:
    			--(snake[i].scolumn);
    			break;
    		case 3:
    			++(snake[i].srow);
    			break;
    		case 4:
    			--(snake[i].srow);
    			break;
    	}
	}
}

void Serpent::show_body(mysnake * snake, int length) {
	int i;
	for (i = (ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3 - length + 1; i < (ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3; i++) {
		light_bit(snake[i].srow, snake[i].scolumn);
	}
}

void Serpent::adapt_body(mysnake * snake, int length) {
	int i;
	for (i = (ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3 - length + 1; i < (ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 3; i++) {
		snake[i].direction = snake[i + 1].direction;
	}
}

void Serpent::change_direction(mysnake *snakehead) {
	switch (snakehead -> direction) {
    	case up:
    	{
    		if (new_direction == 1) {
    			snakehead -> direction = right;
    			break;
    		}
    		if (new_direction == 2) {
    			snakehead -> direction = left;
    			break;
    		}
    	}
    	break;
    	case down:
    	{
    		if (new_direction == 1) {
    			snakehead -> direction = right;
    			break;
    		}
    		if (new_direction == 2) {
    			snakehead -> direction = left;
    			break;
    		}
    	}
    	break;
    	case right:
    	{
    		if (new_direction == 3) {
    			snakehead -> direction = up;
    			break;
    		}
    		if (new_direction == 4) {
    			snakehead -> direction = down;
    			break;
    		}
    	}
    	break;
    	case left:
    	{
    		if (new_direction == 3) {
    			snakehead -> direction = up;
    			break;
    		}
    		if (new_direction == 4) {
    			snakehead -> direction = down;
    			break;
    		}
    	}
    	break;
	}
}

void Serpent::happy_meal(mysnake *listhead) {
	mysnake *temp;
	temp = listhead - 1;

	switch (listhead->direction) {
    	case 1:
        	{
        		temp->srow = listhead->srow;
        		temp->scolumn = (listhead->scolumn) - 1;
        	} //right
        break;
    	case 2:
        	{
        		temp->srow = listhead->srow;
        		temp->scolumn = (listhead->scolumn) + 1;
        	} //left
        break;
    	case 3:
        	{
        		temp->srow = (listhead->srow) - 1;
        		temp->scolumn = listhead->scolumn;
        	} //down
        break;
    	case 4:
        	{
        		temp->srow = (listhead->srow) + 1;
        		temp->scolumn = listhead->scolumn;
        	}; //up
        break;
	}
	temp->direction = listhead->direction;

}

void Serpent::renew_apple(food * applepointer, mysnake * listhead) {
  applepointer->row = random(1, ledmatrix_width - 1);
  applepointer->column = random(1, ledmatrix_length - 1);
}

bool Serpent::check_collision(food* applepointer, mysnake* listhead) {
	mysnake* temp;
	temp = listhead;
	while (temp -> direction != 0) {
		if ((applepointer -> row == temp -> srow) && (applepointer -> column == temp -> scolumn)) {
			return 1;
		}
		--temp;
	}
	return 0;
}

void Serpent::update_head(mysnake* snakehead) {
	switch (snakehead -> direction) {
    	case 1:
    		++(snakehead -> scolumn); //right
    	break;
    	case 2:
    		--(snakehead -> scolumn); //left
    	break;
    	case 3:
    		++(snakehead -> srow); //down
    	break;
    	case 4:
    		--(snakehead -> srow); //up
    	break;
	}
}

bool Serpent::body_crash(mysnake* listhead) {
	mysnake* temp;
	temp = listhead - 1;
	while (temp -> direction != 0) {
		if ((listhead -> srow == temp -> srow) && (listhead -> scolumn == temp -> scolumn))
			return 1;
		--temp;
	}
	return 0;
}

void Serpent::clear(mysnake * snake) {
	int k;
	for (k = 0; k < ((ledmatrix_length * ledmatrix_width) - (ledmatrix_length * 2) - (ledmatrix_width * 2) + 4); k++) {
		snake[k].srow = 0;
		snake[k].scolumn = 0;
		snake[k].direction = 0;
	}
}

Index.html

HTML
It's the controller web page. Put it in a directory with the CSS and JS file, and open the HTML in a browser. Alternatively, host it somewhere, then navigate to it.
<html>
  <head>
    <title>Wordclock controller</title>
	  <script src="http://cdn.jsdelivr.net/sparkjs/1/spark.min.js"></script>
    <script type='application/javascript' src='fastclick.js'></script>
    <link rel="stylesheet" href="styles.css">
    
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui">
  </head>

  <body>
    <div class="container">
    
      <div class="flex-row">
        <div class="flex-child">
          <div class="header">Choose the clock mode:</div>
          <hr>
          <button type="button" onclick="functionPost('handleparams', 'displaymode=0')">Activate</button> Wordclock
          <br>
          <button type="button" onclick="functionPost('handleparams', 'displaymode=1')">Activate</button> Snake
          <br>
          <button type="button" onclick="functionPost('handleparams', 'displaymode=2')">Activate</button> Matrix animation
          <br>
          <button type="button" onclick="functionPost('handleparams', 'displaymode=3')">Activate</button> Digital clock
        </div>
      </div>  
       
      <div class="flex-row" id="snakeDiv" style="display:none;">
        <div class="flex-child">
          <div class="header">Use the buttons below, or the arrow keys to control Snake.</div>
          <hr>
          <button type="button" onclick="functionPost('handleparams', 'direction=2')" style="width:100%; height:80px;">Up</button>
          <br>      
          <button type="button" onclick="functionPost('handleparams', 'direction=3')" style="width:48%; height:80px;">Left</button>      
          <button type="button" onclick="functionPost('handleparams', 'direction=4')" style="width:48%; height:80px; float:right;">Right</button> 
          <br>      
          <button type="button" onclick="functionPost('handleparams', 'direction=1')" style="width:100%; height:80px;">Down</button>
        </div>      
      
      </div>
      
      <div class="flex-row">
             
        <div class="flex-child">   
          Set the speeds: slow - fast
          <hr>
          Snake speed
          <br>
          <br>
          <input type="range" id="snakeSpeedRange" min="100" max="450" step="10" value="200" onchange="snakeSpeedRange()">

          <br>        
          <br>
          
          Matrix speed
          <br>
          <br>
          <input type="range" id="matrixSpeedRange" min="10" max="50" step="5" value="20" onchange="matrixSpeedRange()">
        </div>        
      </div> 

      
      <div class="flex-row">  
        <div class="flex-child">
        
          <div class="header">Choose your prefered time mode:</div>
          <hr>
          <button type="button" onclick="functionPost('handleparams', 'setTimeMode=0')">Activate</button> "It's MM past/to HH"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'setTimeMode=1')">Activate</button> "It's HH (o) MM"
        </div>
      </div>

      <div class="flex-row">  
        <div class="flex-child">
          <div class="header">Display a "special effect"</div>
          <hr>
          <button type="button" onclick="functionPost('handleparams', 'specials=0')">Activate</button> "Use the Force"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'specials=1')">Activate</button> "May the Force be with you"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'specials=2')">Activate</button> "Do, or do not. There is no try"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'specials=3')">Activate</button> "Shoot cannon"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'specials=4')">Activate</button> "Jedi"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'specials=5')">Activate</button> "Sith"
          <br>
          <button type="button" onclick="functionPost('handleparams', 'specials=6')">Activate</button> "Yoda"
        </div>
      
      </div>
      
          
      <div class="flex-row selectors">
      
        <div class="flex-child">
          <div class="header">Choose your prefered text color</div>
          <hr>
          <button type="button" onclick="functionPost('handleparams', 'r=255,g=0,b=0')" style="background-color:rgb(255,0,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=255,g=125,b=0')"style="background-color:rgb(255,125,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=255,g=255,b=0')" style="background-color:rgb(255,255,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=125,g=255,b=0')" style="background-color:rgb(125,255,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=0,g=255,b=0')" style="background-color:rgb(0,255,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=0,g=255,b=125')" style="background-color:rgb(0,255,125);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=0,g=255,b=255')" style="background-color:rgb(0,255,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=0,g=125,b=255')" style="background-color:rgb(0,125,255);"></button> 
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=0,g=0,b=255')" style="background-color:rgb(0,0,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=125,g=0,b=255')" style="background-color:rgb(125,0,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=255,g=0,b=255')" style="background-color:rgb(255,0,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=255,g=0,b=125')" style="background-color:rgb(255,0,125);"></button> 
          <br>
          <button type="button" onclick="functionPost('handleparams', 'r=0,g=0,b=0')" style="background-color:rgb(0,0,0);"></button>  
        </div>
      </div>
        
      <div class="flex-row selectors">
        <div class="flex-child">
        
          <div class="header">Choose your prefered Death Star color</div>
          <hr>
          <button type="button" onclick="functionPost('handleparams', 'sr=255,sg=0,sb=0')" style="background-color:rgb(255,0,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=255,sg=125,sb=0')"style="background-color:rgb(255,125,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=255,sg=255,sb=0')" style="background-color:rgb(255,255,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=125,sg=255,sb=0')" style="background-color:rgb(125,255,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=0,sg=255,sb=0')" style="background-color:rgb(0,255,0);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=0,sg=255,sb=125')" style="background-color:rgb(0,255,125);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=0,sg=255,sb=255')" style="background-color:rgb(0,255,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=0,sg=125,sb=255')" style="background-color:rgb(0,125,255);"></button>    
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=0,sg=0,sb=255')" style="background-color:rgb(0,0,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=125,sg=0,sb=255')" style="background-color:rgb(125,0,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=255,sg=0,sb=255')" style="background-color:rgb(255,0,255);"></button>
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=255,sg=0,sb=125')" style="background-color:rgb(255,0,125);"></button> 
          <br>
          <button type="button" onclick="functionPost('handleparams', 'sr=0,sg=0,sb=0')" style="background-color:rgb(0,0,0);"></button> 
          
        </div>
      </div>
      
    </div>
    
    
    <script>

      var deviceID = "DEVICE_ID_HERE";
      
      var direction;
      var snakeState;
      //var directionsDiv = document.getElementById("directionsDiv");
      var controlEnabler = document.getElementById("controlEnabler");
      var snakeDiv = document.getElementById("snakeDiv");
      
      // callback to be executed by each core
      var callback = function(err, data) {
        if (err) {
          console.log('An error occurred:', err);          
        } else {
          console.log('Device action successfull:', data);
        }
      };    
	
  
      function functionPost(functionName, functionArgument){
        if (functionArgument.indexOf("displaymode") > -1){
          snakeState = (functionArgument == "displaymode=1") ? true : false;      
          snakeDiv.style.display = snakeState ? "flex" : "none";
        }
        spark.callFunction(deviceID, functionName, functionArgument, callback);  
      }
	  
      
      
      document.onkeydown = function(e) {
        if (snakeState){
          switch (e.keyCode) {
            case 37:
              e.preventDefault();
              direction = 3;
              //alert('left');
              break;
            case 38:
              e.preventDefault();
              direction = 2;
              //alert('up');
              break;
            case 39:
              e.preventDefault();
              direction = 4;
              //alert('right');
              break;
            case 40:
              e.preventDefault();
              direction = 1;
              //alert('down');
              break;
          }            
          functionPost('handleparams', 'direction=' + direction);
        }  
      };
      
      
      
      function snakeSpeedRange()
      {
        var snakeSpeedRange = document.getElementById('snakeSpeedRange');
        functionPost('handleparams', 'snakespeed=' + snakeSpeedRange.value);
        snakeSpeedRange.blur();
      }
      
      function matrixSpeedRange()
      {
        var matrixSpeedRange = document.getElementById('matrixSpeedRange');
        functionPost('handleparams', 'matrixspeed=' + matrixSpeedRange.value);
        matrixSpeedRange.blur();
      }
      
      if ('addEventListener' in document) {
        document.addEventListener('DOMContentLoaded', function() {
          FastClick.attach(document.body);
        }, false);
      }
	  
	  spark.on('login', function(response) {           
        console.log(response);
      });
	  	  
      spark.login({ username: 'EMAIL_ADRESS_HERE', password: 'PARTICLE_PASSWORD_HERE' });  
      
    </script>
  </body>
</html>

fastclick.js

JavaScript
Just make sure it's in the same directory as the HTML file. It'll speed up click on mobile devices, which is needed for Snake.
;(function () {
	'use strict';

	/**
	 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
	 *
	 * @codingstandard ftlabs-jsv2
	 * @copyright The Financial Times Limited [All Rights Reserved]
	 * @license MIT License (see LICENSE.txt)
	 */

	/*jslint browser:true, node:true*/
	/*global define, Event, Node*/


	/**
	 * Instantiate fast-clicking listeners on the specified layer.
	 *
	 * @constructor
	 * @param {Element} layer The layer to listen on
	 * @param {Object} [options={}] The options to override the defaults
	 */
	function FastClick(layer, options) {
		var oldOnClick;

		options = options || {};

		/**
		 * Whether a click is currently being tracked.
		 *
		 * @type boolean
		 */
		this.trackingClick = false;


		/**
		 * Timestamp for when click tracking started.
		 *
		 * @type number
		 */
		this.trackingClickStart = 0;


		/**
		 * The element being tracked for a click.
		 *
		 * @type EventTarget
		 */
		this.targetElement = null;


		/**
		 * X-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartX = 0;


		/**
		 * Y-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartY = 0;


		/**
		 * ID of the last touch, retrieved from Touch.identifier.
		 *
		 * @type number
		 */
		this.lastTouchIdentifier = 0;


		/**
		 * Touchmove boundary, beyond which a click will be cancelled.
		 *
		 * @type number
		 */
		this.touchBoundary = options.touchBoundary || 10;


		/**
		 * The FastClick layer.
		 *
		 * @type Element
		 */
		this.layer = layer;

		/**
		 * The minimum time between tap(touchstart and touchend) events
		 *
		 * @type number
		 */
		this.tapDelay = options.tapDelay || 200;

		/**
		 * The maximum time for a tap
		 *
		 * @type number
		 */
		this.tapTimeout = options.tapTimeout || 700;

		if (FastClick.notNeeded(layer)) {
			return;
		}

		// Some old versions of Android don't have Function.prototype.bind
		function bind(method, context) {
			return function() { return method.apply(context, arguments); };
		}


		var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
		var context = this;
		for (var i = 0, l = methods.length; i < l; i++) {
			context[methods[i]] = bind(context[methods[i]], context);
		}

		// Set up event handlers as required
		if (deviceIsAndroid) {
			layer.addEventListener('mouseover', this.onMouse, true);
			layer.addEventListener('mousedown', this.onMouse, true);
			layer.addEventListener('mouseup', this.onMouse, true);
		}

		layer.addEventListener('click', this.onClick, true);
		layer.addEventListener('touchstart', this.onTouchStart, false);
		layer.addEventListener('touchmove', this.onTouchMove, false);
		layer.addEventListener('touchend', this.onTouchEnd, false);
		layer.addEventListener('touchcancel', this.onTouchCancel, false);

		// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
		// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
		// layer when they are cancelled.
		if (!Event.prototype.stopImmediatePropagation) {
			layer.removeEventListener = function(type, callback, capture) {
				var rmv = Node.prototype.removeEventListener;
				if (type === 'click') {
					rmv.call(layer, type, callback.hijacked || callback, capture);
				} else {
					rmv.call(layer, type, callback, capture);
				}
			};

			layer.addEventListener = function(type, callback, capture) {
				var adv = Node.prototype.addEventListener;
				if (type === 'click') {
					adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
						if (!event.propagationStopped) {
							callback(event);
						}
					}), capture);
				} else {
					adv.call(layer, type, callback, capture);
				}
			};
		}

		// If a handler is already declared in the element's onclick attribute, it will be fired before
		// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
		// adding it as listener.
		if (typeof layer.onclick === 'function') {

			// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
			// - the old one won't work if passed to addEventListener directly.
			oldOnClick = layer.onclick;
			layer.addEventListener('click', function(event) {
				oldOnClick(event);
			}, false);
			layer.onclick = null;
		}
	}

	/**
	* Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
	*
	* @type boolean
	*/
	var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;

	/**
	 * Android requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;


	/**
	 * iOS requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;


	/**
	 * iOS 4 requires an exception for select elements.
	 *
	 * @type boolean
	 */
	var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);


	/**
	 * iOS 6.0-7.* requires the target element to be manually derived
	 *
	 * @type boolean
	 */
	var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);

	/**
	 * BlackBerry requires exceptions.
	 *
	 * @type boolean
	 */
	var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;

	/**
	 * Determine whether a given element requires a native click.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element needs a native click
	 */
	FastClick.prototype.needsClick = function(target) {
		switch (target.nodeName.toLowerCase()) {

		// Don't send a synthetic click to disabled inputs (issue #62)
		case 'button':
		case 'select':
		case 'textarea':
			if (target.disabled) {
				return true;
			}

			break;
		case 'input':

			// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
			if ((deviceIsIOS && target.type === 'file') || target.disabled) {
				return true;
			}

			break;
		case 'label':
		case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
		case 'video':
			return true;
		}

		return (/\bneedsclick\b/).test(target.className);
	};


	/**
	 * Determine whether a given element requires a call to focus to simulate click into element.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
	 */
	FastClick.prototype.needsFocus = function(target) {
		switch (target.nodeName.toLowerCase()) {
		case 'textarea':
			return true;
		case 'select':
			return !deviceIsAndroid;
		case 'input':
			switch (target.type) {
			case 'button':
			case 'checkbox':
			case 'file':
			case 'image':
			case 'radio':
			case 'submit':
				return false;
			}

			// No point in attempting to focus disabled inputs
			return !target.disabled && !target.readOnly;
		default:
			return (/\bneedsfocus\b/).test(target.className);
		}
	};


	/**
	 * Send a click event to the specified element.
	 *
	 * @param {EventTarget|Element} targetElement
	 * @param {Event} event
	 */
	FastClick.prototype.sendClick = function(targetElement, event) {
		var clickEvent, touch;

		// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
		if (document.activeElement && document.activeElement !== targetElement) {
			document.activeElement.blur();
		}

		touch = event.changedTouches[0];

		// Synthesise a click event, with an extra attribute so it can be tracked
		clickEvent = document.createEvent('MouseEvents');
		clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
		clickEvent.forwardedTouchEvent = true;
		targetElement.dispatchEvent(clickEvent);
	};

	FastClick.prototype.determineEventType = function(targetElement) {

		//Issue #159: Android Chrome Select Box does not open with a synthetic click event
		if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
			return 'mousedown';
		}

		return 'click';
	};


	/**
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.focus = function(targetElement) {
		var length;

		// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
		if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
			length = targetElement.value.length;
			targetElement.setSelectionRange(length, length);
		} else {
			targetElement.focus();
		}
	};


	/**
	 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
	 *
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.updateScrollParent = function(targetElement) {
		var scrollParent, parentElement;

		scrollParent = targetElement.fastClickScrollParent;

		// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
		// target element was moved to another parent.
		if (!scrollParent || !scrollParent.contains(targetElement)) {
			parentElement = targetElement;
			do {
				if (parentElement.scrollHeight > parentElement.offsetHeight) {
					scrollParent = parentElement;
					targetElement.fastClickScrollParent = parentElement;
					break;
				}

				parentElement = parentElement.parentElement;
			} while (parentElement);
		}

		// Always update the scroll top tracker if possible.
		if (scrollParent) {
			scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
		}
	};


	/**
	 * @param {EventTarget} targetElement
	 * @returns {Element|EventTarget}
	 */
	FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {

		// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
		if (eventTarget.nodeType === Node.TEXT_NODE) {
			return eventTarget.parentNode;
		}

		return eventTarget;
	};


	/**
	 * On touch start, record the position and scroll offset.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchStart = function(event) {
		var targetElement, touch, selection;

		// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
		if (event.targetTouches.length > 1) {
			return true;
		}

		targetElement = this.getTargetElementFromEventTarget(event.target);
		touch = event.targetTouches[0];

		if (deviceIsIOS) {

			// Only trusted events will deselect text on iOS (issue #49)
			selection = window.getSelection();
			if (selection.rangeCount && !selection.isCollapsed) {
				return true;
			}

			if (!deviceIsIOS4) {

				// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
				// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
				// with the same identifier as the touch event that previously triggered the click that triggered the alert.
				// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
				// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
				// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
				// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
				// random integers, it's safe to to continue if the identifier is 0 here.
				if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
					event.preventDefault();
					return false;
				}

				this.lastTouchIdentifier = touch.identifier;

				// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
				// 1) the user does a fling scroll on the scrollable layer
				// 2) the user stops the fling scroll with another tap
				// then the event.target of the last 'touchend' event will be the element that was under the user's finger
				// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
				// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
				this.updateScrollParent(targetElement);
			}
		}

		this.trackingClick = true;
		this.trackingClickStart = event.timeStamp;
		this.targetElement = targetElement;

		this.touchStartX = touch.pageX;
		this.touchStartY = touch.pageY;

		// Prevent phantom clicks on fast double-tap (issue #36)
		if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
			event.preventDefault();
		}

		return true;
	};


	/**
	 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.touchHasMoved = function(event) {
		var touch = event.changedTouches[0], boundary = this.touchBoundary;

		if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
			return true;
		}

		return false;
	};


	/**
	 * Update the last position.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchMove = function(event) {
		if (!this.trackingClick) {
			return true;
		}

		// If the touch has moved, cancel the click tracking
		if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
			this.trackingClick = false;
			this.targetElement = null;
		}

		return true;
	};


	/**
	 * Attempt to find the labelled control for the given label element.
	 *
	 * @param {EventTarget|HTMLLabelElement} labelElement
	 * @returns {Element|null}
	 */
	FastClick.prototype.findControl = function(labelElement) {

		// Fast path for newer browsers supporting the HTML5 control attribute
		if (labelElement.control !== undefined) {
			return labelElement.control;
		}

		// All browsers under test that support touch events also support the HTML5 htmlFor attribute
		if (labelElement.htmlFor) {
			return document.getElementById(labelElement.htmlFor);
		}

		// If no for attribute exists, attempt to retrieve the first labellable descendant element
		// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
		return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
	};


	/**
	 * On touch end, determine whether to send a click event at once.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchEnd = function(event) {
		var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;

		if (!this.trackingClick) {
			return true;
		}

		// Prevent phantom clicks on fast double-tap (issue #36)
		if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
			this.cancelNextClick = true;
			return true;
		}

		if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
			return true;
		}

		// Reset to prevent wrong click cancel on input (issue #156).
		this.cancelNextClick = false;

		this.lastClickTime = event.timeStamp;

		trackingClickStart = this.trackingClickStart;
		this.trackingClick = false;
		this.trackingClickStart = 0;

		// On some iOS devices, the targetElement supplied with the event is invalid if the layer
		// is performing a transition or scroll, and has to be re-detected manually. Note that
		// for this to function correctly, it must be called *after* the event target is checked!
		// See issue #57; also filed as rdar://13048589 .
		if (deviceIsIOSWithBadTarget) {
			touch = event.changedTouches[0];

			// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
			targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
			targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
		}

		targetTagName = targetElement.tagName.toLowerCase();
		if (targetTagName === 'label') {
			forElement = this.findControl(targetElement);
			if (forElement) {
				this.focus(targetElement);
				if (deviceIsAndroid) {
					return false;
				}

				targetElement = forElement;
			}
		} else if (this.needsFocus(targetElement)) {

			// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
			// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
			if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
				this.targetElement = null;
				return false;
			}

			this.focus(targetElement);
			this.sendClick(targetElement, event);

			// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
			// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
			if (!deviceIsIOS || targetTagName !== 'select') {
				this.targetElement = null;
				event.preventDefault();
			}

			return false;
		}

		if (deviceIsIOS && !deviceIsIOS4) {

			// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
			// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
			scrollParent = targetElement.fastClickScrollParent;
			if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
				return true;
			}
		}

		// Prevent the actual click from going though - unless the target node is marked as requiring
		// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
		if (!this.needsClick(targetElement)) {
			event.preventDefault();
			this.sendClick(targetElement, event);
		}

		return false;
	};


	/**
	 * On touch cancel, stop tracking the click.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.onTouchCancel = function() {
		this.trackingClick = false;
		this.targetElement = null;
	};


	/**
	 * Determine mouse events which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onMouse = function(event) {

		// If a target element was never set (because a touch event was never fired) allow the event
		if (!this.targetElement) {
			return true;
		}

		if (event.forwardedTouchEvent) {
			return true;
		}

		// Programmatically generated events targeting a specific element should be permitted
		if (!event.cancelable) {
			return true;
		}

		// Derive and check the target element to see whether the mouse event needs to be permitted;
		// unless explicitly enabled, prevent non-touch click events from triggering actions,
		// to prevent ghost/doubleclicks.
		if (!this.needsClick(this.targetElement) || this.cancelNextClick) {

			// Prevent any user-added listeners declared on FastClick element from being fired.
			if (event.stopImmediatePropagation) {
				event.stopImmediatePropagation();
			} else {

				// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
				event.propagationStopped = true;
			}

			// Cancel the event
			event.stopPropagation();
			event.preventDefault();

			return false;
		}

		// If the mouse event is permitted, return true for the action to go through.
		return true;
	};


	/**
	 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
	 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
	 * an actual click which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onClick = function(event) {
		var permitted;

		// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
		if (this.trackingClick) {
			this.targetElement = null;
			this.trackingClick = false;
			return true;
		}

		// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
		if (event.target.type === 'submit' && event.detail === 0) {
			return true;
		}

		permitted = this.onMouse(event);

		// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
		if (!permitted) {
			this.targetElement = null;
		}

		// If clicks are permitted, return true for the action to go through.
		return permitted;
	};


	/**
	 * Remove all FastClick's event listeners.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.destroy = function() {
		var layer = this.layer;

		if (deviceIsAndroid) {
			layer.removeEventListener('mouseover', this.onMouse, true);
			layer.removeEventListener('mousedown', this.onMouse, true);
			layer.removeEventListener('mouseup', this.onMouse, true);
		}

		layer.removeEventListener('click', this.onClick, true);
		layer.removeEventListener('touchstart', this.onTouchStart, false);
		layer.removeEventListener('touchmove', this.onTouchMove, false);
		layer.removeEventListener('touchend', this.onTouchEnd, false);
		layer.removeEventListener('touchcancel', this.onTouchCancel, false);
	};


	/**
	 * Check whether FastClick is needed.
	 *
	 * @param {Element} layer The layer to listen on
	 */
	FastClick.notNeeded = function(layer) {
		var metaViewport;
		var chromeVersion;
		var blackberryVersion;
		var firefoxVersion;

		// Devices that don't support touch don't need FastClick
		if (typeof window.ontouchstart === 'undefined') {
			return true;
		}

		// Chrome version - zero for other browsers
		chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];

		if (chromeVersion) {

			if (deviceIsAndroid) {
				metaViewport = document.querySelector('meta[name=viewport]');

				if (metaViewport) {
					// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
					if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// Chrome 32 and above with width=device-width or less don't need FastClick
					if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
						return true;
					}
				}

			// Chrome desktop doesn't need FastClick (issue #15)
			} else {
				return true;
			}
		}

		if (deviceIsBlackBerry10) {
			blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);

			// BlackBerry 10.3+ does not require Fastclick library.
			// https://github.com/ftlabs/fastclick/issues/251
			if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
				metaViewport = document.querySelector('meta[name=viewport]');

				if (metaViewport) {
					// user-scalable=no eliminates click delay.
					if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// width=device-width (or less than device-width) eliminates click delay.
					if (document.documentElement.scrollWidth <= window.outerWidth) {
						return true;
					}
				}
			}
		}

		// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
		if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
			return true;
		}

		// Firefox version - zero for other browsers
		firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];

		if (firefoxVersion >= 27) {
			// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896

			metaViewport = document.querySelector('meta[name=viewport]');
			if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
				return true;
			}
		}

		// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
		// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
		if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
			return true;
		}

		return false;
	};


	/**
	 * Factory method for creating a FastClick object
	 *
	 * @param {Element} layer The layer to listen on
	 * @param {Object} [options={}] The options to override the defaults
	 */
	FastClick.attach = function(layer, options) {
		return new FastClick(layer, options);
	};


	if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {

		// AMD. Register as an anonymous module.
		define(function() {
			return FastClick;
		});
	} else if (typeof module !== 'undefined' && module.exports) {
		module.exports = FastClick.attach;
		module.exports.FastClick = FastClick;
	} else {
		window.FastClick = FastClick;
	}
}());

styles.css

CSS
Makes things look pretty. Goes in the same directory as the HTML file.
html{
  color:white;
}
 /*
 body{
   background-image:url("wordclock2.JPG");
   background-size:100%;   
   background-repeat: no-repeat;
 }
 */
 
.container{

  display:flex;
  flex-flow: column wrap;

  justify-content:center; 

}

.flex-row{
  display:flex;
  justify-content:center; 
  margin:10px;
}

 
.flex-child{
  padding:25px;
  min-width:300px;
  max-width: 600px;
  background-color: rgba(40, 40, 40, 0.95);
  
}
 
 
button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 10px 15px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

input[type=range] {
    width: 100%;
    height:20px;
}

input[type="range"]::-webkit-slider-thumb {
    width: 30px;
    height: 30px;
}

input[type="range" i] {
    color: white;
}

input[type=range]::-ms-thumb {
  box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
  border: 1px solid #000000;
  height: 36px;
  width: 16px;
  border-radius: 3px;
  background: #ffffff;
  cursor: pointer;
}



.selectors button {
  width:100%;
  height:40px;
  border: none;
  color: white;
  padding: 10px 15px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 2px 2px;
  cursor: pointer;
}

.header{
  word-wrap:normal;
  text-align:center;
  font-size:18px;
  font-weight:bold;
}

DFmini player code

C/C++
Flash it to the device you've got the player hooked up to. This code is pretty much a copy from this topic in the Particle community. I've only added the function and subscribe block to it: https://community.particle.io/t/a-great-very-cheap-mp3-sound-module-without-need-for-a-library/20111
/* DF Player mini command discovery (Modified for Particle world by @FiDel - Feb 16, 2016)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This program is meant to discover all the possibilities of the command structure of the DFPlayer mini.
No special libraries are needed.
It's very easy to understand and can be the basis for your own mp3 player sketch.
Note: Commands are not always correctly described in the manual. I tried to fix it, but there is still a lot to do. The commands recoverd so far are listed below.

Use of sketch: Enter three (separated) decimal numbers in the Serial Monitor with no end of line character.
First number : Command
Second number: First (High Byte) parameter
Third number : Second (Low Byte) parameter
E.g.: 3,0,1 will play the first track on the TF card

Very important for 5V Arduinos: Use serial 1K resistors or a level shifter between module RX and TX and Arduino to suppress noise
Connect Sound module board RX to Arduino pin 11 (via 1K resistor)
Connect Sound module board TX to Arduino pin 10 (via 1K resistor)
Connect Sound module board Vcc to Arduino Vin when powered via USB (preferably 3.0) else use seperate 5V power supply
Connect Sound module board GND to Arduino GND

General DF Player mini command structure (only byte 3, 5 and 6 to be entered in the serial monitor):
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Byte Function Value
==== ================ ====
(0) Start Byte 0x7E
(1) Version Info 0xFF (don't know why it's called Version Info)
(2) Number of bytes 0x06 (Always 6 bytes)
(3) Command 0x__
(4) Command feedback 0x__ If enabled returns info with command 0x41 [0x01: info, 0x00: no info]
(5) Parameter 1 [DH] 0x__
(6) Parameter 2 [DL] 0x__
(7) Checksum high 0x__ See explanation below. Is calculated in function: execute_CMD
(8) Checksum low 0x__ See explanation below. Is calculated in function: execute_CMD
(9) End command 0xEF

Checksum calculation.
~~~~~~~~~~~~~~~~~~~~
Checksum = -Sum(byte(1..6)) (2 bytes, notice minus sign!)

Commands without returned parameters (*=Confirmed command ?=Unknown, not clear or not validated)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CMD CMD
HEX Dec Function Description Parameters(2 x 8 bit)
==== === =================================== ========================================================================
0x01 1 Next * [DH]=X, [DL]=X Next file in current folder.Loops when last file played
0x02 2 Previous * [DH]=X, [DL]=X Previous file in current folder.Loops when last file played
0x03 3 Specify track(NUM) * [DH]=highByte(NUM), [DL]=lowByte(NUM)
1~2999 Playing order is order in which the numbers are stored.
Filename and foldername are arbitrary, but when named starting with
an increasing number and in one folder, files are played in
that order and with correct track number.
e.g. 0001-Joe Jackson.mp3...0348-Lets dance.mp3)
0x04 4 Increase volume * [DH]=X, [DL]=X Increase volume by 1
0x05 5 Decrease volume * [DH]=X, [DL]=X Decrease volume by 1
0x06 6 Specify volume * [DH]=X, [DL]= Volume (0-0x30) Default=0x30
0x07 7 Specify Equalizer * [DH]=X, [DL]= EQ(0/1/2/3/4/5) [Normal/Pop/Rock/Jazz/Classic/Base]
0x08 8 Specify repeat(NUM) * [DH]=highByte(NUM), [DL]=lowByte(NUM).Repeat the specified track number
0x09 9 Specify playback source (Datasheet) ? [DH]=X, [DL]= (0/1/2/3/4)Unknown. Seems to be overrided by automatic detection
(Datasheet: U/TF/AUX/SLEEP/FLASH)
0x0A 10 Enter into standby – low power loss * [DH]=X, [DL]=X Works, but no command found yet to end standby
(insert TF-card again will end standby mode)
0x0B 11 Normal working (Datasheet) ? Unknown. No error code, but no function found
0x0C 12 Reset module * [DH]=X, [DL]=X Resets all (Track = 0x01, Volume = 0x30)
Will return 0x3F initialization parameter (0x02 for TF-card)
"Clap" sound after excecuting command (no solution found)
0x0D 13 Play * [DH]=X, [DL]=X Play current selected track
0x0E 14 Pause * [DH]=X, [DL]=X Pause track
0x0F 15 Specify folder and file to playback * [DH]=Folder, [DL]=File
Important: Folders must be named 01~99, files must be named 001~255
0x10 16 Volume adjust set (Datasheet) ? Unknown. No error code. Does not change the volume gain.
0x11 17 Loop play * [DH]=X, [DL]=(0x01:play, 0x00:stop play)
Loop play all the tracks. Start at track 1.
0x12 18 Play mp3 file [NUM] in mp3 folder * [DH]=highByte(NUM), [DL]=lowByte(NUM)
Play mp3 file in folder named mp3 in your TF-card. File format exact
4-digit number (0001~2999) e.g. 0235.mp3
0x13 19 Unknown ? Unknown: Returns error code 0x07
0x14 20 Unknown ? Unknown: Returns error code 0x06
0x15 21 Unknown ? Unknown: Returns no error code, but no function found 
0x16 22 Stop * [DH]=X, [DL]=X, Stop playing current track
0x17 23 Loop Folder 01 * [DH]=x, [DL]=1~255, Loops all tracks in folder named "01"
0x18 24 Random play * [DH]=X, [DL]=X Random all tracks, always starts at track 1
0x19 25 Single loop * [DH]=0, [DL]=0 Loops the track that is playing
0x1A 26 Pause * [DH]=X, [DL]=(0x01:pause, 0x00:stop pause)

Commands with returned parameters (*=Confirmed command ?=Unknown, not clear or not validated)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CMD CMD
HEX Dec Function Description Parameters(2 x 8 bit)
==== === =================================== ===========================================================================
0x3A 58 Medium inserted * [DH]=0, [DL]=(1:U-disk, 2:TF-card)
0x3B 59 Medium ejected * [DH]=0, [DL]=(1:U-disk, 2:TF-card)
0x3C 60 Finished track on U-disk * [DH]=highByte(NUM), [DL]=lowByte(NUM)
Not validated. Returns track number when song is finished on U-Disk
0x3D 61 Finished track on TF-card * [DH]=highByte(NUM), [DL]=lowByte(NUM)
Returns track number when song is finished on TF
0x3E 62 Finished track on Flash * [DH]=highByte(NUM), [DL]=lowByte(NUM)
Not validated. Returns track number when song is finished on Flash
0x3F 63 Initialization parameters * [DH]=0, [DL]= 0 ~ 0x0F. Returned code when Reset (0x12) is used.
(each bit represent one device of the low-four bits)
See Datasheet. 0x02 is TF-card. Error 0x01 when no medium is inserted.
0x40 64 Error ? [DH]=0, [DL]= 0~7 Error code(Returned codes not yet analyzed)
0x41 65 Reply ? [DH]=0, [DL]= 0~? Return code when command feedback is high
0x00 no Error (Other returned code not known)
0x42 66 The current status * [DH] = Device number [DL] = 0 no play, 1 play
0x43 67 The current volume * [DH]=0, [DL]= Volume (0-30)
0x44 68 The current EQ * [DH]=0, [DL]= EQ(0/1/2/3/4/5) [Normal/Pop/Rock/Jazz/Classic/Base]
0x45 69 The current playback mode * [DH]=0, [DL]= (0x00: no CMD 0x08 used, 0x02: CMD 0x08 used, not usefull)
0x46 70 The current software version * [DH]=0, [DL]= Software version. (My version is 5)
0x47 71 The total number of U-disk files * [DH]=highByte(NUM), [DL]=lowByte(NUM). Not validated
0x48 72 The total number of TF-card files * [DH]=highByte(NUM), [DL]=lowByte(NUM)
0x49 73 The total number of flash files * [DH]=highByte(NUM), [DL]=lowByte(NUM). Not validated
0x4A 74 Keep on (Datasheet) ? Unknown. No returned parameter
0x4B 75 The current track of U-Disk * [DH]=highByte(NUM), [DL]=lowByte(NUM), Current track on all media
0x4C 76 The current track of TF card * [DH]=highByte(NUM), [DL]=lowByte(NUM), Current track on all media
0x4D 77 The current track of Flash * [DH]=highByte(NUM), [DL]=lowByte(NUM), Current track on all media
0x4E 78 Folder "01" [DH]=x, [DL]=1 * [DH]=0, [DL]=(NUM) Change to first track in folder "01"
Returns number of files in folder "01"
0x4F 79 The total number of folders * [DH]=0, [DL]=(NUM), Total number of folders, including root directory

Additional info can be found on DFRobot site, but is not very reliable
Additional info:http://www.dfrobot.com/index.php?route=product/product&product_id=1121

Ype Brada 2015-04-06
*/
    
# define Start_Byte 0x7E
# define Version_Byte 0xFF
# define Command_Length 0x06
# define End_Byte 0xEF
# define Acknowledge 0x00 //Returns info with command 0x41 [0x01: info, 0x00: no info]


void execute_CMD(byte CMD, byte Par1, byte Par2) // Excecute the command and parameters
{
 // Calculate the checksum (2 bytes)
 int16_t checksum = -(Version_Byte + Command_Length + CMD + Acknowledge + Par1 + Par2);

 // Build the command line
 byte Command_line[10] = { Start_Byte, Version_Byte, Command_Length, CMD, Acknowledge, Par1, Par2, checksum >> 8, checksum & 0xFF, End_Byte};

 //Send the command line to the module
 for (byte k=0; k<10; k++)
 {
  Serial1.write( Command_line[k]);
 }
}



void setup ()
{
 Particle.function("musicPick",musicPick);
 Serial.begin(9600);
 Serial1.begin(9600);

 execute_CMD(0x3F, 0, 0); // Send request for initialization parameters

 while (Serial1.available()<10) // Wait until initialization parameters are received (10 bytes)
 delay(30); // Pretty long delays between succesive commands needed (not always the same)

 // Initialize sound to very low volume. Adapt according used speaker and wanted volume
 execute_CMD(0x06, 0, 25); // Set the volume (0x00~0x30)
 
 Particle.subscribe("musicPick", musicPickHandler);
 
}


void loop ()
{
 if (Serial.available())
 {
  // Input in the Serial monitor: Command and the two parameters in decimal numbers (NOT HEX)
  // E.g. 3,0,1 (or 3 0 1 or 3;0;1) will play first track on the TF-card
  byte Command = Serial.parseInt();
  byte Parameter1 = Serial.parseInt();
  byte Parameter2 = Serial.parseInt();
  
  // Write the input at the screen
  Serial.print("Command : 0x");if (Command < 16) Serial.print("0"); Serial.print(Command, HEX);
  Serial.print("("); Serial.print(Command, DEC);
  Serial.print("); Parameter: 0x");if (Parameter1 < 16) Serial.print("0");Serial.print(Parameter1, HEX);
  Serial.print("("); Serial.print(Parameter1, DEC);
  Serial.print("), 0x");if (Parameter2 < 16) Serial.print("0");Serial.print(Parameter2, HEX);
  Serial.print("("); Serial.print(Parameter2, DEC);Serial.println(")");

  // Excecute the entered command and parameters
  execute_CMD(Command, Parameter1, Parameter2);
 }

 if (Serial1.available()>=10) // There is at least 1 returned message (10 bytes each)
 {
  // Read the returned code
  byte Returned[10];
  for (byte k=0; k<10; k++)
  Returned[k] = Serial1.read();

  // Wtite the returned code to the screen
  Serial.print("Returned: 0x"); if (Returned[3] < 16) Serial.print("0"); Serial.print(Returned[3],HEX);
  Serial.print("("); Serial.print(Returned[3], DEC);
  Serial.print("); Parameter: 0x"); if (Returned[5] < 16) Serial.print("0"); Serial.print(Returned[5],HEX);
  Serial.print("("); Serial1.print(Returned[5], DEC);
  Serial.print("), 0x"); if (Returned[6] < 16) Serial.print("0"); Serial.print(Returned[6],HEX);
  Serial.print("("); Serial.print(Returned[6], DEC); Serial.println(")");
 }
}

int musicPick(String command){
    byte Command = 0x03;
    byte Parameter1 = 0x00;
    byte Parameter2 = command.toInt();
    // Excecute the entered command and parameters
    execute_CMD(Command, Parameter1, Parameter2);
    return 0;
}

void musicPickHandler(const char *event, const char *data)
{
    byte Command = 0x03;
    byte Parameter1 = 0x00;
    String dataString = String(data);
    byte Parameter2 = dataString.toInt();;
    
    execute_CMD(Command, Parameter1, Parameter2);
}

Credits

Jordy Moors

Jordy Moors

1 project • 7 followers
Student at the FH Aachen, Germany. Studying EE and computer science. Interested in IoT, woodworking and most recently: laser cutting.

Comments