SD card functionality

Dependents:   ELEC350_Project2 SDcard

Revision:
11:89960c1f2234
Parent:
10:f2b8e3b587d5
Child:
12:3198f0b7b36f
--- a/SDCard.cpp	Wed Dec 19 15:29:27 2018 +0000
+++ b/SDCard.cpp	Fri Dec 21 09:58:51 2018 +0000
@@ -55,19 +55,81 @@
 
 void SDread(int n)
 {
-    //Read n samples from the SD card
+    //Read n samples from the SD card    
     printlock.lock();
-    if (n == -1) puts("Received command to read all");
-    else printf("Received command to read %d\n", n);
+    if (n == -1)
+    {
+        unsigned int i=newestIndex;
+        unsigned int j = 0;
+        bufferLock.lock();
+        while (i != oldestIndex)
+        {            
+            i = (i ? i : BUFFERSIZE) - 1; //if i is not 0 subtract 1. if it is 0, set to buffersize - 1
+            pc->printf("Date/Time: %s\tTemperature: %5.2f\tPressure: %5.2f\tLight: %5.2f\n\r", buffer[i].getTime(), buffer[i].gettemp(), buffer[i].getpress(), buffer[i].getlight()); 
+            j++;
+        }
+        bufferLock.unlock();
+        
+        printf("%d records read\r\n\n\n", j);
+    }
+    else 
+    {
+        //printf("Received command to read %d\n\r", n);
+        /*
+        Read from newestIndex back by n, until either newestIndex - n or oldestindex
+        */
+        unsigned int i;
+        unsigned int j = newestIndex;
+        bufferLock.lock();
+        for (i = 0; i<n; i++)
+        {
+            if (j == oldestIndex) {break;}
+            j = (j ? j : BUFFERSIZE) - 1;
+            pc->printf("Date/Time: %s\tTemperature: %5.2f\tPressure: %5.2f\tLight: %5.2f\n\r", buffer[j].getTime(), buffer[j].gettemp(), buffer[j].getpress(), buffer[j].getlight());           
+        }
+        bufferLock.unlock();
+        
+        printf("%d records read\r\n\n\n", i);
+    }
     printlock.unlock();
+    
 }
 
 void SDdelete(int n)
 {
     //Delete n samples from the SD card
     printlock.lock();
-    if (n == -1) puts("Received command to delete all");
-    else printf("Received command to delete %d\n", n); 
+    if (n == -1) 
+    {
+        unsigned int i = newestIndex;
+        unsigned int j = 0;
+        
+        while (i != oldestIndex)
+        {
+            i = (i ? i : BUFFERSIZE) - 1;
+            j++;
+        }
+        
+        oldestIndex = 0;
+        newestIndex = 0;
+        pc->printf("Deleted %d records\r\n\n\n", j);        
+    }
+    else 
+    {
+        //printf("Received command to delete %d\n", n); 
+        //move oldestIndex forwards for the given number or until you hit newestIndex
+        unsigned int i;
+        unsigned int j = oldestIndex;
+        bufferLock.lock();
+        for (i = 0; i<n; i++)
+        {
+            if (j == newestIndex) {break;}
+            j = (j + 1) % BUFFERSIZE;
+        } 
+        oldestIndex = j;
+        bufferLock.unlock();
+        printf("Deleted %d records\r\n\n\n", i);
+    }
     printlock.unlock();  
 }