PROJ515 / Mbed OS ELEC-351-GROUP-E-CW

Dependencies:   BMP280

Files at this revision

API Documentation at this revision

Comitter:
mwthewsey
Date:
Tue Jan 09 20:51:19 2018 +0000
Parent:
20:25939e03b803
Child:
22:617bf92b481f
Commit message:
Everything working. Comments checked.

Changed in this revision

LCD.cpp Show annotated file Show diff for this revision Revisions of this file
LCD.h Show annotated file Show diff for this revision Revisions of this file
Logging.cpp Show annotated file Show diff for this revision Revisions of this file
Logging.h Show annotated file Show diff for this revision Revisions of this file
SDCard.cpp Show annotated file Show diff for this revision Revisions of this file
SDCard.h Show annotated file Show diff for this revision Revisions of this file
Sampling.cpp Show annotated file Show diff for this revision Revisions of this file
Sampling.h Show annotated file Show diff for this revision Revisions of this file
Serial.cpp Show annotated file Show diff for this revision Revisions of this file
Serial.h Show annotated file Show diff for this revision Revisions of this file
WebUI.cpp Show annotated file Show diff for this revision Revisions of this file
WebUI.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
--- a/LCD.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/LCD.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -4,27 +4,32 @@
 #include "rtos.h"
 
 using namespace std;
+//Initalise TextLCD and button1 before constructor. 
 ENVDISPLAY::ENVDISPLAY(PinName rsPin, PinName rePin, PinName d4Pin, PinName d5Pin, PinName d6Pin, PinName d7Pin, PinName Button1Pin, PinName Button2Pin) : TextLCD(rsPin, rePin, d4Pin, d5Pin, d6Pin, d7Pin), Button1(Button1Pin), Button2(Button2Pin)
 {
-    //constructor
+    //constructor. Initalise variables
     _latestTemp = 0.0;
     _latestPres = 0.0;
     _latestLDR = 0.0;
     _latestTime = 0;
     _currentState = SCROLLREADINGS;
 }
+
+
 void ENVDISPLAY::SendMessage(char sentText[], bool returnToReadings)
 {
     if (strlen(sentText)>32)
     {
         //overflow error
+        LogEvent(Log_LCDOverflow);
     } else {
-        std::copy( sentText, sentText+strlen(sentText), _message ); //store  inputted message to _message
+        std::copy( sentText, sentText+strlen(sentText), _message ); //store inputted message to _message
         _AutoQuit = returnToReadings;   //Set AutoQuitState
         _currentState = MESSAGE;    //Change LCD state to show message
     }
 }
 
+
 void ENVDISPLAY::UpdateData(float temp, float pres, float LDR, time_t sampleTime)
 {
     _latestTemp = temp;
@@ -33,10 +38,11 @@
     _latestTime = sampleTime;
 }
 
+
 void ENVDISPLAY::StateMachine(void)
 {
     while (true) {
-        cls();
+        cls();  //clear LCD
         switch (_currentState) {
             case SCROLLREADINGS:
                 LogEvent(Log_LCDScroll);   //Log position
@@ -44,7 +50,6 @@
                 tm T = ReturnDateTimeStruct(_latestTime);   //Get a time structure
                 printf("Temp: %5.1fC\n",_latestTemp);   //Print temperature
                 printf("Pres: %5.1fmBar\n",_latestPres);//Print Pressure
-                //while (Button2 == 0) {}; //Spin
                 Thread::wait(SCREENDELAY_MS);   //Hold screen for specified time
                 cls();  //Clear screen
                 printf("LDR: %4.3f\n",_latestLDR);  //Print Light Level
@@ -76,9 +81,9 @@
 
 void ENVDISPLAY::Start(void)
 {
-    LCDThread.start(this, &ENVDISPLAY::StateMachine);
-    this->Button1.rise(this, &ENVDISPLAY::Button1ISR);
-    SendMessage("Starting...",true);
+    LCDThread.start(this, &ENVDISPLAY::StateMachine);  //Start thread
+    this->Button1.rise(this, &ENVDISPLAY::Button1ISR); //Initalise button interrupt
+    SendMessage("Starting...",true);                   //WRite message
 }
 
 void ENVDISPLAY::Button1ISR(void)
--- a/LCD.h	Tue Jan 09 11:53:11 2018 +0000
+++ b/LCD.h	Tue Jan 09 20:51:19 2018 +0000
@@ -21,25 +21,26 @@
 *lcd.Start() must be run to begin operation.
 */
 
-#define SCREENDELAY_MS 2707
+#define SCREENDELAY_MS 2707  //Delay for screen update
 
-class ENVDISPLAY : TextLCD
+class ENVDISPLAY : TextLCD  //Class inherits TextLCD
 {
 private:
     char _message[32];  //32 characters on display
-    bool _AutoQuit; //After a message, should the LCD return to enviromental?
-    float _latestTemp;
+    bool _AutoQuit;     //After a message, should the LCD return to enviromental?
+    float _latestTemp;  //Latest sample data
     float _latestPres;
     float _latestLDR;
     time_t _latestTime;
     
     enum ThreadState{MESSAGE,SCROLLREADINGS,ADJUSTTIME};
     
-    ThreadState _currentState;
+    ThreadState _currentState; //State machine state
     
-    InterruptIn Button1;
+    //Hardware
+    InterruptIn Button1;  //Buttons used for setting time
     DigitalIn Button2;
-    Thread LCDThread;
+    Thread LCDThread;     //Thread which LCD runs in
     
     void Button1ISR(void);
     //Called when button 1 is pressed. 
--- a/Logging.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/Logging.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -2,8 +2,8 @@
 #include <string>
 
 using namespace std;
-Mail<uint32_t,32> ActivityLog;
-bool logging = false;
+Mail<uint32_t,32> ActivityLog;  //Mail Queue passes logging data
+bool logging = false;           //Are we logging or not
 
 void LogEvent(uint32_t eventCode)
 {
@@ -18,10 +18,10 @@
 {
     string returnString = "";
     if (logging) {  //Only do if logging is enabled
-        osEvent evt = ActivityLog.get();    //Get the object from mailbox. This blocks until there is data
+        osEvent evt = ActivityLog.get(5000);    //Get the object from mailbox. This blocks until there is data. Timeout after 5 secconds
         if (evt.status == osEventMail) {
             //Does it have content? If not, there is no mail.
-            uint32_t* mail = (uint32_t*)evt.value.p;    //extract the value passed
+            uint32_t* mail = (uint32_t*)evt.value.p;    //Extract the value passed
             //Convert int value to string
             char intStr[4]; //Has to be done in two steps because of known to_string bug stackoverflow.com/questions/12975341
             sprintf(intStr, "%d", *mail);
@@ -29,8 +29,8 @@
             ActivityLog.free(mail);     //Now we can release the space in the mailbox
             returnString = "Data Logged:\n\r" + mailAsString;
             return returnString;
-        } else {
-            //There wasn't any data
+        } else {  
+            //There wasn't any data            
             string returnString = "ERROR: There wasn't any data";
         }
     }
--- a/Logging.h	Tue Jan 09 11:53:11 2018 +0000
+++ b/Logging.h	Tue Jan 09 20:51:19 2018 +0000
@@ -27,15 +27,23 @@
 #define Log_SampleTicker 0
 #define Log_EnviromSampled 1
 #define Log_TimeSampled 2
-#define Log_IndexInc 3
-#define Log_OldestInc 4
-#define Log_LCDScroll 5
-#define Log_LCDMessage 6
-#define Log_LCDTime 7
-#define Log_SetDateFail 8
-#define Log_SetTimeFail 9
-#define Log_EthCongifd 10
-#define Log_EthRequest 11
+#define Log_IndexInc 3 
+#define Log_OldestInc 4 
+#define Log_LCDScroll 5 
+#define Log_LCDMessage 6 
+#define Log_LCDTime 7 
+#define Log_LCDOverflow 8
+#define Log_LCDNoData 9
+#define Log_SetDateFail 10 
+#define Log_SetTimeFail 11
+#define Log_EthConfig 12
+#define Log_EthRequest 13
+#define Log_SDInitFail 14
+#define Log_SDFileOpenFail 15
+#define Log_SDRemoved 16
+#define Log_SDInserted 17
+#define Log_SDDeInit 18
+#define Log_SDDismountFail 19
 
 extern Mail<uint32_t,32> ActivityLog;   //Mailbox that holds the activity
 
--- a/SDCard.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/SDCard.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -5,15 +5,19 @@
 #include "FATFileSystem.h"
 #include "LCD.h"
 
+
+//Hardware
 DigitalOut SDCardStatusLED(LED3);
 
+//Variables
 bool SDCardPresent;
 bool SDCardMounted;
 unsigned short SDinternalIndex;
 
 FILE* fp; //File pointer type
-SDCardStates SDCurrentState;
+SDCardStates SDCurrentState;    //Create state machine state
 
+Timeout antiBounce;
 Thread SDCardThread;
 FATFileSystem fs;
 
@@ -25,7 +29,7 @@
     SD_WP.fall(&SDCardInsertedISR);    //SD inserted
     UserButton.fall(&SDCardButtonISR); //Button released
 
-    if (SD_WP == 1) {
+    if (SD_WP == 1) {               //Checks if card is inserted on power up and sets states
         SDCardPresent = false;
         SDCurrentState = REMOVED;
         SDCardMounted = false;
@@ -43,35 +47,32 @@
 {
     SDCardPresent = false;
     SDCurrentState = REMOVED;
-    SDCardThread.signal_set(1);
+    antiBounce.attach(&antiBounceISR,1);
 }
 
 void SDCardInsertedISR(void)
 {
     SDCardPresent = true;
     SDCurrentState = INSERTED;
-    SDCardThread.signal_set(1);
+    antiBounce.attach(&antiBounceISR,1);
 
 }
 
 void SDCardButtonISR(void)
 {
     SDCurrentState = DISMOUNTREQUEST;
+    antiBounce.attach(&antiBounceISR,1);
+}
+//-----------------------------------------------------------------//
+
+void antiBounceISR(void)
+{
     SDCardThread.signal_set(1);
 }
-//-----------------------------------------------------------------//
 
 
 void SDCardCode(void)
 {
-
-    //set bool state. if sd card is in or not. (if sd card is already in)
-    if (SD_WP) {
-        SDCurrentState = REMOVED;
-    } else {
-        SDCurrentState = INSERTED;
-    }
-
     while(true) {
         Thread::signal_wait(1);    //Wait untill signal set
 
@@ -81,57 +82,71 @@
                 //print error message file currupt
                 lcd.SendMessage("SD CARD REMOVED!  FILE CORRUPT",true);
             }
-            SDCardStatusLED = 0;
+            LogEvent(Log_SDRemoved);
+            SDCardStatusLED = 0;    //Set LEDs
             GreenLED = 0;
 
 
 
         } else if (SDCurrentState == INSERTED) {
+            LogEvent(Log_SDInserted);
+            SDCardStatusLED = 0;    //Set LEDs
+            GreenLED = 0;
 
-            Thread::wait(1000); //wait 1 seccond to allow the SD card to be pluged in.
-            
             if ( sd.init() != 0) { //Initalises the SDCard and checks if it succeeded
                 //SDInit failed. Reinsert the SDCard
-            }
+                lcd.SendMessage("REINSERT SDCARD",true);
+                LogEvent(Log_SDInitFail);
 
-            //Create a filing system for SD Card
-            FATFileSystem fs("sd", &sd);////////////////////////////////////////////////////moved to init. dont know if this works.
+            } else {
 
-            //Open to WRITE
-            fp = fopen("/sd/test.csv","w");
-            if (fp == NULL) {
-                lcd.SendMessage("CANNOT OPEN FILE/sd/test.csv",true);
-                //error
-            }
-            SDCardMounted = true;
-            
-            Sampling(false);         //Stop sampling
-            SDinternalIndex = currentIndex; //InternalIndex for incrementing out data
-            TakeKeys(true); //Take keys
-            
-            fprintf(fp,"Date,Time,Temperature,Pressure,Light\n");
-            for (short i = 0; i < BUFFERSIZE; i++) { //For loop of length buffersize
-                tm T = ReturnDateTimeStruct(timeReadings[SDinternalIndex]);
-                //InternalIndex was set as newest. We will now decrement to display oldest to newest
-                fprintf(fp," %4d/%2d/%2d,%2d:%2d:%2d,%2.2f,%2.2f,%2.2f\n",T.tm_year,T.tm_mon,T.tm_mday,T.tm_hour,T.tm_min,T.tm_sec,tempReadings[SDinternalIndex],presReadings[SDinternalIndex],LDRReadings[SDinternalIndex]);
-                SDinternalIndex = IndexDecrement(SDinternalIndex); //Decrement internal index
-            }
-            
-            TakeKeys(false); //Return keys
-            Sampling(true);  //Start sampling
-            
+                //Create a filing system for SD Card
+                FATFileSystem fs("sd", &sd);
 
-            fclose(fp);
-            SDCardStatusLED = 1;
+                //Open to WRITE
+                fp = fopen("/sd/samples.csv","w");
 
 
+                if (fp == NULL) {
+                    //error
+                    lcd.SendMessage("CANNOT OPEN FILE/sd/samples.csv",true);
+                    LogEvent(Log_SDFileOpenFail);
+
+                } else {
+                    SDCardMounted = true;   //SD card is now mounted
+
+                    Sampling(false);    //Stop sampling
+                    SDinternalIndex = currentIndex; //SDinternalIndex for incrementing out data
+                    TakeKeys(true);     //Take keys
+
+                    fprintf(fp,"Date,Time,Temperature,Pressure,Light\n");
+                    for (short i = 0; i < BUFFERSIZE; i++) { //For loop of length buffersize
+                        tm T = ReturnDateTimeStruct(timeReadings[SDinternalIndex]);
+                        //SDinternalIndex was set as newest. We will now decrement to display oldest to newest
+                        fprintf(fp," %4d/%2d/%2d,%2d:%2d:%2d,%2.2f,%2.2f,%2.2f\n",T.tm_year,T.tm_mon,T.tm_mday,T.tm_hour,T.tm_min,T.tm_sec,tempReadings[SDinternalIndex],presReadings[SDinternalIndex],LDRReadings[SDinternalIndex]);
+                        SDinternalIndex = IndexDecrement(SDinternalIndex); //Decrement internal index
+                    }
+                }
+                TakeKeys(false); //Return keys
+                Sampling(true);  //Start sampling
+
+
+                fclose(fp);         //Close file
+                SDCardStatusLED = 1;//Set light to indicate SD card file transfer complete.
+            }
 
         } else if (SDCurrentState == DISMOUNTREQUEST) {
 
-            sd.deinit();
-            SDCardMounted = false;
-            lcd.SendMessage("REMOVE SD CARD",true);
-            GreenLED = 1;
+            if (SDCardMounted) {
+                sd.deinit();    //De initalise SD card
+                SDCardMounted = false;  //Card now not mounted
+                lcd.SendMessage("REMOVE SD CARD",true); //SD card can be removed
+                GreenLED = 1;   //Indication LED
+                LogEvent(Log_SDDeInit);
+            } else {
+                lcd.SendMessage("NO SD CARD  TO REMOVE",true);
+                LogEvent(Log_SDDismountFail);
+            }
 
         }
     }
--- a/SDCard.h	Tue Jan 09 11:53:11 2018 +0000
+++ b/SDCard.h	Tue Jan 09 20:51:19 2018 +0000
@@ -9,13 +9,14 @@
 #include "SDBlockDevice.h"
 #include "FATFileSystem.h"
 #include "LCD.h"
+#include "Logging.h"
 
 //Hardware devices
-extern InterruptIn SD_WP;   //Pin that indicates if the card has been inserted (active low)
-extern InterruptIn UserButton;//Demount request
-extern SDBlockDevice sd;      //SD Card device
-extern DigitalOut GreenLED;   //Shows its safe to demount
-extern DigitalOut SDCardStatusLED;//Shows if the card is inserted
+extern InterruptIn SD_WP;          //Pin that indicates if the card has been inserted (active low)
+extern InterruptIn UserButton;     //Demount request
+extern SDBlockDevice sd;           //SD Card device
+extern DigitalOut GreenLED;        //Shows its safe to demount
+extern DigitalOut SDCardStatusLED; //Shows if the card is inserted
 
 enum SDCardStates{INSERTED,REMOVED,DISMOUNTREQUEST};
 
@@ -31,9 +32,14 @@
 void SDCardInit(void);
 //Starts the thread and sets up the interrupts
 void SDCardRemovedISR(void);
-//
+//Interrupt runs when SD card is removed
 void SDCardInsertedISR(void);
+//Interrupt runs when SD card is inserted
 void SDCardButtonISR(void);
+//Interrupt runs when user button is pressed
 void SDCardCode(void);
+//Thread code which handles writing to SD card
+void antiBounceISR(void);
+//Prevent button bounce
 
 #endif
\ No newline at end of file
--- a/Sampling.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/Sampling.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -15,11 +15,13 @@
 float LDRReadings[BUFFERSIZE] = {};
 time_t timeReadings[BUFFERSIZE] = {};
 
+unsigned short SAMPLERATE = 15; //Set initial sample rate.
+
 Thread t1; //Sample Enviromental Sensor
 Thread t2; //Sample LDR Sensor
 
-Ticker sampleRate;
-Timeout SampleLEDTimeout;
+Ticker sampleRate;          
+Timeout SampleLEDTimeout;   
 
 bool NewEnvSample;  //Is there new data from the envirom sensor to output?
 bool NewLDRSample;  //Is there new data from the LDR to output?
@@ -29,7 +31,7 @@
 volatile unsigned short currentIndex = 0;
 volatile unsigned short oldestIndex = 0;
 
-bool firstSample = true;
+bool firstSample;
 
 void SampleTimerISR(void)
 {
@@ -45,24 +47,27 @@
     NewEnvSample = false;  //Reset
     NewLDRSample = false;  //Reset
 
-    t1.start(&ThreadSampleEnvSensor);
+    t1.start(&ThreadSampleEnvSensor); //Start Threads
     t2.start(&ThreadSampleLDR);
 
+    Thread t1(osPriorityRealtime);  //Higher priority
+    Thread t2(osPriorityRealtime);
+
     sampleRate.attach(&SampleTimerISR, SAMPLERATE); //15 second interval
 }
 
 void AddTempSample(float temp)
 {
-    tempReadingsLock.lock(); //Take the key
+    tempReadingsLock.lock();        //Take the key
     tempReadings[nextIndex] = temp; //Add the sample after the most recent
-    tempReadingsLock.unlock(); // Release the key
+    tempReadingsLock.unlock();      // Release the key
 }
 
 void AddPresSample(float pres)
 {
-    presReadingsLock.lock();    //Take the key
+    presReadingsLock.lock();        //Take the key
     presReadings[nextIndex] = pres; //Add to register
-    presReadingsLock.unlock(); //Release the key
+    presReadingsLock.unlock();      //Release the key
 }
 
 void ThreadSampleEnvSensor(void)
@@ -80,16 +85,16 @@
 
 void AddLDRSample(float LDRval)
 {
-    LDRReadingsLock.lock(); //Take the key
-    LDRReadings[nextIndex] = LDRval; //Add the sample after the most recent
-    LDRReadingsLock.unlock(); // Release the key
+    LDRReadingsLock.lock();             //Take the key
+    LDRReadings[nextIndex] = LDRval;    //Add the sample after the most recent
+    LDRReadingsLock.unlock();           // Release the key
 }
 
 void AddTimeSample(time_t sampledTime)
 {
-    timeReadingsLock.lock();    //Take the key
+    timeReadingsLock.lock();                //Take the key
     timeReadings[nextIndex] = sampledTime;  //Add the sample after the most recent
-    timeReadingsLock.unlock();  // Release the key
+    timeReadingsLock.unlock();              // Release the key
 }
 
 void ThreadSampleLDR(void)
@@ -108,8 +113,6 @@
 
 void IncrementIndex(void)
 {
-    //printf("%d   %d   %d        %2.2f  %2.2f  %2.2f  %2.2f  %2.2f  %2.2f  %2.2f  %2.2f\r",nextIndex, currentIndex, oldestIndex, LDRReadings[0], LDRReadings[1], LDRReadings[2], LDRReadings[3], LDRReadings[4], LDRReadings[5], LDRReadings[6], LDRReadings[7]);
-
     nextIndex = IndexIncrement(nextIndex); //Increment next index
     if (firstSample) {
         firstSample = false; //During first sample, do not increment current or oldest
@@ -144,9 +147,9 @@
 void Sampling(bool inputState)
 {
     if (inputState) {
-        sampleRate.attach(&SampleTimerISR, SAMPLERATE);
+        sampleRate.attach(&SampleTimerISR, SAMPLERATE); //Attach ticker
     } else {
-        sampleRate.detach();
+        sampleRate.detach(); //Detach ticker, stops sampling
     }
 }
 
@@ -158,7 +161,7 @@
         LDRReadingsLock.lock();
         timeReadingsLock.lock();
     } else {
-        tempReadingsLock.unlock();           // Release the key
+        tempReadingsLock.unlock();           //Release the key
         presReadingsLock.unlock();
         LDRReadingsLock.unlock();
         timeReadingsLock.unlock();
--- a/Sampling.h	Tue Jan 09 11:53:11 2018 +0000
+++ b/Sampling.h	Tue Jan 09 20:51:19 2018 +0000
@@ -23,8 +23,7 @@
 #include "rtos.h"
 
 #define BUFFERSIZE 120
-#define SAMPLERATE 7
-
+extern unsigned short SAMPLERATE;
 
 //Thread Sync Tools
 extern Mutex tempReadingsLock;
@@ -58,12 +57,6 @@
 extern AnalogIn LDRSensor; //Input pin for LDR
 extern DigitalOut SamplingLED; //Onboard LED showing when a sample happens
 
-/*These can be deleted I think
-extern float fLatestTemp;
-extern float fLatestLDR;
-extern float fLatestPres;
-*/
-
 extern bool NewEnvSample;  //Is there new data from the envirom sensor to output?
 extern bool NewLDRSample;  //Is there new data from the LDR to output?
 
--- a/Serial.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/Serial.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -2,32 +2,36 @@
 #include "mbed.h"
 #include "Sampling.h"
 #include "TimeInterface.h"
+#include "Logging.h"
 
 #include <string>
 
 Thread SerialThread;
 
+//Variables
 int DateTimeVar[3];
+bool SerialState;
 char InputBufferText[128];
 unsigned short InputBufferNum;
 unsigned short internalIndex;
-float tempReadingsSerial[BUFFERSIZE] = {};
-float presReadingsSerial[BUFFERSIZE] = {};
-float LDRReadingsSerial[BUFFERSIZE] = {};
-time_t timeReadingsSerial[BUFFERSIZE] = {};
+
+//float tempReadingsSerial[BUFFERSIZE] = {};
+//float presReadingsSerial[BUFFERSIZE] = {};
+//float LDRReadingsSerial[BUFFERSIZE] = {};
+//time_t timeReadingsSerial[BUFFERSIZE] = {};
 
 
 void SerialStart(void)
 {
-    SerialThread.start(&SerialCode);            //Start thread running
-    //PC.attach(&RXInterruptISR, Serial::RxIrq);  //Attach interrupt function to hardware interrupt
-    PC.attach(&RXInterruptISR); //Fix
+    SerialThread.start(&SerialCode);   //Start thread running 
+    Thread SerialThread(osPriorityNormal, 32 * 1024);  //Normal priority with a 32k stack size 
+    PC.attach(&RXInterruptISR); //Attach interrupt function to hardware interrupt
 }
 
 
 void RXInterruptISR(void)
 {
-    SerialThread.signal_set(1);     //Set thread signal to start SerialCode
+    SerialThread.signal_set(1); //Set thread signal to start SerialCode
     PC.attach(NULL); //Disable interrupt
 }
 
@@ -43,21 +47,24 @@
 
 
         if (InputBufferString == "test") {
+            //Test function
             PC.printf("testsuccess\n\r");
 
 
         } else if (InputBufferString == "help") {
+            //Help function
             PC.printf("Here is an usefull list of commands:\n\r");
             PC.printf(" readall\n\r deleteall\n\r read <n>\n\r delete <n>\n\r setdate <dd><mm><yyyy>\n\r settime <hh><mm><ss>\n\r sett <T>\n\r state <x>\n\r logging <x>\n\r");
 
 
         } else if (InputBufferString == "readall") {
-            Sampling(false);         //Stop sampling
+            //Reads all samples in buffers and prints oldest first
+            Sampling(false); //Stop sampling
             internalIndex = currentIndex; //InternalIndex for incrementing out data
             PC.printf("Printing all %d reccords\n\r",BUFFERSIZE);
             PC.printf("  Date  |  Time  | Temp | Pressure | Light\n\r");
+            
             TakeKeys(true); //Take keys
-
             for (short i = 0; i < BUFFERSIZE; i++) { //For loop of length buffersize
                 tm T = ReturnDateTimeStruct(timeReadings[internalIndex]);
                 //InternalIndex was set as newest. We will now decrement to display oldest to newest
@@ -65,15 +72,15 @@
                 //PC.printf("%d\n\r",T.tm_year);
                 internalIndex = IndexDecrement(internalIndex); //Decrement internal index
             }
-            
+
             TakeKeys(false); //Return keys
             Sampling(true);  //Start sampling
 
 
         } else if (InputBufferString == "deleteall") {
-            //Stop sampling, take all keys, clear all, reset index, firstSample=true, unlock all, start sampling.
+            //Deletes all reccords
 
-            Sampling(false);         //Stop sampling
+            Sampling(false);//Stop sampling
 
             TakeKeys(true); //Take keys
 
@@ -82,7 +89,7 @@
             memset(LDRReadings, 0.0, BUFFERSIZE * sizeof(float));
             memset(timeReadings, 0.0, BUFFERSIZE * sizeof(float));
 
-            nextIndex = 0;      //Reset Index
+            nextIndex = 0;   //Reset Index
             currentIndex = 0;
             oldestIndex = 0;
 
@@ -96,9 +103,9 @@
 
 
         } else if (InputBufferString == "read") {
-
+            //Reads past <n> records
             PC.printf("How many records would you like to view:\n\r");
-            PC.attach(&RXInterruptISR); //Enable interrupt
+            PC.attach(&RXInterruptISR);  //Enable interrupt
             Thread::signal_wait(1);      //Wait untill signal set
 
             PC.scanf("%d", &InputBufferNum); //Scan serial
@@ -112,7 +119,7 @@
             PC.printf("  Date  |  Time  | Temp | Pressure | Light\n\r");
             TakeKeys(true); //Take keys
 
-            for (short i = 0; i < InputBufferNum; i++) { //For loop of length InputBufferNum                
+            for (short i = 0; i < InputBufferNum; i++) { //For loop of length InputBufferNum
                 tm T = ReturnDateTimeStruct(timeReadings[internalIndex]);
                 PC.printf(" %4d/%2d/%2d    %2d:%2d:%2d    %2.2f     %2.2f     %2.2f\n\r",T.tm_year,T.tm_mon,T.tm_mday,T.tm_hour,T.tm_min,T.tm_sec,tempReadings[internalIndex],presReadings[internalIndex],LDRReadings[internalIndex]);
                 internalIndex = IndexDecrement(internalIndex); //Decrement internal index
@@ -121,7 +128,7 @@
 
 
         } else if (InputBufferString == "delete") {
-
+            //Deletes oldest <n> records
             PC.printf("How many records would you like to delete:\n\r");
             PC.attach(&RXInterruptISR); //Enable interrupt
             Thread::signal_wait(1);      //Wait untill signal set
@@ -136,7 +143,7 @@
                 LDRReadings[oldestIndex] = 0;
                 timeReadings[oldestIndex] = 0;
 
-                oldestIndex = IndexIncrement(oldestIndex);
+                oldestIndex = IndexIncrement(oldestIndex); //Increment index
             }
 
             TakeKeys(false); //Return keys
@@ -145,11 +152,11 @@
 
 
         } else if (InputBufferString == "setdate") {
-
+            //Set date YYYY/MM/DD
             Sampling(false);  //Stop sampling
             PC.printf("Setting Date\n\r");
 
-            for (int i = 0; i < 3; i++) {
+            for (int i = 0; i < 3; i++) { //Changes message on each iteration
                 if (i==0) {
                     PC.printf("Input Year <YYYY>:\n\r");
                 } else if(i==1) {
@@ -158,23 +165,23 @@
                     PC.printf("Input Date <DD>:\n\r");
                 }
 
-                PC.attach(&RXInterruptISR); //Enable interrupt
+                PC.attach(&RXInterruptISR);  //Enable interrupt
                 Thread::signal_wait(1);      //Wait untill signal set
 
                 PC.scanf("%d", &DateTimeVar[i]); //Scan serial
             }
 
-            SetDate(DateTimeVar[2], DateTimeVar[1], DateTimeVar[0]);
+            SetDate(DateTimeVar[2], DateTimeVar[1], DateTimeVar[0]); //Set date
             PC.printf("Date set to : %d/%d/%d",DateTimeVar[2], DateTimeVar[1], DateTimeVar[0]);
             Sampling(true);  //Stop sampling
 
 
         } else if (InputBufferString == "settime") {
-
+            //Set time hh/mm/ss
             Sampling(false);  //Stop sampling
             PC.printf("Setting Time\n\r");
 
-            for (int i = 0; i < 3; i++) {
+            for (int i = 0; i < 3; i++) { //Changes message on each iteration
                 if (i==0) {
                     PC.printf("Input Hour <hh>:\n\r");
                 } else if(i==1) {
@@ -183,30 +190,50 @@
                     PC.printf("Input Seccond <ss>:\n\r");
                 }
 
-                PC.attach(&RXInterruptISR); //Enable interrupt
+                PC.attach(&RXInterruptISR);  //Enable interrupt
                 Thread::signal_wait(1);      //Wait untill signal set
 
                 PC.scanf("%d", &DateTimeVar[i]); //Scan serial
             }
 
-            SetTime(DateTimeVar[0], DateTimeVar[1], DateTimeVar[2]);
+            SetTime(DateTimeVar[0], DateTimeVar[1], DateTimeVar[2]); //Set time
             PC.printf("Time set to : %d:%d:%d",DateTimeVar[0], DateTimeVar[1], DateTimeVar[2]);
             Sampling(true);  //Stop sampling
 
 
         } else if (InputBufferString == "sett") {
+            //Set sample rate
+            PC.printf("What would you like to set the sample rate to:\n\r");
+            PC.attach(&RXInterruptISR);  //Enable interrupt
+            Thread::signal_wait(1);      //Wait untill signal set
+
+            PC.scanf("%d", &SAMPLERATE); //Scan serial
+
+            ConfigThreadsAndIR(); //Reattach ticker
+
+            PC.printf("Sample rate set to: %d\n\r",SAMPLERATE);
 
 
         } else if (InputBufferString == "state") {
-            
+            //Toggle sampling
+            SerialState = !SerialState; //Toggle state
+            if (SerialState) {
+                Sampling(true); //Start sampling
+                PC.printf("Sampling started\n\r");
+            } else {
+                Sampling(false);//Stop sampling
+                PC.printf("Sampling stopped\n\r");
+            }
+
 
 
         } else if (InputBufferString == "logging") {
-            internalIndex = currentIndex;
-            for (short i = 0; i < BUFFERSIZE; i++) { //For loop of length buffersize
-                //InternalIndex was set as newest. We will now decrement to display oldest to newest
-                PC.printf(" %d\n\r",timeReadings[internalIndex]);
-                internalIndex = IndexDecrement(internalIndex); //Decrement internal index
+            //Toggle logging
+            logging = !logging; //Toggle state
+            if (logging) {
+                PC.printf("Logging started");
+            } else {
+                PC.printf("Logging stopped");
             }
         }
 
--- a/Serial.h	Tue Jan 09 11:53:11 2018 +0000
+++ b/Serial.h	Tue Jan 09 20:51:19 2018 +0000
@@ -1,20 +1,37 @@
 #ifndef __Serial__
 #define __Serial__
 /*
-* These functions handle the USB serial interface
+*This module handles all serial communications with a PC over USB. 
+*Serial code is attached to its own thread and is run when the RX interrupt is triggered.
+*The RX interrupt is triggered when someone starts typing in a PC terminal. 
+*The Scanf function is then started to capture the input. 
+*There are a list of commands that are used with serial:
+
+* readall
+* deleteall
+* read <n>
+* delete <n>
+* setdate <dd><mm><yyyy>
+* settime <hh><mm><ss>
+* sett <T>
+* state <x>
+* logging <x>
+
 */
 
 #include "mbed.h"
 #include "Sampling.h"
+#include "Logging.h"
 
 //Variables
-extern int DateTimeVar[3];
-extern char InputBufferText[128];
-extern unsigned short InputBufferNum;
-extern unsigned short internalIndex;
+extern int DateTimeVar[3];  //Used for reading date or time from serial
+extern bool SerialState;    //Used for toggling sampling
+extern char InputBufferText[128];   //Buffer for incoming chars
+extern unsigned short InputBufferNum;   //Buffer for incoming numbers
+extern unsigned short internalIndex;    //Used for incrementing out sample data
 
 //Objects
-extern Thread SampleThread; //
+extern Thread SampleThread; 
 extern Serial PC;
 
 //Functions
--- a/WebUI.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/WebUI.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -41,15 +41,12 @@
 
 void WebUISetup(void)
 {
-    //printf("Basic HTTP server example\n\r");
-
     //Configure an ethernet connection
-
     eth.set_network(IP, NETMASK, GATEWAY);
     eth.connect();
-    //printf("The target IP address is '%s'\n\r", eth.get_ip_address());
-
-
+    
+    PC.printf("The target IP address is '%s'\n\r", eth.get_ip_address());
+    LogEvent(Log_EthConfig);
 
     /* Open the server on ethernet stack */
     srv.open(&eth);
@@ -67,9 +64,8 @@
     while (true) {
         //Block and wait on an incoming connection
         srv.accept(&clt_sock, &clt_addr);
-
-        //Show that an event has been recieved.
-        //printf("accept %s:%d\n\r", clt_addr.get_ip_address(), clt_addr.get_port());
+        
+        LogEvent(Log_EthRequest); //Request recived
 
         //This string will hold the HTML that will be sent to the browser
         string response;
--- a/WebUI.h	Tue Jan 09 11:53:11 2018 +0000
+++ b/WebUI.h	Tue Jan 09 20:51:19 2018 +0000
@@ -13,6 +13,8 @@
 #include "TCPServer.h"
 #include "TCPSocket.h"
 #include "TimeInterface.h"
+#include "Logging.h"
+#include "Serial.h"
 #include <iostream> 
 
 extern Thread WebThread;
--- a/main.cpp	Tue Jan 09 11:53:11 2018 +0000
+++ b/main.cpp	Tue Jan 09 20:51:19 2018 +0000
@@ -8,31 +8,36 @@
 #include "Logging.h"
 
 //Hardware setup
-BMP280 sensor(D14, D15);    //enviromental sensor
-AnalogIn LDRSensor(A0);     //LDR sensor
-DigitalOut SamplingLED(PB_10);//LED to indicate sampling
+BMP280 sensor(D14, D15);        //Enviromental sensor
+AnalogIn LDRSensor(A0);         //LDR sensor      
+DigitalOut SamplingLED(PB_10);  //LED to indicate sampling
+             
 //SD Card devices
 InterruptIn SD_WP(PE_10);
 InterruptIn UserButton(USER_BUTTON);
 SDBlockDevice sd(PB_5, D12, D13, D10);
 DigitalOut GreenLED(PB_11);
 
-Serial PC(USBTX, USBRX);    //Serial interface
-//SD Card Object
-ENVDISPLAY lcd(D9, D8, D7, D6, D4, D2,PE_12, PE_14);    //LCD pins and two timeset buttons
+//Serial interface
+Serial PC(USBTX, USBRX);    
+
+//LCD card object. LCD pins and two timeset buttons
+ENVDISPLAY lcd(D9, D8, D7, D6, D4, D2,PE_12, PE_14);   
 
 int main()
 {
     //Initialise devices
     firstSample = true; //Set only at start of program
-    logging = true;
+    logging = false;
+    
     //Hardware Self Test
+    
 
     //Initialise interrupts and times
-    SerialStart();  //Start serial comms
-    lcd.Start();    //Start LCD functionality
-    SDCardInit();   //Start SDCard functionality
-    WebUISetup();   //Start Web Interface
+    SerialStart();        //Start serial comms
+    lcd.Start();          //Start LCD functionality
+    SDCardInit();         //Start SDCard functionality
+    WebUISetup();         //Start Web Interface
     ConfigThreadsAndIR(); //Start sampling
 
 
@@ -40,15 +45,16 @@
     while (true) {
         if (NewEnvSample && NewLDRSample) {
             //New samples have been captured and are in the register
-            IncrementIndex();
+            IncrementIndex();       //Index for buffers
             NewEnvSample = false;   //Reset sampling threads
             NewLDRSample = false;
 
-            //push latest samples to LCD.
+            //Push latest samples to LCD.
             lcd.UpdateData(tempReadings[currentIndex],presReadings[currentIndex],LDRReadings[currentIndex],timeReadings[currentIndex]);
             LogEvent(Log_IndexInc);   //Log position
         }
         if (logging) {
+            //Grab from mailbox and print to serial
             string QueueData = CheckLoggingQueue(); //Get the data from queue
             char char_array[QueueData.length()+1];  //Char array for message
             strcpy(char_array, QueueData.c_str());  //String must be converted to char array for printf