Logger to USB stick running on KL25Z

Dependencies:   F401RE-USBHost FastAnalogIn RTC mbed tsi_sensor2 mbed-rtos2

Fork of ReadSendData by Stuart Scott

Homepage for kXX_logger(was kl25x_usb_logger)

2014Nov12 - Added TSI - only works for kl25z, and fails after 4287seconds

Tests sequences for freezing 4287seconds 4287 4287 - Changed to USB write update every two seconds and lasted 4283seconds. Added mbed TSI_sensor - kudos to mbed as it turns out to be complex to do capacitive touch sensing. Kinetis L series Cortex-M0 (kl25z) has simpler capacitive sensing hardware which mbed/TSI_sensor lib uses, but doesn't support Cortex-M4 versions. K20D is older more complex interface. TSS hasn't had an open source support by Freescale in the past however that has changed. Currently I found KDS1.1.1 has a Processor Expert TSSlib that can be imported - but I'm getting a weird compile/include error - and not found any examples of how to make it work.

2014Oct05 - Published simple kl25z_usb_logger

Testing: Version (2:f06fbf86887e) has run over 28days starting 2014Sept07, reading a sensor data every seconds and then on the USB stick open file, write record, close file

This is over 2,419,200seconds ( 28days*24hrs*3600seconds) The stick data reflected 2,447,633 seconds, but only had 1,776,366 data records. After 407,650 data records started missing updates - analysis: the file could not be opened and read to the end in the allocated 1 second, and therefore missed the next ADC deadline.

By the end of the test period with 1,776,366 records on the USB Stick, ever read then write was causing it to miss two/three ADC updates - ie taking longer than two seconds.

Analysis: this was an aggressive test, and normally would not be opening, writing, closing every 1 second. However big plus the file mechanism held up and the program continued to operate, with a graceful failure of a missed ADC readings. The output used JSON, which reads nicely but turns out not to be supported by Excel (2014?) I was using.

Conclusion: Overall the USB Mechanisms and file read is stable. However the USB stack used doesn't have an event based management for stick insertion and removal, or OTG power management . This KL25Z has been a very useful test to prove the configuration of clocks for USB Stack is possible and stable. The target processor being looked at is the MK20 and is similar in clocks, but slightly more comprehensive USB OTG Next step is to investigate the full Freescale Kinetis USB OTG Stack with power management on a custom K20 board, using Kinetis Design Studio, and very low power capability.

Example https://github.com/ErichStyger/mcuoneclipse/tree/master/Examples/FRDM-K20D50M/FRDM-K20_MSD_Host http://mcuoneclipse.com/2014/10/25/usb-cdc-with-the-frdm-k64f-finally/#comment-37727 - Commentary on Freescale USB versions

Revision:
15:91ef840c442c
Parent:
13:729f5ae38c24
--- a/main.cpp	Thu Nov 13 19:29:11 2014 +0000
+++ b/main.cpp	Tue May 19 16:03:50 2015 +0000
@@ -50,9 +50,11 @@
 */
 
 #include "mbed.h"
+//#include "rtos.h"
 #include "rtc_api.h"
 #include "FastAnalogIn.h"
 #include "USBHostMSD.h"
+#include "board_cust.h"
 
 
 #if defined(TARGET_K20D50M)
@@ -72,6 +74,7 @@
    //TSIElectrode tsiElec1(ELEC1);
    //#define TsiRead()  tsi.readDistance() - has problesm
    #define TsiRead()  tsi.readPercentage()
+   
 #elif defined (TARGET_KL05Z)
   #define TsiActive 0
   #include "TSISensor.h"
@@ -86,7 +89,7 @@
 #endif
 
 
-//size of sample  buffer 
+//size of Customer ADC sample  buffer 
 #define BuffSize 16  //16 to test, upto kl25z spare ram of about xxxx?, !2000, linker warns if too large, but also fails
 #define SAMPLE_WIN 8 // Should be less than BuffSize
 #if BuffSize < SAMPLE_WIN
@@ -97,6 +100,7 @@
 
 using namespace mbed;
 
+
 //Device Init - per FRDM-KL25Z
 DigitalOut ledRed(LED1); 
 //DigitalOut ledGrn(LED2); 
@@ -116,7 +120,7 @@
  unsigned int time_[BuffSize];
 
 
- FILE* fpUsb;
+ 
  bool UsbPresent=0;
  bool warmBoot = rtc_isenabled(); 
  long lp2i =0;
@@ -124,8 +128,7 @@
  unsigned int tmrE_evt; //Elapsed
  Ticker tock; //periodic tick
 
- USBHostMSD  msd("usbAa"); //defines the file system access
-    
+     
 #if defined(TARGET_K20D50M)
 const char meProc[] = "K20D50M";
 #elif defined(TARGET_KL25Z)
@@ -149,12 +152,12 @@
 /* Process output Header to USB, 
 return !0 if valid USB present
 */
- bool outputHeaderUsb() {
+ bool outputHeaderUsb(FILE* fpUsb) {
     // JSON {"headings":{"time":{"elapsed":"seconds"},  "adcN":"normalized_to_1.0", "adcV":"Volts"}}
     
     if (!UsbPresent) 
     {
-      if (msd.connect()) //Attempt to find a device
+      if (1/*ToDo msd.connect()*/) //Attempt to find a device
       {//USB Event: newly connected so attempt write header
         if (NULL !=(fpUsb = fopen("/usbAa/test1.txt", "a"))) 
         {
@@ -174,7 +177,7 @@
       } //else //Can't find USB device
     } else {
         // UsbPresent and assume headers written
-        if (!msd.connected()) 
+        if (1/*ToDo !msd.connected()*/) 
         {
           pc.printf("  USB Flash drive removed.\n\r");
           UsbPresent=0;
@@ -185,7 +188,7 @@
 }
 //--------------------------------------------------------------
  void outputHeaders(void) {
-    outputHeaderUsb();
+    //ToDo - outputHeaderUsb(*fp);
     pc.printf("  Time(S)   depthR(norm) Volts Idx %d\n\r",(unsigned int) rtc_read());
 }//outputHeaders
 
@@ -201,13 +204,13 @@
  adcNorm:<float number 0.0-1.0>, 
  adcV:<Volts 0-VRef>
  */
-bool manageUsbWrite() {
+bool manageUsbWrite(FILE* fpUsb) {
 #define ADC_NORMALIZE (1.0f/65535.0f)
 #define ADC_NORM_VREF 3.3
     float data_n=( ((float)sample_u16[lp2i]) * ADC_NORMALIZE);
     bool writeUsb=0;
     //Future redesign to use USBHALHost::wait_attach()
-    if (outputHeaderUsb()) 
+    if (outputHeaderUsb(fpUsb)) 
     {
       if (NULL !=(fpUsb = fopen("/usbAa/test1.txt", "a"))) 
       {  
@@ -280,7 +283,7 @@
     //ledGrn = !(lp2i&0x01);//!ledGrn; syncs with blue led flashing    
     //ledPwmGrn = ((lp2i&0x01) ? (1.0-? ? ?) : 1.0 ); //LEDGrn=1 off, =0 On
     if (lp2i&0x01) {//Only write every two times
-        if (1==manageUsbWrite()) {
+        if (1/*ToDo==manageUsbWrite(*fp)*/) {
             ledBlue = !ledBlue; //(lp2i&0x03);
         } else {ledBlue =1;}//off
     }
@@ -296,14 +299,57 @@
     if (++lp2i >= BuffSize) lp2i=0;
     sample_u16[lp2i]=ainPinAA.read_u16();
     time_[lp2i]=(unsigned int)tmrE_evt; //TODO - replace with wall time
+#if TsiActive
     tsiSlider_dist = TsiRead();
     electr[lp2i]= tsi.getDelta0();
+#endif //TsiActive
     
     //elec1p = tsi.getDelta1();    
     //tsiSlider_dist = (float)tsi.readPercentage(); 
        
  }//manageAdcIn
  
+ //--------------------------------------------------------------
+ void UsbHostMsd_task(void const *) {
+     USBHostMSD  msd("usbAa"); //defines the file system access
+    int i = 0;
+    
+    while(1) {
+        
+        // try to connect a MSD device
+        while(!msd.connect()) {
+            //Thread::wait(500);
+        }
+        
+        // in a loop, append a file
+        // if the device is disconnected, we try to connect it again
+        while(1) {
+            
+            // append a file
+            FILE * fp = fopen("/usb/test1.txt", "a");
+        
+            if (fp != NULL) {
+                fprintf(fp, "Hello fun SD Card World: %d!\r\n", i++);
+                printf("Goodbye World!\r\n");
+                fclose(fp);
+            } else {
+                printf("FILE == NULL\r\n");
+            }
+            
+            //Thread::wait(500);
+        
+            // if device disconnected, try to connect again
+            if (!msd.connected())
+                break;
+        }
+            
+    }
+}
+/* Input parser from usb - but how large is buffer
+  char buffer[128];    
+  pc.gets(buffer, 4);
+  pc.printf("I got '%s'\n", buffer);  
+*/
 //--------------------------------------------------------------
 int main() {
 
@@ -319,6 +365,9 @@
     //ledGrn =1; //off
     ledPwmGrn =1.0; //off
     ledBlue = 1; //on    
+    
+    //Thread msdTask(UsbHostMsd_task, NULL, osPriorityNormal, 1024 * 4);
+    
     wait_ms(5000); 
     //Thread::wait(2000);
     ledRed =1;//Off