/*
* C++ demo program for controlling LPD6803 LED driver chips via SPI
*
* Copyright 2015 protological.com
* CLI Systems LLC clisystems.com
*
* This software is placed into the public domain and may be
* used for any purpose.  However, this notice must not be changed
* or removed.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/

#include "mbed.h"

Ticker ledtimer;
Ticker statetimer;
DigitalOut myled(LED1);
SPI spi(p5, p6, p7); // mosi, miso, sclk

#include "stdint.h"

// The 5m strip I have is 30 pixels per meter
// in groups of 3, so there are 50 groups of
// 3 to individually control.
#define NUM_PIXELS          50
#define LAST_PIXEL          (NUM_PIXELS-1)

// The timeout in seconds for the demos
#define DEMO_TIMEOUT_SEC    10

// Start the demo at this number
#define DEMO_START_NUMER    3

// RAM array storing the color for
// each pixel in the strip
uint16_t colors[NUM_PIXELS];

int state=DEMO_START_NUMER;

// ISR for switch timer
void stateincrement()
{
    static int count=0;
    count+=1;
    // Add 1 to the state every time we hi
    // the timeout limit.  This changes which
    // demo we do every X seconds
    if(count>DEMO_TIMEOUT_SEC)
    {    
        state+=1;
        count=0;
    }
}

// ISR for timer led driver timer
void ledwrite()
{
    int x;
    // Reset the chain
    for(x=0;x<8;x++) spi.write(0x00);
    // Write each pixel
    for(x=0;x<NUM_PIXELS;x++)
    {
        spi.write((colors[x]>>8)|0x80);
        spi.write(colors[x]);
    }
    
    return;
}
// Take the colors and subtract 1.  This was
// to test if we could 'dim' the color.  The
// lower levels are bigger luminosity steps
// so a luminosity to brightness correction
// for the human eye is really needed.
// 
// Call like this:
// for(int x=0;x<NUM_PIXELS;x++)
//     stepdown(x);
//
void stepdown(int x)
{
    uint16_t tmp16;
    uint16_t c;
    if(x>=NUM_PIXELS|| x<0) return;
    tmp16 = colors[x];
    // Step down color
    c = tmp16&0x001F;
    if(c>0) c -=1;
    tmp16 = (tmp16&0xFFE0)|c;
    // Step down color
    c = (tmp16>>5)&0x001F;
    if(c>0)c -=1;
    tmp16 = (tmp16&0xFC1F)|(c<<5);
    // Step down color
    c = (tmp16>>10)&0x001F;
    if(c>0)c -=1;
    tmp16 = (tmp16&0x83FF)|(c<<10);
    colors[x]=tmp16;
    return;
}

// Given RGB values, make a 16bit value of 5 byte colors
// RGB values are 0x00-0x1F (0-31)
uint16_t color(uint8_t r, uint8_t g, uint8_t b)
{
    int16_t tmp16=0;
    tmp16|=(g&0x1F);
    tmp16<<=5;
    tmp16|=(r&0x1F);
    tmp16<<=5;
    tmp16|=(b&0x1F);
    return tmp16;
}
// Clear all pixel data
void clearall()
{
    memset(colors,0,sizeof(colors));   
}

// Set all pixels to the same color
// RGB values are 0x00-0x1F (0-31)
void setcolorall(uint8_t r, uint8_t g, uint8_t b)
{
    int16_t tmp16=0;
    tmp16|=(g&0x1F);
    tmp16<<=5;
    tmp16|=(r&0x1F);
    tmp16<<=5;
    tmp16|=(b&0x1F);
    for(int x=0;x<NUM_PIXELS;x++)
        colors[x]=tmp16;
    return;
}

// Set pixel X to the RGB color
// RGB values are 0x00-0x1F (0-31)
void setcolor(int x, uint8_t r, uint8_t g, uint8_t b)
{
    uint16_t tmp16=0;
    if(x>=NUM_PIXELS|| x<0) return;
    tmp16|=(g&0x1F);
    tmp16<<=5;
    tmp16|=(r&0x1F);
    tmp16<<=5;
    tmp16|=(b&0x1F);
    colors[x]=tmp16;
}

// Alternate Red, Green, Blue all the way down
// the LED strip
void colortest()
{
    uint16_t red,green,blue;
    red = color(0x1F,0x00,0x00);
    green = color(0x00,0x1F,0x00);
    blue= color(0x00,0x00,0x1F);
    
    for(int x=0;x<NUM_PIXELS;x+=3)
    {
        colors[x]=red;   
        colors[x+1]=green;
        colors[x+2]=blue;
    }
    
    return;
}

// Shift pixels by one space.  true is 'right'
// false is 'left'.
void shift(bool right)
{
    if(right)
    {
        colors[0]=0;
        for(int x=LAST_PIXEL;x>0;x--)
            colors[x]=colors[x-1];
    }else{
        colors[LAST_PIXEL]=0;
        for(int x=0;x<NUM_PIXELS;x++)
            colors[x]=colors[x+1];
    }
    return;
}

// DEMOS!!!
// ----------------------------
// Fade from color to color by adjusting R, G, B buy different steps
void demo1(int mystate)
{
    static int8_t r,g,b;
    static int8_t rs,gs,bs;
    
    // Start with these colors
    r=0x0F;
    g=0x10;
    b=0x03;
    
    setcolorall(r, g, b);
    
    // These are the steps each time
    rs = -1;
    gs = 1;
    bs = 1;
    
    while(state==mystate)
    {
        // Add the step
        r += rs;
        g += gs;
        b += bs;
        // If we hit the limit, reverse the step
        if(r>=0x1F||r<0) rs=rs*-1;
        if(g>=0x1F||g<0) gs=gs*-1;
        if(b>=0x1F||b<0) bs=bs*-1;
        // Make sure we don't go over or under        
        if(r<=0) r=0;
        if(g<0) g=0;
        if(b<0) b=0;
        if(r>=0x1f){ r=0x1f; r-=2; }
        if(g>=0x1f) g=0x1f;
        if(b>=0x1f){ b=0x1f; b-=4; }
        
        // Set the color for all LEDs
        setcolorall(r, g, b);
        
        // A delay between steps 0.1sec        
        wait(0.1);
    }
    return;
}

// Set the strip to alternate R-G-B then slide it down
void demo2(int mystate)
{
    //
    int x;
    while(state==mystate)
    {
        colortest();
        wait(1.0);
        for(x=0;x<NUM_PIXELS;x++)
        {
            // shift 'right'
            shift(true);
            wait(0.05);
        }
        wait(1.0);
    }
}

// Pixel 0 and 1 are Red-Yellow-Green then shoot down the strip
void demo3(int mystate)
{
    int x;
    while(state==mystate)
    {
        clearall();
        wait(1.0);
        setcolor(0,0x1F,0x00,0x00);
        setcolor(1,0x1F,0x00,0x00);
        wait(0.5);
        setcolor(0,0xF,0x0F,0x00);
        setcolor(1,0xF,0x0F,0x00);
        wait(0.5);
        setcolor(0,0x00,0x1F,0x00);
        setcolor(1,0x00,0x1F,0x00);
        wait(0.5);
        for(x=0;x<NUM_PIXELS;x++)
        {
            shift(true);
            wait(0.01);
        }
        wait(1.0);
    }
}

// Make your demo here
void yourdemo(int mystate)
{
    while(state==mystate){   // Only run when this is our state
    //while(1){                // Run forever
    setcolorall(0x00, 0x1F, 0x00);
    wait(1.0);
    setcolorall(0x1F, 0x00, 0x00);
    wait(1.0);
    }
    
    return;
}

int main()
{
    // Create the 10ms timer for writing the LEDs
    ledtimer.attach(&ledwrite, 0.01);
    // Create the 1 sec timer for the state switch
    statetimer.attach(&stateincrement, 1.0);
 
    // Setup the spi for 8 bit data, mode = 0
    // with a 500KHz clock rate
    /*
    Mode 0 CPOL-0 CPHA-0: CLK idle low,Rising edge latch
    Mode 1 CPOL-0 CPHA-1: CLK idle low, Falling edge latch
    Mode 2 CPOL-1 CPHA-0: CLK idle high,Rising edge latch
    Mode 3 CPOL-1 CPHA-1: CLK idle high, Falling edge latch
    */
    spi.format(8,0);
    spi.frequency(500000);
    
    // All pixels off
    clearall();
    
    // Some testing examples
    // Set pixel 1 red, 2 green, 3 blue, skip others, set last to Magenta
    //setcolor(0,0x1F,0x00,0x00);
    //setcolor(1,0x1F,0x00,0x00);
    //setcolor(2,0x00,0x00,0x1F);
    //setcolor(LAST_PIXEL,0x1F,0x00,0x1F);
    
    // Set alternating R,G,B
    //colortest();
    
    // Set all White
    //setcolorall(0x1F, 0x1F, 0x1F);
    
    //yourdemo(0);
    
    // Run through the demos based on the current state
    while(1)
    {
        switch(state){
        case 0: demo1(state);
        case 1: demo2(state);
        case 2: demo3(state);
        case 3: yourdemo(state);

        default: state=0; break;
        }
        // If you add a demo, make this % max number+1
        state=state%4;
    }
    
    // End
    return 0;
}

//eof
