John Rattray / Mbed 2 deprecated Spark

Dependencies:   BLE_API mbed nRF51822

Files at this revision

API Documentation at this revision

Comitter:
omnipharious
Date:
Wed Oct 03 21:49:43 2018 +0000
Commit message:
1st commit

Changed in this revision

BLE_API.lib Show annotated file Show diff for this revision Revisions of this file
DotStar.cpp Show annotated file Show diff for this revision Revisions of this file
DotStar.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
nRF51822.lib Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 1538004cf391 BLE_API.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/BLE_API.lib	Wed Oct 03 21:49:43 2018 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/teams/Bluetooth-Low-Energy/code/BLE_API/#a782d73aae68
diff -r 000000000000 -r 1538004cf391 DotStar.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/DotStar.cpp	Wed Oct 03 21:49:43 2018 +0000
@@ -0,0 +1,129 @@
+#include "DotStar.h"
+
+SPI SPI1(P0_5,NC,P0_4);
+
+// Constructor for 'soft' (bitbang) SPI -- any two pins can be used
+DotStar::DotStar(uint16_t n, uint8_t data, uint8_t clock) :
+ dataPin(data), clockPin(clock), brightness(0), pixels(NULL)
+{
+  updateLength(n);
+}
+
+void DotStar::begin(void) { // Initialize SPI
+    //SPI1.begin(clockPin, dataPin, P0_29);//SCK, MOSI, MISO
+    //SPI1.transfer(0xFF);
+}
+
+void DotStar::updateLength(uint16_t n) {
+  if(pixels) free(pixels);
+  uint16_t bytes = n * 3;              // COLOR: 3 bytes/pixel
+  if((pixels = (uint8_t *)malloc(bytes))) {
+    numLEDs = n;
+    clear();
+  } else {
+    numLEDs = 0;
+  }
+}
+
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+void DotStar::show(void) {
+
+    if(!pixels) return;
+    
+    
+    uint8_t *ptr = pixels, i;            // -> LED data
+    uint16_t n   = numLEDs;              // Counter
+    uint16_t b16 = (uint16_t)brightness; // Type-convert for fixed-point math
+    
+    // Soft (bitbang) SPI
+
+    for(i=0; i<4; i++) SPI1.write(0x00);    // Start-frame marker
+    if(brightness) {                     // Scale pixel brightness on output
+      do {                               // For each pixel...
+        SPI1.write(0xFF);                //  Pixel start
+        for(i=0; i<3; i++) SPI1.write((*ptr++ * b16) >> 8); // Scale, write
+      } while(--n);
+    } else {                             // Full brightness (no scaling)
+      do {                               // For each pixel...
+        SPI1.write(0xFF);                //  Pixel start
+        for(i=0; i<3; i++) SPI1.write(*ptr++); // R,G,B
+      } while(--n);
+    }
+    //Remove end-frame below if last led goes all white
+    //for(i=0; i<4; i++) SPI1.write(0xFF); // End-frame marker (see note above)
+    
+}
+
+
+void DotStar::clear() { // Write 0s (off) to full pixel buffer
+  memset(pixels, 0, numLEDs * 3);                   // COLOR: 3 bytes/pixel
+}
+
+// Set pixel color, separate R,G,B values (0-255 ea.)
+void DotStar::setPixelColor(
+ uint16_t n, uint8_t r, uint8_t g, uint8_t b) {
+  if(n < numLEDs) {
+    uint8_t *p = &pixels[n * 3];
+    p[0] = r;
+    p[1] = g;
+    p[2] = b;
+    //SPI1.transfer(0xFF);
+  }
+}
+
+// Set pixel color, 'packed' RGB value (0x000000 - 0xFFFFFF)
+void DotStar::setPixelColor(uint16_t n, uint32_t c) {
+  if(n < numLEDs) {
+    uint8_t *p = &pixels[n * 3];
+    p[0] = (uint8_t)(c >> 16);
+    p[1] = (uint8_t)(c >>  8);
+    p[2] = (uint8_t)c;
+  }
+}
+
+// Convert separate R,G,B to packed value
+uint32_t DotStar::Color(uint8_t r, uint8_t g, uint8_t b) {
+  return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
+}
+
+// Read color from previously-set pixel, returns packed RGB value.
+uint32_t DotStar::getPixelColor(uint16_t n) const {
+  if(n >= numLEDs) return 0;
+  uint8_t *p = &pixels[n * 3];
+  return ((uint32_t)p[0] << 16) |
+         ((uint32_t)p[1] <<  8) |
+          (uint32_t)p[2];
+}
+
+uint16_t DotStar::numPixels(void) { // Ret. strip length
+  return numLEDs;
+}
+
+// Set global strip brightness.  This does not have an immediate effect;
+// must be followed by a call to show().  Not a fan of this...for various
+// reasons I think it's better handled in one's sketch, but it's here for
+// parity with the NeoPixel library.  Good news is that brightness setting
+// in this library is 'non destructive' -- it's applied as color data is
+// being issued to the strip, not during setPixel(), and also means that
+// getPixelColor() returns the exact value originally stored.
+void DotStar::setBrightness(uint8_t b) {
+  // Stored brightness value is different than what's passed.  This
+  // optimizes the actual scaling math later, allowing a fast 8x8-bit
+  // multiply and taking the MSB.  'brightness' is a uint8_t, adding 1
+  // here may (intentionally) roll over...so 0 = max brightness (color
+  // values are interpreted literally; no scaling), 1 = min brightness
+  // (off), 255 = just below max brightness.
+  brightness = b + 1;
+}
+
+uint8_t DotStar::getBrightness(void) const {
+  return brightness - 1; // Reverse above operation
+}
+
+// Return pointer to the library's pixel data buffer.  Use carefully,
+// much opportunity for mayhem.  It's mostly for code that needs fast
+// transfers, e.g. SD card to LEDs.  Color data is in BGR order.
+uint8_t *DotStar::getPixels(void) const {
+  return pixels;
+}
\ No newline at end of file
diff -r 000000000000 -r 1538004cf391 DotStar.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/DotStar.h	Wed Oct 03 21:49:43 2018 +0000
@@ -0,0 +1,46 @@
+#ifndef _DOT_STAR_H_
+#define _DOT_STAR_H_
+
+#include "mbed.h"
+
+class DotStar
+{
+    public:
+        
+        DotStar(uint16_t n, uint8_t d, uint8_t c);
+        
+        void begin();                           // Prime pins/SPI for output
+        void clear();                                // Set all pixel data to zero
+        void setBrightness(uint8_t);                 // Set global brightness 0-255
+        void setPixelColor(uint16_t n, uint32_t c);
+        void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b);
+        void show(void);                             // Issue color data to strip
+        void updatePins(void);                       // Change pin assignments (HW)
+        void updatePins(uint8_t d, uint8_t c);       // Change pin assignments (SW)
+        void updateLength(uint16_t n);               // Change length
+        uint32_t
+            Color(uint8_t r, uint8_t g, uint8_t b), // R,G,B to 32-bit color
+            getPixelColor(uint16_t n) const;        // Return 32-bit pixel color
+        uint16_t
+            numPixels(void);                        // Return number of pixels
+        uint8_t
+            getBrightness(void) const,              // Return global brightness
+            *getPixels(void) const,                  // Return pixel data pointer
+            sine8(uint8_t) const,
+            gamma8(uint8_t) const;
+        
+        
+    private:
+        uint16_t
+            numLEDs;                                // Number of pixels
+        uint8_t
+            dataPin,                                // If soft SPI, data pin #
+            clockPin,                               // If soft SPI, clock pin #
+            brightness,                             // Global brightness setting
+           *pixels,                                 // LED RGB values (3 bytes ea.)
+            rOffset,                                // Index of red in 3-byte pixel
+            gOffset,                                // Index of green byte
+            bOffset;                                // Index of blue byte
+};
+
+#endif
\ No newline at end of file
diff -r 000000000000 -r 1538004cf391 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Oct 03 21:49:43 2018 +0000
@@ -0,0 +1,830 @@
+/*
+
+Copyright (c) 2012-2014 RedBearLab
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
+and associated documentation files (the "Software"), to deal in the Software without restriction, 
+including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
+and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
+subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include "DotStar.h"
+#include "BLE.h"
+#include "mbed.h"
+#include "pstorage.h"
+#include "nrf_error.h"
+
+#define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
+#define BLE_UUID_TX_CHARACTERISTIC       0x0002 /**< The UUID of the TX Characteristic. */
+#define BLE_UUIDS_RX_CHARACTERISTIC      0x0003 /**< The UUID of the RX Characteristic. */
+
+#define DATAPIN 0
+#define CLOCKPIN 0
+
+#define TXRX_BUF_LEN                20
+
+#define NUMPIXELS                   4
+#define NAMELENGTH                  8
+#define NAMEBLOCK                   0
+#define PARAMSBLOCK                 8
+#define PARAMSLENGTH                16
+#define ELEMSLENGTH                 19
+#define ELEMSBLOCK                  24
+
+#define BLOCKSIZE                   100
+
+DotStar         strip = DotStar(NUMPIXELS, DATAPIN, CLOCKPIN);
+BLE             ble;
+Serial          serial(USBTX, USBRX); // tx, rx
+
+uint8_t DEFAULTNAME[NAMELENGTH] = {'b','e','t','a',0,0,0,0};
+uint8_t elements[ELEMSLENGTH] = {0,};
+uint8_t parameters[PARAMSLENGTH] = {2,5,'4',1,0,1,0,0,'F','F','F','F',4,0,0,0};
+uint8_t masterMode[12];
+
+Gap::AddressType_t type;
+Gap::Address_t address;
+uint32_t peerColor1,peerColor2,peerColor3;
+int location;
+
+/*COLORS*/
+uint32_t RED = 0x0000FF;
+uint32_t LIME = 0x00FF00;
+uint32_t YELLOW  = 0x00FFFF;
+uint32_t BLUE = 0xFF0000;
+uint32_t MAGENTA = 0xFF00FF;
+uint32_t CYAN = 0xFFFF00;
+uint32_t WHITE = 0xFFFFFF;
+uint32_t ORANGE = 0x0055FF;
+uint32_t FUSCIA = 0x5500FF;
+uint32_t WATER = 0xFF5500;
+uint32_t VIOLET = 0xFF0055;
+uint32_t LIGHTGREEN = 0x00FF55;
+uint32_t SEAFOAM = 0x55FF00;
+uint32_t ROSEGOLD = 0x5555FF;
+uint32_t LIGHTPURPLE = 0xFF5555;
+
+uint32_t retval;
+pstorage_handle_t handle;
+bool readvertise = false;
+
+int      head, tail; // Index of first 'on' and 'off' pixels
+uint32_t color = 0xFFFF00;      // 'On' color (starts white)
+uint32_t newColor = 0xFFFF00;
+char     mode = '4'; //starts solid
+double   brightness = 0, MAX = 10, speed = 640;
+double   duration = .06;
+int      direction = 1;
+double   step = 0, total = 300;
+uint32_t c2 = MAGENTA, temp;
+uint8_t everything[44];
+bool synergy = false;
+int tick = 0;
+bool resetTick = false;
+uint8_t master = 0;
+uint8_t showNum = 0;
+int waterfallMax = 640, waterfallCounter = 0;
+uint8_t threshold = 4;
+bool showColor = false;
+uint32_t deviceColor;
+
+uint8_t random = false, advertise = true, length = 5;
+
+uint8_t input[8] = {0,};
+uint8_t eventID = 1;
+
+uint32_t colors [15] = {WHITE,CYAN,BLUE,LIME,RED,MAGENTA,YELLOW,ORANGE,FUSCIA,WATER,VIOLET,LIGHTGREEN,SEAFOAM,ROSEGOLD,LIGHTPURPLE};
+uint8_t  j = 0;
+
+
+// The Nordic UART Service
+static const uint8_t uart_base_uuid[] = {0x71, 0x3D, 0, 0, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
+static const uint8_t uart_tx_uuid[]   = {0x71, 0x3D, 0, 3, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
+static const uint8_t uart_rx_uuid[]   = {0x71, 0x3D, 0, 2, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
+static const uint8_t uart_base_uuid_rev[] = {0x1E, 0x94, 0x8D, 0xF1, 0x48, 0x31, 0x94, 0xBA, 0x75, 0x4C, 0x3E, 0x50, 0, 0, 0x3D, 0x71};
+
+
+uint8_t txPayload[TXRX_BUF_LEN] = {0,};
+uint8_t rxPayload[TXRX_BUF_LEN] = {0,};
+
+GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
+                                      
+GattCharacteristic  rxCharacteristic (uart_rx_uuid, rxPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
+                                      
+GattCharacteristic *uartChars[] = {&txCharacteristic, &rxCharacteristic};
+
+GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));
+
+
+void sendMsg(uint8_t *str, int length){
+     ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), str, length);    
+}
+
+
+/* ==================================================================================================================================================
+**
+** CLEAR PROGRAM MEMORY
+**
+   ==================================================================================================================================================*/
+
+// Request clearing of one block where block size is 16 bytes.
+void ClearMemory() 
+{
+    retval = pstorage_clear(&handle, BLOCKSIZE);
+    if (retval == NRF_SUCCESS)
+    {
+        // Clear successfully requested. Wait for operation result.
+        //serial.printf("Clear successfully performed.\r\n");
+    }
+    else
+    {
+        // Failed to request clear, take corrective action.
+        //serial.printf("Clear unsuccessfully performed.\r\n");
+    }
+}
+
+/* ==================================================================================================================================================
+**
+** STORING DATA INTO MEMORY FROM PROGRAM SPACE
+**
+** ==================================================================================================================================================*/
+
+// Store the name, device parameters, and elements 
+void StoreEverything(uint8_t *params)
+{
+    retval = pstorage_store(&handle, params, 44, 0); //store new name in block 0 with an offset of 16
+    if (retval == NRF_SUCCESS)
+    {
+       //serial.printf("STORE Everything: %02x:%02x:%02x:%02x - %02x:%02x:%02x:%02x \r\n", params[0],params[1],params[2],params[3],params[4],params[5],params[6],params[7]);
+       //serial.printf("Everything Store successfully requested. Wait for operation result.\r\n");
+    }
+    else {//serial.printf("Failed to request store, take corrective action.\r\n");
+    }
+}
+
+/* ==================================================================================================================================================
+**
+** LOADING DATA INTO PROGRAM SPACE FROM MEMORY
+**
+** ==================================================================================================================================================*/
+
+//Load the name from memory into input address
+void LoadName(uint8_t *name)
+{
+    retval = pstorage_load(name, &handle, NAMELENGTH, NAMEBLOCK); 
+    if (retval == NRF_SUCCESS)
+    {
+        //serial.printf("Loading Advertising Name\n");         
+    }
+    else {
+       //serial.printf("Failed to load, take corrective action.\r\n"); 
+    }
+    //serial.printf("LOAD: %02x:%02x:%02x:%02x - %02x:%02x:%02x:%02x \r\n",name[0],name[1],name[2],name[3], name[4],name[5],name[6],name[7]); 
+}
+
+//Load the name from memory into input address
+void LoadParams(uint8_t *params)
+{
+    retval = pstorage_load(params, &handle, PARAMSLENGTH, PARAMSBLOCK); 
+    if (retval == NRF_SUCCESS)
+    {
+        //serial.printf("Loading Parameters\n");         
+    }
+    else {
+       //serial.printf("Failed to load, take corrective action.\r\n"); 
+    }
+    //serial.printf("LOAD: %02x:%02x:%02x:%02x - %02x:%02x:%02x:%02x \r\n",params[0],params[1],params[2],params[3], params[4],params[5],params[6],params[7]); 
+}
+
+//Load the name from memory into input address
+void LoadElements(uint8_t *params)
+{
+    retval = pstorage_load(params, &handle, 20, ELEMSBLOCK); 
+    if (retval == NRF_SUCCESS)
+    {
+    }
+    else {  
+    }
+}
+
+void scanCallback(const Gap::AdvertisementCallbackParams_t *params) {    
+    /*serial.printf("adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
+           params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
+           params->rssi, params->isScanResponse, params->type);
+           
+    serial.printf("\n");
+    for (uint8_t i = 0; i < params->advertisingDataLen; i++) {
+        serial.printf("%c",params->advertisingData[i]);
+    }
+    serial.printf("\n");*/
+           
+          /* // MASTER COMMANDS DETECTED
+           if (!(params->isScanResponse) && params->advertisingData[4] == 0xff && params->advertisingData[5] == 'M' && params->advertisingData[6] == eventID) {
+               memcpy(masterMode,params->advertisingData+7,12);
+           }
+           // OTHER SPARK DETECTED
+           if (params->isScanResponse && params->advertisingData[1] == 0xff && params->advertisingData[2] == 0xAB && params->advertisingData[3] == eventID) {
+            if(advertise) {   
+               uint8_t counter = 0;
+               for (uint8_t i = 4; i < 4+ELEMSLENGTH; i++) {
+                    if(params->advertisingData[i] != 0 && params->advertisingData[i] == elements[i-4]){counter++;}
+                }
+                //serial.printf("There are %d elements in common\n",counter);
+                if(counter>=threshold){
+                    tick = 9600;
+                    //SHIFT COLORS DOWN IF MULTIPLE SYNERGISTIC SPARKS
+                    peerColor3=peerColor2;
+                    peerColor2=peerColor1;
+                
+                    peerColor1 = colors[params->peerAddr[0]%15];              
+                }
+            }
+           } */                      
+}
+
+
+//Handles for Reading and Writing to Flash Memory
+static void cb_handler(pstorage_handle_t  * cllbck_handle,
+                               uint8_t              op_code,
+                               uint32_t             result,
+                               uint8_t            * p_data,
+                               uint32_t             data_len)
+{
+  
+  //serial.printf("Callback handler successful\r\n");  
+  
+  switch(op_code)
+        {
+           case PSTORAGE_CLEAR_OP_CODE:
+               if (result == NRF_SUCCESS)
+               {
+                   //serial.printf("Clear operation successful in Callback\r\n");
+               }
+               else
+               {
+                   //serial.printf("Clear operation failed in Callback\r\n");
+               }
+               break;
+ 
+     
+          case PSTORAGE_LOAD_OP_CODE:
+               if (result == NRF_SUCCESS)
+               {
+                   //serial.printf("Load operation successful in Callback\r\n");                
+               }
+               else
+               {
+                   //serial.printf("Load operation failed in Callback\r\n");
+               }            
+               break;     
+          case PSTORAGE_STORE_OP_CODE:            
+               if (result == NRF_SUCCESS)
+               {
+                   //serial.printf("Store operation successful in Callback\r\n");
+               }
+               else
+               {
+                   //serial.printf("Store operation failed in Callback\r\n");
+               }     
+               if (readvertise) {
+                   readvertise = false;
+                   ble.gap().clearScanResponse();
+                   //Load the data here to ensure that the store command is complete 
+                   uint8_t dest_data[8] = {0,};
+                    LoadName(dest_data);
+                    //Start the advertising process with the new name
+                    ble.clearAdvertisingPayload();
+                    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
+                    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
+                    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
+                                    dest_data, NAMELENGTH);
+                    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
+                        (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid)); 
+                    ble.gap().startAdvertising(); 
+                    ble.gap().startScan(scanCallback);            
+                    if (advertise){                        
+                        uint8_t adv_elements[ELEMSLENGTH+2] = {0xAB,eventID,};
+                        memcpy(adv_elements+2,elements,ELEMSLENGTH);
+                        ble.accumulateScanResponse(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA,adv_elements, sizeof(adv_elements)); 
+                    } else {
+                        uint8_t adv_elements[ELEMSLENGTH+2] = {0xAB,eventID};
+                        ble.accumulateScanResponse(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA,adv_elements, sizeof(adv_elements));
+                    }
+                }
+               break;
+        }
+ 
+}
+
+
+uint8_t char2hex (char nibble1, char nibble2) 
+{
+    uint8_t number = 0;
+    if (nibble1>=48 && nibble1<=57) //MSN(0-9)
+        number = (nibble1-48)*16;
+    else if (nibble1 >= 65 && nibble1 <= 70) //MSN(A-F)
+        number = (nibble1 - 55)*16;
+    if(nibble2>=48 && nibble2<=57)//LSN(0-9)
+        number += (nibble2-48);
+    else if (nibble2 >= 65 && nibble2 <= 70) //LSN(A-F)
+        number += (nibble2 - 55);
+        
+    return number;
+    
+    
+}
+
+bool fade(uint32_t start, uint32_t finish) {
+        
+        bool finished = false;
+        uint8_t b0, b1, g0, g1, r0, r1;
+        double blue,green,red;
+        b0 = (start >> 16);
+        b1 = (finish >> 16);
+        g0 = start >> 8;
+        g1 = finish >> 8;
+        r0 = start;
+        r1 = finish;
+        
+        
+        blue = (b1 - b0)*(step/total)+ b0;
+        green = (g1-g0)*(step/total)+g0;
+        red = (r1-r0)*(step/total)+r0;
+        
+        
+        temp = ((uint32_t) blue<<16)|((uint32_t) green<<8)|(uint32_t) red; 
+        for (uint8_t i = 0; i < NUMPIXELS; i++) {               
+                    strip.setPixelColor(i,temp);
+                  }   
+        strip.show();     
+        if (step+1 <= total)
+        {
+            step++;
+            
+        } else {
+            //color = newColor;
+            step = 0;
+            finished =  true;
+        }
+        return finished;
+}
+
+
+/**
+ * Callback triggered upon a connection event. Needs to halt scanning.
+ */
+void connectionCallback(const Gap::ConnectionCallbackParams_t *params)
+{
+    ble.gap().stopScan(); 
+    masterMode[0] = 0;    
+}
+
+/**
+ * Callback triggered upon a disconnection event. Needs to re-enable advertisements.
+ */
+void disconnectionCallback(Gap::Handle_t gaphandle, Gap::DisconnectionReason_t reason)
+{                  
+    memset(everything, 0, 44);
+    memcpy(everything, input, NAMELENGTH);
+    memcpy(everything+PARAMSBLOCK, parameters, PARAMSLENGTH);
+    memcpy(everything+ELEMSBLOCK,elements,ELEMSLENGTH);
+    //serial.printf("Everything - %c,%c,%c,%c ... %02x:%02x:%02x:%02x\n",everything[0],everything[1],everything[2],everything[3],everything[8],everything[9],everything[10],everything[11]);
+    ClearMemory();
+    readvertise = true;
+    StoreEverything(everything);
+}
+
+
+
+uint32_t ble_advdata_parser(uint8_t type, uint8_t advdata_len, uint8_t *p_advdata, uint8_t *len, uint8_t *p_field_data)
+{
+    uint8_t index=0;
+    uint8_t field_length, field_type;
+    
+    while(index<advdata_len)
+    {
+        field_length = p_advdata[index];
+        field_type   = p_advdata[index+1];
+        if(field_type == type)
+        {
+            memcpy(p_field_data, &p_advdata[index+2], (field_length-1));
+            *len = field_length - 1;
+            return NRF_SUCCESS;
+        }
+        index += field_length + 1;
+    }
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+/**
+ * This Handler controls all information recevied via BT
+ */
+void WrittenHandler(const GattWriteCallbackParams *Handler)
+{   
+    uint8_t buf[TXRX_BUF_LEN];
+    uint16_t bytesRead;
+    
+    if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) 
+    {
+        ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), buf, &bytesRead);
+        memset(txPayload, 0, TXRX_BUF_LEN);
+        memcpy(txPayload, buf, TXRX_BUF_LEN);       
+        }  
+        
+    char command = buf[0];
+    serial.printf("The command is %c\n",command);
+        switch (command) {
+            case 'i': //initialization
+                //serial.printf("Send Data");
+                uint8_t packet1[20];
+                uint8_t packet2[20];
+                memset(packet1,'p', 20);
+                memset(packet2,'e', 20);
+                memcpy(packet1+1, parameters, 19);
+                packet1[13] = threshold;
+                memcpy(packet2+1, elements, 19);
+                sendMsg(packet1,20);
+                sendMsg(packet2,20);
+            break;
+            case '1': //fade
+                mode = '1';
+                parameters[2] = buf[0]; //save this to mode byte
+            break;
+            case '2': //pulse
+                mode = '2';                
+                parameters[2] = buf[0]; //save this to mode byte
+            break;   
+            case '3': //rays
+                mode = '3';
+                parameters[2] = buf[0]; //save this to mode byte
+            break;
+            case '4': //solid
+                mode = '4';                
+                parameters[2] = buf[0]; //save this to mode byte
+            break;
+            case '5': //sparks
+                mode = '5';
+                waterfallCounter = 0;
+                parameters[2] = buf[0]; //save this to mode byte
+            break;
+            case 'b': //change brightness
+                MAX = buf[1]*4;  
+                parameters[0] = buf[1]; 
+            break; 
+            case 's': //change speed
+            {
+                switch(buf[1]) {
+                    case 0: //slow
+                        speed = 960;
+                        duration = .08;
+                    break;
+                    case 1: //medium
+                        speed = 640;
+                        duration = .06;                    
+                    break;
+                    case 2: //fast
+                        speed = 320;
+                        duration = .04;                    
+                    break;
+                    default:
+                } 
+                parameters[3] = buf[1];
+            }                       
+            break;
+            case 'l': //change length
+                length = buf[1];   
+                parameters[1] = buf[1];  
+            break;
+            case 'r': //set random flag
+                random = buf[1];    
+                parameters[4] = buf[1];
+            break;
+            case 'c':
+                //serial.printf("Color Code - %c%c:%c%c:%c%c\n",buf[1],buf[2],buf[3],buf[4],buf[5],buf[6]);
+                
+                uint8_t red = char2hex(buf[1],buf[2]);
+                uint8_t green = char2hex(buf[3],buf[4]);
+                uint8_t blue = char2hex(buf[5],buf[6]); 
+                
+                newColor = ((uint32_t) blue<<16)|((uint32_t) green<<8)|(uint32_t) red;
+                step = 0;
+                
+                parameters[6] = buf[1];
+                parameters[7] = buf[2];
+                parameters[8] = buf[3];
+                parameters[9] = buf[4];
+                parameters[10] = buf[5];
+                parameters[11] = buf[6];
+            break; 
+            case '*':        
+                memset(input, 0, NAMELENGTH);
+                memcpy(input,buf+1,NAMELENGTH);
+            break;
+            case 'a': //set advertising flag
+                advertise = buf[1];  
+                parameters[5] = buf[1];              
+            break;
+            case 'e': //elements
+                memcpy(elements,buf+1,ELEMSLENGTH);
+                //serial.printf("Elements - %d %d %d %d\n",elements[0],elements[1],elements[2],elements[3]);
+            break;
+            case '@': //show device color
+                deviceColor =  colors[address[0]%15];
+                strip.setBrightness(15);
+                step = 0;
+                total = 1200;
+                showColor = true;
+                serial.printf("Show Color\n");
+            break;
+            case '&': //change threshold
+                threshold = buf[1];
+            default:
+        } 
+}
+
+
+
+int main(void)
+{       
+    //Initialize bluetooth module
+    ble.init();
+    
+    /*Initialize Pstorage Module*/
+    retval = pstorage_init();
+    if(retval == NRF_SUCCESS)
+    {
+        //serial.printf("Module initialization successful\r\n");
+         
+        pstorage_module_param_t param;
+         
+        param.block_size  = BLOCKSIZE; 
+        param.block_count = 1; 
+        
+        param.cb = cb_handler;
+
+        retval = pstorage_register(&param, &handle); //register our pstorage and store store address in handle
+        if (retval == NRF_SUCCESS)
+        {
+            //serial.printf("Registration successful.\r\n");
+            //serial.printf("Module id: %u , block: %u \r\n", handle.module_id, handle.block_id);
+        } else {//serial.printf("Failed to register, take corrective action.\r\n");
+        }
+    } else {//serial.printf("Initialization failed, take corrective action.\r\n"); 
+    }
+    
+    LoadElements(elements);
+    if (elements[0] == 255) {
+        memset(elements,0,ELEMSLENGTH);
+    }
+
+    ble.gap().onDisconnection(disconnectionCallback);
+    ble.gap().onConnection(connectionCallback);
+    ble.gattServer().onDataWritten(WrittenHandler);  
+    ble.gattServer().addService(uartService);
+    // set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4
+    ble.gap().setTxPower(-12); // tx power to -20
+    // set adv_interval, 100ms in multiples of 0.625ms.
+    ble.gap().setAdvertisingInterval(100);
+    
+    ble.gap().setScanParams(1000,150,0,true); // (scan interval, scan time,timeout,send scan requests)
+    
+    
+    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
+    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); 
+    
+    //Load Name
+    uint8_t dest_data[NAMELENGTH] = {0,};
+    LoadName(dest_data);            
+                                
+    //Advertise the Loaded Name
+    if (dest_data[0] != 255)   {        
+        ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
+                    dest_data, NAMELENGTH);           
+    } else { //This is first time powered on so initialize default name and advertise
+        //serial.printf("Factory Condition .... Loading Default Name\n");
+        ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
+                    DEFAULTNAME, NAMELENGTH);
+    }
+    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
+                    (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid)); 
+   
+    
+    
+    
+    uint8_t temp_parameters[PARAMSLENGTH];
+    //Load Parameters
+    LoadParams(temp_parameters);
+    if (temp_parameters[0] != 255)
+    {
+        memcpy(parameters,temp_parameters,PARAMSLENGTH);
+        MAX = parameters[0]*4;
+        length = parameters[1];
+        mode = parameters[2];
+        switch(parameters[3]) {
+            case 0: //slow
+                speed = 960;
+                duration = .08;
+            break;
+            case 1: //medium
+                speed = 640;
+                duration = .06;
+            break;
+            case 2: //fast
+                speed = 320;
+                duration = .04;
+            break;
+            default:
+        }
+        random = parameters[4];
+        advertise = parameters[5];
+        
+        uint8_t red = char2hex(parameters[6],parameters[7]);
+        uint8_t green = char2hex(parameters[8],parameters[9]);
+        uint8_t blue = char2hex(parameters[10],parameters[11]); 
+        
+        newColor = ((uint32_t) blue<<16)|((uint32_t) green<<8)|(uint32_t) red;
+    }    
+    
+    ble.gap().startAdvertising();  
+    ble.gap().startScan(scanCallback);  
+    if (advertise){        
+        uint8_t adv_elements[ELEMSLENGTH+2] = {0xAB,eventID};
+        memcpy(adv_elements+2,elements,ELEMSLENGTH);
+        ble.accumulateScanResponse(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA,adv_elements, sizeof(adv_elements)); 
+    }  
+
+    strip.begin();
+    
+    ble.gap().getAddress(&type,address);
+    
+    while(1) { 
+          if (showColor)
+          {
+            total = 2400;
+            strip.setBrightness(15);
+            if (fade(deviceColor,deviceColor))
+                showColor = false;
+          }
+          else if (masterMode[0]) {
+            strip.setBrightness(masterMode[1]);
+            total = 1200;
+            if (masterMode[2]) {
+                if (elements[masterMode[3]])
+                    fade(0,colors[elements[masterMode[3]]%15]);
+                else
+                    fade(0,0);
+            } 
+            else {
+                uint8_t red = char2hex(masterMode[4],masterMode[5]);
+                uint8_t green = char2hex(masterMode[6],masterMode[7]);
+                uint8_t blue = char2hex(masterMode[8],masterMode[9]);                                 
+                uint32_t colour = ((uint32_t) blue<<16)|((uint32_t) green<<8)|(uint32_t) red;
+                
+                if(masterMode[3]) { //blink -1  or solid - 0
+                    fade(0,colour);
+                }
+                else{
+                    fade(colour,colour); 
+                }               
+            }                 
+          }
+          else if(tick>0){            
+            tick--;
+            
+            strip.setPixelColor(0,colors[address[0]%15]);
+            strip.setPixelColor(1,peerColor3);            
+            strip.setPixelColor(2,peerColor2);
+            strip.setPixelColor(3,peerColor1);
+            
+            if (tick == 0)
+            {
+               peerColor1 = 0;
+               peerColor2 = 0;
+               peerColor3 = 0;
+            }
+            
+            strip.setBrightness(15);            
+            strip.show();                      
+          } else {
+          switch(mode) {
+            case '1': //color fade
+            {         
+              brightness = MAX;
+              total = 1200;      
+              if(fade(color, c2)){
+                j = (j+1)%7;  
+                color = c2;               
+                c2 = colors[j];
+                }                                         
+            }            
+            break;
+            case '2': //pulse
+              {             
+                    if (brightness >= MAX){direction = -1;}
+                    else if(brightness <= 0){
+                        if (random) {
+                            j = (j+1)%15;
+                            color = colors[j];
+                        } else {
+                            color = newColor;
+                        }
+                        direction = 1;}
+                  
+                    if (MAX == 0)
+                        brightness = 0;
+                    else
+                        brightness += (MAX/speed)*direction;                                    
+                    for (uint8_t i = 0; i < NUMPIXELS; i++) {
+                        strip.setPixelColor(i, color);
+                    }                   
+              }
+            break;
+            case '3': //rays setup
+            {
+                tail = -NUMPIXELS*2;
+                head = 0;
+                mode = '[';
+            }
+            break;
+            case '[': //rays
+              {    
+                  brightness = MAX;     
+                  strip.setPixelColor(head, color); // 'On' pixel at head
+                  strip.setPixelColor(tail, 0);     // 'Off' pixel at tail            
+                
+                  if(++head >= NUMPIXELS*4) {         // Increment head index.  Off end of strip?
+                    head = 0;    
+                    if (random) {
+                        j = (j+1)%15;
+                        color = colors[j];
+                    } else {color = newColor;}
+                  }
+                  if(++tail >= NUMPIXELS*4) tail = 0; // Increment, reset tail index
+                  wait(duration);                  
+              }
+              break;            
+              case '4': //solid
+              {
+                  brightness = MAX;
+                  total = 300;
+                  if(fade(color, newColor))
+                    color = newColor;
+              }
+              break;
+              case '5': //waterfall
+              {
+                    brightness = MAX;                                    
+                                        
+                    if((waterfallCounter)==speed*4) {
+                        strip.setPixelColor(0,0);
+                        strip.setPixelColor(1,color);
+                        strip.setPixelColor(2,color);
+                        strip.setPixelColor(3,0);
+                    } else if ((waterfallCounter)==speed*3) {
+                        strip.setPixelColor(0,color);
+                        strip.setPixelColor(1,color);
+                        strip.setPixelColor(2,color);
+                        strip.setPixelColor(3,color);                           
+                    } else if ((waterfallCounter)==speed*2) {
+                        strip.setPixelColor(0,color);
+                        strip.setPixelColor(1,0);
+                        strip.setPixelColor(2,0);
+                        strip.setPixelColor(3,color);
+                    } else if ((waterfallCounter)==speed) {
+                        strip.setPixelColor(0,0);
+                        strip.setPixelColor(1,0);
+                        strip.setPixelColor(2,0);
+                        strip.setPixelColor(3,0);
+                    }
+                    if (--waterfallCounter<=0) {
+                        if (random) {
+                            j = (j+1)%15;
+                            color = colors[j];
+                        } else {
+                            color = newColor;
+                        }
+                        waterfallCounter = speed*4;
+                    }
+              }
+              break;              
+              default:
+              {
+                 
+              }
+              break;
+          }
+          strip.setBrightness(brightness);
+          strip.show();
+        } 
+    }  
+}
\ No newline at end of file
diff -r 000000000000 -r 1538004cf391 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Wed Oct 03 21:49:43 2018 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed/builds/994bdf8177cb
\ No newline at end of file
diff -r 000000000000 -r 1538004cf391 nRF51822.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nRF51822.lib	Wed Oct 03 21:49:43 2018 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/teams/Nordic-Semiconductor/code/nRF51822/#a9ed252089c4