Code to run the controller for the wifi robot

Dependencies:   ESP8266Interface HTTPClient-SSL WebSocketClient mbed-rtos mbed

Files at this revision

API Documentation at this revision

Comitter:
anewton8
Date:
Tue Oct 20 17:35:45 2015 +0000
Commit message:
Finished controller code. Tuesday October 20th, 2015

Changed in this revision

ESP8266Interface.lib Show annotated file Show diff for this revision Revisions of this file
HTTPClient-SSL.lib Show annotated file Show diff for this revision Revisions of this file
WebSocketClient.lib 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-rtos.lib 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
mpr121.cpp Show annotated file Show diff for this revision Revisions of this file
mpr121.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r e68e51f935d1 ESP8266Interface.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ESP8266Interface.lib	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,1 @@
+http://developer.mbed.org/teams/ESP8266/code/ESP8266Interface/#1f4dd0e91837
diff -r 000000000000 -r e68e51f935d1 HTTPClient-SSL.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPClient-SSL.lib	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,1 @@
+http://developer.mbed.org/users/sarahmarshy/code/HTTPClient-SSL/#a18a06b000f3
diff -r 000000000000 -r e68e51f935d1 WebSocketClient.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/WebSocketClient.lib	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,1 @@
+http://developer.mbed.org/users/samux/code/WebSocketClient/#4567996414a5
diff -r 000000000000 -r e68e51f935d1 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,414 @@
+#include "mbed.h"
+
+#define USE_CAP 1
+#define USE_WIFI_BASIC 0
+#define USE_WIFI_ADVANCED 1
+
+DigitalOut led1(LED1);
+DigitalOut led2(LED2);
+DigitalOut led3(LED3);
+DigitalOut led4(LED4);
+Serial pc(USBTX, USBRX); // tx, rx
+
+#if USE_CAP
+#include <mpr121.h>
+// Create the interrupt receiver object on pin 26
+InterruptIn interrupt(p26);
+// Setup the i2c bus on pins 9 and 10
+I2C i2c(p9, p10);
+// Setup the Mpr121:
+// constructor(i2c object, i2c address of the mpr121)
+Mpr121 mpr121(&i2c, Mpr121::ADD_VSS);
+
+void fallInterrupt();
+#endif
+
+// WiFi stuff
+#if USE_WIFI_BASIC
+Serial esp(p28, p27); // tx, rx
+DigitalOut reset(p29);
+Timer t;
+
+char ssid[32] = "GTother";     // enter WiFi router ssid inside the quotes
+char pwd [32] = "GeorgeP@1927"; // enter WiFi router password inside the quotes
+int  count,ended,timeout;
+char buf[1024];
+char snd[255];
+
+void SendCMD(), getreply(), ESPconfig(), ESPsetbaudrate();
+
+void basicWifiSetup();
+void basicWifiLoop();
+#endif
+
+#if USE_WIFI_ADVANCED
+#include "HTTPClient.h"
+#include "ESP8266Interface.h"
+#include "TCPSocketConnection.h"
+#include "Websocket.h"
+#include "rtos.h"
+
+const char *httpDest = "http://143.215.98.59/";
+ESP8266Interface wifi(p28, p27, p29, "GTother", "GeorgeP@1927", 115200); // TX,RX,Reset,SSID,Password,Baud
+
+HTTPClient http;
+char responseBuffer[512];
+
+void advWifiSetup();
+void advWifiTest();
+void advWifiSendCommand(int val);
+
+Mutex advWifiMutex;
+void advWifiThread(void const *args);
+int gKeycode = -1;
+bool gKeycodeLatch = false;
+#endif
+
+int main() {
+    pc.printf("====\n\r===\n\r===\n\r=== Reset ====\n\r====\n\r\n\r");
+    
+    led1 = led2 = led3 = led4 = 0;
+    
+    #if USE_CAP
+    interrupt.fall(&fallInterrupt);
+    interrupt.mode(PullUp);
+    #endif
+
+    // Wifi setup
+    #if USE_WIFI_BASIC
+    basicWifiSetup();
+    #endif
+    
+    #if USE_WIFI_ADVANCED
+    advWifiSetup();
+    Thread t2(advWifiThread);
+    #endif
+
+    while(1) {
+        #if USE_WIFI_BASIC
+        basicWifiLoop();
+        #endif
+        
+        #if USE_WIFI_ADVANCED
+        //for (int i = 0; i < 2; i++) {
+        //    advWifiSendCommand(i);
+        //}
+        #endif
+    }
+}
+
+#if USE_CAP
+// Light up LEDs with capacitive touch interrupt stuff
+void fallInterrupt() {
+    int key_code = 0;
+    int i = 0;
+    
+    // Address 0x00 has touch status of 0 - 7 (7, 6, 5, 4, 3, 2, 1, 0)
+    // Address 0x01 has touch status of 8 - 11 (X,X,X,X, 11, 10, 9, 8)
+    // Combined value is a bitfield type thing
+    int value = mpr121.read(0x00);
+    value += mpr121.read(0x01) << 8;
+    
+    // Takes highest set key and uses it
+    int bits[12];
+    for (i = 0; i < 12; i++) {
+        bits[i] = (value >> i) & 0x01;
+        if (bits[i] == 1) {
+            key_code = i + 1;
+        }
+    }
+    led4 = (key_code >> 0) & 0x01;
+    led3 = (key_code >> 1) & 0x01;
+    led2 = (key_code >> 2) & 0x01;
+    led1 = (key_code >> 3) & 0x01;
+
+    #if USE_WIFI_ADVANCED
+    gKeycode = key_code - 1;
+    gKeycodeLatch = true;
+    #endif
+}
+#endif
+
+#if USE_WIFI_BASIC
+// Sets new ESP8266 baurate, change the esp.baud(xxxxx) to match your new setting once this has been executed
+void ESPsetbaudrate()
+{
+    strcpy(snd, "AT+CIOBAUD=115200\r\n");   // change the numeric value to the required baudrate
+    SendCMD();
+}
+ 
+//  +++++++++++++++++++++++++++++++++ This is for ESP8266 config only, run this once to set up the ESP8266 +++++++++++++++
+void ESPconfig()
+{
+    wait(5);
+    strcpy(snd,"AT\r\n");
+    SendCMD();
+    wait(1);
+    strcpy(snd,"AT\r\n");
+    SendCMD();
+    wait(1);
+    strcpy(snd,"AT\r\n");
+    SendCMD();
+    timeout=1;
+    getreply();
+    wait(1);
+    pc.printf("\f---------- Starting ESP Config ----------\r\n\n");
+ 
+    pc.printf("---------- Reset & get Firmware ----------\r\n");
+    strcpy(snd,"AT+RST\r\n");
+    SendCMD();
+    timeout=5;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(2);
+ 
+    pc.printf("\n---------- Get Version ----------\r\n");
+    strcpy(snd,"AT+GMR\r\n");
+    SendCMD();
+    timeout=4;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(3);
+ 
+    // set CWMODE to 1=Station,2=AP,3=BOTH, default mode 1 (Station)
+    pc.printf("\n---------- Setting Mode ----------\r\n");
+    strcpy(snd, "AT+CWMODE=1\r\n");
+    SendCMD();
+    timeout=4;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(2);
+ 
+    // set CIPMUX to 0=Single,1=Multi
+    pc.printf("\n---------- Setting Connection Mode ----------\r\n");
+    strcpy(snd, "AT+CIPMUX=1\r\n");
+    SendCMD();
+    timeout=4;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(2);
+ 
+    pc.printf("\n---------- Listing Access Points ----------\r\n");
+    strcpy(snd, "AT+CWLAP\r\n");
+    SendCMD();
+    timeout=15;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(2);
+ 
+    pc.printf("\n---------- Connecting to AP ----------\r\n");
+    pc.printf("ssid = %s   pwd = %s\r\n",ssid,pwd);
+    strcpy(snd, "AT+CWJAP=\"");
+    strcat(snd, ssid);
+    strcat(snd, "\",\"");
+    strcat(snd, pwd);
+    strcat(snd, "\"\r\n");
+    SendCMD();
+    timeout=10;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(5);
+ 
+    pc.printf("\n---------- Get IP's ----------\r\n");
+    strcpy(snd, "AT+CIFSR\r\n");
+    SendCMD();
+    timeout=3;
+    getreply();
+    pc.printf(buf);
+ 
+    wait(1);
+ 
+    pc.printf("\n---------- Get Connection Status ----------\r\n");
+    strcpy(snd, "AT+CIPSTATUS\r\n");
+    SendCMD();
+    timeout=5;
+    getreply();
+    pc.printf(buf);
+ 
+    pc.printf("\n\n\n  If you get a valid (non zero) IP, ESP8266 has been set up.\r\n");
+    pc.printf("  Run this if you want to reconfig the ESP8266 at any time.\r\n");
+    pc.printf("  It saves the SSID and password settings internally\r\n");
+    wait(10);
+}
+ 
+void SendCMD()
+{
+    esp.printf("%s", snd);
+}
+ 
+void getreply()
+{
+    memset(buf, '\0', sizeof(buf));
+    t.start();
+    ended=0;
+    count=0;
+    while(!ended) {
+        if(esp.readable()) {
+            buf[count] = esp.getc();
+            count++;
+        }
+        if(t.read() > timeout) {
+            ended = 1;
+            t.stop();
+            t.reset();
+        }
+    }
+}
+
+// Basic wifi setup code
+void basicWifiSetup() {
+    reset=0; //hardware reset for 8266
+    pc.baud(9600);  // set what you want here depending on your terminal program speed
+    pc.printf("\f\n\r-------------ESP8266 Hardware Reset-------------\n\r");
+    wait(0.5);
+    reset=1;
+    timeout=2;
+    getreply();
+ 
+    esp.baud(115200);   // change this to the new ESP8266 baudrate if it is changed at any time.
+ 
+    //ESPsetbaudrate();   //******************  include this routine to set a different ESP8266 baudrate  ******************
+ 
+    ESPconfig();        //******************  include Config to set the ESP8266 configuration  ***********************
+}
+
+// Loop for basic wifi stuff
+void basicWifiLoop() {
+    pc.printf("\n---------- Listing Acces Points ----------\r\n");
+    strcpy(snd, "AT+CWLAP\r\n");
+    SendCMD();
+    timeout=15;
+    getreply();
+    pc.printf(buf);
+    wait(2);
+    pc.printf("\n---------- Get IP and MAC ----------\r\n");
+    strcpy(snd, "AT+CIFSR\r\n");
+    SendCMD();
+    timeout=10;
+    getreply();
+    pc.printf(buf);
+    wait(2);
+}
+#endif
+
+#if USE_WIFI_ADVANCED
+// Setup advanced wifi
+void advWifiSetup() {
+    pc.baud(9600);
+    wifi.init(); //Reset
+    wifi.connect(); //Use DHCP
+    
+    advWifiTest(); // Test the connection
+}
+
+// Test that the advanced wifi is working with pastebin get/post
+void advWifiTest() {
+    bool getSuccess = false,
+         postSuccess = false;
+    
+    //GET
+    pc.printf("\nTrying to fetch page using GET...\n\r");
+    int httpResp = http.get("http://54.175.222.246/get", responseBuffer, 512);//IP address is httpbin.org/get
+    if (!httpResp) {
+        pc.printf("Page fetched successfully - read %d characters\n\r", strlen(responseBuffer));
+        pc.printf("Result: %s\n\r", responseBuffer);
+        getSuccess = true;
+    } else {
+        pc.printf("Error - ret = %d - HTTP return code = %d\n\r", httpResp, http.getHTTPResponseCode());
+        getSuccess = false;
+    }
+    
+    //POST
+    HTTPMap postDataMap;
+    HTTPText responseTextBind(responseBuffer, 512);
+    postDataMap.put("Hello", "World");
+    postDataMap.put("test", "1234");
+    pc.printf("\nTrying to POST data to httpbin.org/post...\n\r");
+    httpResp = http.post("http://54.175.222.246/post", postDataMap, &responseTextBind);//IP address is httpbin.org/post
+    if (!httpResp) {
+      pc.printf("Executed POST successfully - read %d characters\n\r", strlen(responseBuffer));
+      pc.printf("Result: %s\n\r", responseBuffer);
+      postSuccess = true;
+    }
+    else {
+      pc.printf("Error - ret = %d - HTTP return code = %d\n\r", httpResp, http.getHTTPResponseCode());
+      postSuccess = false;
+    }
+    
+    if (getSuccess && postSuccess) {
+        pc.printf("\n\r=== WIFI SETUP AND GOOD TO GO====\n\r\n\r");
+    } else {
+        pc.printf("\n\r=== WIFI BAD - Try at your own risk... ====\n\r\n\r");
+    }
+}
+
+// Send an advanced wifi command (non-blocking)
+// INPUTS:
+//    keycode - Keycode from capacitive touch screen
+void advWifiSendCommand(int keycode) {
+    pc.printf("Send command %d\n\r", keycode);
+    
+    char sendVal[32];
+    switch (keycode) {
+        case 2:
+            sprintf(sendVal, "fwd");
+            break;
+        case 5:
+            sprintf(sendVal, "left");
+            break;
+        case 7:
+            sprintf(sendVal, "right");
+            break;
+        case 10:
+            sprintf(sendVal, "back");
+            break;
+        default:
+            pc.printf("\tBailing from bad keycode '%d'...\n\r", keycode);
+            return; // Bail
+    }
+    
+    // We good to go? Grab a mutex
+    //if (!advWifiMutex.trylock()) {
+    //    pc.printf("\tFailed to lock mutex. Bailing...\n\r");
+    //    return;
+    //}
+    
+    // Clear buffer
+    responseBuffer[0] = '\0';
+    
+    // Setup bindings
+    HTTPMap postDataMap;
+    HTTPText responseTextBind(responseBuffer, 512);
+    postDataMap.put("keycode", sendVal);
+    
+    pc.printf("Turning: %s with %d\t(%s)\n\r", sendVal, keycode, httpDest);
+    int httpResp = http.post(httpDest, postDataMap, &responseTextBind);
+    if (!httpResp) {
+        pc.printf("\tSuccess!\n\r");
+        pc.printf("\tResult: %s\n\r", responseBuffer);
+    } else {
+        pc.printf("\tFailed!\n\r");
+        pc.printf("\tResult: %s\n\r", responseBuffer);
+        pc.printf("\tRespVal(%d) \ ResponseCode(%d)\n\r", httpResp, http.getHTTPResponseCode());
+    }
+    
+    //advWifiMutex.unlock();
+}
+
+void advWifiThread(void const *args) {
+    while(1) {
+        if (gKeycodeLatch && gKeycode != -1) {
+            advWifiSendCommand(gKeycode);
+            gKeycodeLatch = false;
+        }
+        
+        Thread::wait(100);
+    }
+}
+#endif
\ No newline at end of file
diff -r 000000000000 -r e68e51f935d1 mbed-rtos.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-rtos.lib	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed-rtos/#e45e4ac7c3c8
diff -r 000000000000 -r e68e51f935d1 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/34e6b704fe68
\ No newline at end of file
diff -r 000000000000 -r e68e51f935d1 mpr121.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mpr121.cpp	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,221 @@
+/*
+Copyright (c) 2011 Anthony Buckton (abuckton [at] blackink [dot} net {dot} au)
+ 
+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 <mbed.h>
+#include <sstream>
+#include <string>
+#include <list>
+
+#include <mpr121.h>
+    
+Mpr121::Mpr121(I2C *i2c, Address i2cAddress)
+{
+    this->i2c = i2c;
+    
+    address = i2cAddress;
+           
+    // Configure the MPR121 settings to default
+    this->configureSettings();
+}
+
+   
+void Mpr121::configureSettings()
+{
+    // Put the MPR into setup mode
+    this->write(ELE_CFG,0x00);
+    
+    // Electrode filters for when data is > baseline
+    unsigned char gtBaseline[] = {
+         0x01,  //MHD_R
+         0x01,  //NHD_R 
+         0x00,  //NCL_R
+         0x00   //FDL_R
+         };
+         
+    writeMany(MHD_R,gtBaseline,4);   
+                 
+     // Electrode filters for when data is < baseline   
+     unsigned char ltBaseline[] = {
+        0x01,   //MHD_F
+        0x01,   //NHD_F
+        0xFF,   //NCL_F
+        0x02    //FDL_F
+        };
+        
+    writeMany(MHD_F,ltBaseline,4);
+        
+    // Electrode touch and release thresholds
+    unsigned char electrodeThresholds[] = {
+        E_THR_T, // Touch Threshhold
+        E_THR_R  // Release Threshold
+        };
+
+    for(int i=0; i<12; i++){
+        int result = writeMany((ELE0_T+(i*2)),electrodeThresholds,2);
+    }   
+
+    // Proximity Settings
+    unsigned char proximitySettings[] = {
+        0xff,   //MHD_Prox_R
+        0xff,   //NHD_Prox_R
+        0x00,   //NCL_Prox_R
+        0x00,   //FDL_Prox_R
+        0x01,   //MHD_Prox_F
+        0x01,   //NHD_Prox_F
+        0xFF,   //NCL_Prox_F
+        0xff,   //FDL_Prox_F
+        0x00,   //NHD_Prox_T
+        0x00,   //NCL_Prox_T
+        0x00    //NFD_Prox_T
+        };
+    writeMany(MHDPROXR,proximitySettings,11);
+
+    unsigned char proxThresh[] = {
+        PROX_THR_T, // Touch Threshold
+        PROX_THR_R  // Release Threshold
+        };
+    writeMany(EPROXTTH,proxThresh,2); 
+       
+    this->write(FIL_CFG,0x04);
+    
+    // Set the electrode config to transition to active mode
+    this->write(ELE_CFG,0x0c);
+}
+
+void Mpr121::setElectrodeThreshold(int electrode, unsigned char touch, unsigned char release){
+    
+    if(electrode > 11) return;
+    
+    // Get the current mode
+    unsigned char mode = this->read(ELE_CFG);
+    
+    // Put the MPR into setup mode
+    this->write(ELE_CFG,0x00);
+    
+    // Write the new threshold
+    this->write((ELE0_T+(electrode*2)), touch);
+    this->write((ELE0_T+(electrode*2)+1), release);
+    
+    //Restore the operating mode
+    this->write(ELE_CFG, mode);
+}
+    
+    
+unsigned char Mpr121::read(int key){
+
+    unsigned char data[2];
+    
+    //Start the command
+    i2c->start();
+
+    // Address the target (Write mode)
+    int ack1= i2c->write(address);
+
+    // Set the register key to read
+    int ack2 = i2c->write(key);
+
+    // Re-start for read of data
+    i2c->start();
+
+    // Re-send the target address in read mode
+    int ack3 = i2c->write(address+1);
+
+    // Read in the result
+    data[0] = i2c->read(0); 
+
+    // Reset the bus        
+    i2c->stop();
+
+    return data[0];
+}
+
+
+int Mpr121::write(int key, unsigned char value){
+    
+    //Start the command
+    i2c->start();
+
+    // Address the target (Write mode)
+    int ack1= i2c->write(address);
+
+    // Set the register key to write
+    int ack2 = i2c->write(key);
+
+    // Read in the result
+    int ack3 = i2c->write(value); 
+
+    // Reset the bus        
+    i2c->stop();
+    
+    return (ack1+ack2+ack3)-3;
+}
+
+
+int Mpr121::writeMany(int start, unsigned char* dataSet, int length){
+    //Start the command
+    i2c->start();
+
+    // Address the target (Write mode)
+    int ack= i2c->write(address);
+    if(ack!=1){
+        return -1;
+    }
+    
+    // Set the register key to write
+    ack = i2c->write(start);
+    if(ack!=1){
+        return -1;
+    }
+
+    // Write the date set
+    int count = 0;
+    while(ack==1 && (count < length)){
+        ack = i2c->write(dataSet[count]);
+        count++;
+    } 
+    // Stop the cmd
+    i2c->stop();
+    
+    return count;
+}
+      
+
+bool Mpr121::getProximityMode(){
+    if(this->read(ELE_CFG) > 0x0c)
+        return true;
+    else
+        return false;
+}
+
+void Mpr121::setProximityMode(bool mode){
+    this->write(ELE_CFG,0x00);
+    if(mode){
+        this->write(ELE_CFG,0x30); //Sense proximity from ALL pads
+    } else {
+        this->write(ELE_CFG,0x0c); //Sense touch, all 12 pads active.
+    }
+}
+
+
+int Mpr121::readTouchData(){
+    return this->read(0x00);
+}
\ No newline at end of file
diff -r 000000000000 -r e68e51f935d1 mpr121.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mpr121.h	Tue Oct 20 17:35:45 2015 +0000
@@ -0,0 +1,157 @@
+/*
+Copyright (c) 2011 Anthony Buckton (abuckton [at] blackink [dot} net {dot} au)
+
+ 
+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.
+
+   Parts written by Jim Lindblom of Sparkfun
+   Ported to mbed by A.Buckton, Feb 2011
+*/
+
+#ifndef MPR121_H
+#define MPR121_H
+
+//using namespace std;
+
+class Mpr121 
+{
+
+public:
+    // i2c Addresses, bit-shifted
+    enum Address { ADD_VSS = 0xb4,// ADD->VSS = 0x5a <-wiring on Sparkfun board
+                   ADD_VDD = 0xb6,// ADD->VDD = 0x5b
+                   ADD_SCL = 0xb8,// ADD->SDA = 0x5c
+                   ADD_SDA = 0xba // ADD->SCL = 0x5d
+                 };
+
+    // Real initialiser, takes the i2c address of the device.
+    Mpr121(I2C *i2c, Address i2cAddress);
+    
+    bool getProximityMode();
+    
+    void setProximityMode(bool mode);
+    
+    int readTouchData();
+               
+    unsigned char read(int key);
+    
+    int write(int address, unsigned char value);
+    int writeMany(int start, unsigned char* dataSet, int length);
+
+    void setElectrodeThreshold(int electrodeId, unsigned char touchThreshold, unsigned char releaseThreshold);
+        
+protected:
+    // Configures the MPR with standard settings. This is permitted to be overwritten by sub-classes.
+    void configureSettings();
+    
+private:
+    // The I2C bus instance.
+    I2C *i2c;
+
+    // i2c address of this mpr121
+    Address address;
+};
+
+
+// MPR121 Register Defines
+#define    MHD_R        0x2B
+#define    NHD_R        0x2C
+#define    NCL_R        0x2D
+#define    FDL_R        0x2E
+#define    MHD_F        0x2F
+#define    NHD_F        0x30
+#define    NCL_F        0x31
+#define    FDL_F        0x32
+#define    NHDT         0x33
+#define    NCLT         0x34
+#define    FDLT         0x35
+// Proximity sensing controls
+#define    MHDPROXR     0x36
+#define    NHDPROXR     0x37
+#define    NCLPROXR     0x38
+#define    FDLPROXR     0x39
+#define    MHDPROXF     0x3A
+#define    NHDPROXF     0x3B
+#define    NCLPROXF     0x3C
+#define    FDLPROXF     0x3D
+#define    NHDPROXT     0x3E
+#define    NCLPROXT     0x3F
+#define    FDLPROXT     0x40
+// Electrode Touch/Release thresholds
+#define    ELE0_T       0x41
+#define    ELE0_R       0x42
+#define    ELE1_T       0x43
+#define    ELE1_R       0x44
+#define    ELE2_T       0x45
+#define    ELE2_R       0x46
+#define    ELE3_T       0x47
+#define    ELE3_R       0x48
+#define    ELE4_T       0x49
+#define    ELE4_R       0x4A
+#define    ELE5_T       0x4B
+#define    ELE5_R       0x4C
+#define    ELE6_T       0x4D
+#define    ELE6_R       0x4E
+#define    ELE7_T       0x4F
+#define    ELE7_R       0x50
+#define    ELE8_T       0x51
+#define    ELE8_R       0x52
+#define    ELE9_T       0x53
+#define    ELE9_R       0x54
+#define    ELE10_T      0x55
+#define    ELE10_R      0x56
+#define    ELE11_T      0x57
+#define    ELE11_R      0x58
+// Proximity Touch/Release thresholds
+#define    EPROXTTH     0x59
+#define    EPROXRTH     0x5A
+// Debounce configuration
+#define    DEB_CFG      0x5B
+// AFE- Analogue Front End configuration
+#define    AFE_CFG      0x5C 
+// Filter configuration
+#define    FIL_CFG      0x5D
+// Electrode configuration - transistions to "active mode"
+#define    ELE_CFG      0x5E
+
+#define GPIO_CTRL0      0x73
+#define GPIO_CTRL1      0x74
+#define GPIO_DATA       0x75
+#define    GPIO_DIR     0x76
+#define    GPIO_EN      0x77
+#define    GPIO_SET     0x78
+#define GPIO_CLEAR      0x79
+#define GPIO_TOGGLE     0x7A
+// Auto configration registers
+#define    AUTO_CFG_0   0x7B
+#define    AUTO_CFG_U   0x7D
+#define    AUTO_CFG_L   0x7E
+#define    AUTO_CFG_T   0x7F
+
+// Threshold defaults
+// Electrode touch threshold
+#define    E_THR_T      0x0F   
+// Electrode release threshold 
+#define    E_THR_R      0x0A    
+// Prox touch threshold
+#define    PROX_THR_T   0x02
+// Prox release threshold
+#define    PROX_THR_R   0x02
+
+#endif