AvrAdcLogger.ino 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /**
  2. * This program logs data from the Arduino ADC to a binary file.
  3. *
  4. * Samples are logged at regular intervals. Each Sample consists of the ADC
  5. * values for the analog pins defined in the PIN_LIST array. The pins numbers
  6. * may be in any order.
  7. *
  8. * Edit the configuration constants below to set the sample pins, sample rate,
  9. * and other configuration values.
  10. *
  11. * If your SD card has a long write latency, it may be necessary to use
  12. * slower sample rates. Using a Mega Arduino helps overcome latency
  13. * problems since more 64 byte buffer blocks will be used.
  14. *
  15. * Each 64 byte data block in the file has a four byte header followed by up
  16. * to 60 bytes of data. (60 values in 8-bit mode or 30 values in 10-bit mode)
  17. * Each block contains an integral number of samples with unused space at the
  18. * end of the block.
  19. *
  20. */
  21. #ifdef __AVR__
  22. #include <SPI.h>
  23. #include "SdFat.h"
  24. #include "BufferedPrint.h"
  25. #include "FreeStack.h"
  26. #include "AvrAdcLogger.h"
  27. // Save SRAM if 328.
  28. #ifdef __AVR_ATmega328P__
  29. #include "MinimumSerial.h"
  30. MinimumSerial MinSerial;
  31. #define Serial MinSerial
  32. #endif // __AVR_ATmega328P__
  33. //------------------------------------------------------------------------------
  34. // This example was designed for exFAT but will support FAT16/FAT32.
  35. //
  36. // Note: Uno will not support SD_FAT_TYPE = 3.
  37. // SD_FAT_TYPE = 0 for SdFat/File as defined in SdFatConfig.h,
  38. // 1 for FAT16/FAT32, 2 for exFAT, 3 for FAT16/FAT32 and exFAT.
  39. #define SD_FAT_TYPE 2
  40. //------------------------------------------------------------------------------
  41. // Set USE_RTC nonzero for file timestamps.
  42. // RAM use will be marginal on Uno with RTClib.
  43. // Set USE_RTC nonzero for file timestamps.
  44. // RAM use will be marginal on Uno with RTClib.
  45. // 0 - RTC not used
  46. // 1 - DS1307
  47. // 2 - DS3231
  48. // 3 - PCF8523
  49. #define USE_RTC 0
  50. #if USE_RTC
  51. #include "RTClib.h"
  52. #endif // USE_RTC
  53. //------------------------------------------------------------------------------
  54. // Pin definitions.
  55. //
  56. // Digital pin to indicate an error, set to -1 if not used.
  57. // The led blinks for fatal errors. The led goes on solid for SD write
  58. // overrun errors and logging continues.
  59. const int8_t ERROR_LED_PIN = -1;
  60. // SD chip select pin.
  61. const uint8_t SD_CS_PIN = SS;
  62. //------------------------------------------------------------------------------
  63. // Analog pin number list for a sample. Pins may be in any order and pin
  64. // numbers may be repeated.
  65. const uint8_t PIN_LIST[] = {0, 1, 2, 3, 4};
  66. //------------------------------------------------------------------------------
  67. // Sample rate in samples per second.
  68. const float SAMPLE_RATE = 5000; // Must be 0.25 or greater.
  69. // The interval between samples in seconds, SAMPLE_INTERVAL, may be set to a
  70. // constant instead of being calculated from SAMPLE_RATE. SAMPLE_RATE is not
  71. // used in the code below. For example, setting SAMPLE_INTERVAL = 2.0e-4
  72. // will result in a 200 microsecond sample interval.
  73. const float SAMPLE_INTERVAL = 1.0/SAMPLE_RATE;
  74. // Setting ROUND_SAMPLE_INTERVAL non-zero will cause the sample interval to
  75. // be rounded to a a multiple of the ADC clock period and will reduce sample
  76. // time jitter.
  77. #define ROUND_SAMPLE_INTERVAL 1
  78. //------------------------------------------------------------------------------
  79. // Reference voltage. See the processor data-sheet for reference details.
  80. // uint8_t const ADC_REF = 0; // External Reference AREF pin.
  81. uint8_t const ADC_REF = (1 << REFS0); // Vcc Reference.
  82. // uint8_t const ADC_REF = (1 << REFS1); // Internal 1.1 (only 644 1284P Mega)
  83. // uint8_t const ADC_REF = (1 << REFS1) | (1 << REFS0); // Internal 1.1 or 2.56
  84. //------------------------------------------------------------------------------
  85. // File definitions.
  86. //
  87. // Maximum file size in bytes.
  88. // The program creates a contiguous file with MAX_FILE_SIZE_MiB bytes.
  89. // The file will be truncated if logging is stopped early.
  90. const uint32_t MAX_FILE_SIZE_MiB = 100; // 100 MiB file.
  91. // log file name. Integer field before dot will be incremented.
  92. #define LOG_FILE_NAME "AvrAdc00.bin"
  93. // Maximum length name including zero byte.
  94. const size_t NAME_DIM = 40;
  95. // Set RECORD_EIGHT_BITS non-zero to record only the high 8-bits of the ADC.
  96. #define RECORD_EIGHT_BITS 0
  97. //------------------------------------------------------------------------------
  98. // FIFO size definition. Use a multiple of 512 bytes for best performance.
  99. //
  100. #if RAMEND < 0X8FF
  101. #error SRAM too small
  102. #elif RAMEND < 0X10FF
  103. const size_t FIFO_SIZE_BYTES = 512;
  104. #elif RAMEND < 0X20FF
  105. const size_t FIFO_SIZE_BYTES = 4*512;
  106. #elif RAMEND < 0X40FF
  107. const size_t FIFO_SIZE_BYTES = 12*512;
  108. #else // RAMEND
  109. const size_t FIFO_SIZE_BYTES = 16*512;
  110. #endif // RAMEND
  111. //------------------------------------------------------------------------------
  112. // ADC clock rate.
  113. // The ADC clock rate is normally calculated from the pin count and sample
  114. // interval. The calculation attempts to use the lowest possible ADC clock
  115. // rate.
  116. //
  117. // You can select an ADC clock rate by defining the symbol ADC_PRESCALER to
  118. // one of these values. You must choose an appropriate ADC clock rate for
  119. // your sample interval.
  120. // #define ADC_PRESCALER 7 // F_CPU/128 125 kHz on an Uno
  121. // #define ADC_PRESCALER 6 // F_CPU/64 250 kHz on an Uno
  122. // #define ADC_PRESCALER 5 // F_CPU/32 500 kHz on an Uno
  123. // #define ADC_PRESCALER 4 // F_CPU/16 1000 kHz on an Uno
  124. // #define ADC_PRESCALER 3 // F_CPU/8 2000 kHz on an Uno (8-bit mode only)
  125. //==============================================================================
  126. // End of configuration constants.
  127. //==============================================================================
  128. // Temporary log file. Will be deleted if a reset or power failure occurs.
  129. #define TMP_FILE_NAME "tmp_adc.bin"
  130. // Number of analog pins to log.
  131. const uint8_t PIN_COUNT = sizeof(PIN_LIST)/sizeof(PIN_LIST[0]);
  132. // Minimum ADC clock cycles per sample interval
  133. const uint16_t MIN_ADC_CYCLES = 15;
  134. // Extra cpu cycles to setup ADC with more than one pin per sample.
  135. const uint16_t ISR_SETUP_ADC = PIN_COUNT > 1 ? 100 : 0;
  136. // Maximum cycles for timer0 system interrupt.
  137. const uint16_t ISR_TIMER0 = 160;
  138. //==============================================================================
  139. const uint32_t MAX_FILE_SIZE = MAX_FILE_SIZE_MiB << 20;
  140. // Max SPI rate for AVR is 10 MHz for F_CPU 20 MHz, 8 MHz for F_CPU 16 MHz.
  141. #define SPI_CLOCK SD_SCK_MHZ(10)
  142. // Select fastest interface.
  143. #if ENABLE_DEDICATED_SPI
  144. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SPI_CLOCK)
  145. #else // ENABLE_DEDICATED_SPI
  146. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SPI_CLOCK)
  147. #endif // ENABLE_DEDICATED_SPI
  148. #if SD_FAT_TYPE == 0
  149. SdFat sd;
  150. typedef File file_t;
  151. #elif SD_FAT_TYPE == 1
  152. SdFat32 sd;
  153. typedef File32 file_t;
  154. #elif SD_FAT_TYPE == 2
  155. SdExFat sd;
  156. typedef ExFile file_t;
  157. #elif SD_FAT_TYPE == 3
  158. SdFs sd;
  159. typedef FsFile file_t;
  160. #else // SD_FAT_TYPE
  161. #error Invalid SD_FAT_TYPE
  162. #endif // SD_FAT_TYPE
  163. file_t binFile;
  164. file_t csvFile;
  165. char binName[] = LOG_FILE_NAME;
  166. #if RECORD_EIGHT_BITS
  167. const size_t BLOCK_MAX_COUNT = PIN_COUNT*(DATA_DIM8/PIN_COUNT);
  168. typedef block8_t block_t;
  169. #else // RECORD_EIGHT_BITS
  170. const size_t BLOCK_MAX_COUNT = PIN_COUNT*(DATA_DIM16/PIN_COUNT);
  171. typedef block16_t block_t;
  172. #endif // RECORD_EIGHT_BITS
  173. // Size of FIFO in blocks.
  174. size_t const FIFO_DIM = FIFO_SIZE_BYTES/sizeof(block_t);
  175. block_t* fifoData;
  176. volatile size_t fifoCount = 0; // volatile - shared, ISR and background.
  177. size_t fifoHead = 0; // Only accessed by ISR during logging.
  178. size_t fifoTail = 0; // Only accessed by writer during logging.
  179. //==============================================================================
  180. // Interrupt Service Routines
  181. // Disable ADC interrupt if true.
  182. volatile bool isrStop = false;
  183. // Pointer to current buffer.
  184. block_t* isrBuf = nullptr;
  185. // overrun count
  186. uint16_t isrOver = 0;
  187. // ADC configuration for each pin.
  188. uint8_t adcmux[PIN_COUNT];
  189. uint8_t adcsra[PIN_COUNT];
  190. uint8_t adcsrb[PIN_COUNT];
  191. uint8_t adcindex = 1;
  192. // Insure no timer events are missed.
  193. volatile bool timerError = false;
  194. volatile bool timerFlag = false;
  195. //------------------------------------------------------------------------------
  196. // ADC done interrupt.
  197. ISR(ADC_vect) {
  198. // Read ADC data.
  199. #if RECORD_EIGHT_BITS
  200. uint8_t d = ADCH;
  201. #else // RECORD_EIGHT_BITS
  202. // This will access ADCL first.
  203. uint16_t d = ADC;
  204. #endif // RECORD_EIGHT_BITS
  205. if (!isrBuf) {
  206. if (fifoCount < FIFO_DIM) {
  207. isrBuf = fifoData + fifoHead;
  208. } else {
  209. // no buffers - count overrun
  210. if (isrOver < 0XFFFF) {
  211. isrOver++;
  212. }
  213. // Avoid missed timer error.
  214. timerFlag = false;
  215. return;
  216. }
  217. }
  218. // Start ADC for next pin
  219. if (PIN_COUNT > 1) {
  220. ADMUX = adcmux[adcindex];
  221. ADCSRB = adcsrb[adcindex];
  222. ADCSRA = adcsra[adcindex];
  223. if (adcindex == 0) {
  224. timerFlag = false;
  225. }
  226. adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0;
  227. } else {
  228. timerFlag = false;
  229. }
  230. // Store ADC data.
  231. isrBuf->data[isrBuf->count++] = d;
  232. // Check for buffer full.
  233. if (isrBuf->count >= BLOCK_MAX_COUNT) {
  234. fifoHead = fifoHead < (FIFO_DIM - 1) ? fifoHead + 1 : 0;
  235. fifoCount++;
  236. // Check for end logging.
  237. if (isrStop) {
  238. adcStop();
  239. return;
  240. }
  241. // Set buffer needed and clear overruns.
  242. isrBuf = nullptr;
  243. isrOver = 0;
  244. }
  245. }
  246. //------------------------------------------------------------------------------
  247. // timer1 interrupt to clear OCF1B
  248. ISR(TIMER1_COMPB_vect) {
  249. // Make sure ADC ISR responded to timer event.
  250. if (timerFlag) {
  251. timerError = true;
  252. }
  253. timerFlag = true;
  254. }
  255. //==============================================================================
  256. // Error messages stored in flash.
  257. #define error(msg) (Serial.println(F(msg)),errorHalt())
  258. #define assert(e) ((e) ? (void)0 : error("assert: " #e))
  259. //------------------------------------------------------------------------------
  260. //
  261. void fatalBlink() {
  262. while (true) {
  263. if (ERROR_LED_PIN >= 0) {
  264. digitalWrite(ERROR_LED_PIN, HIGH);
  265. delay(200);
  266. digitalWrite(ERROR_LED_PIN, LOW);
  267. delay(200);
  268. }
  269. }
  270. }
  271. //------------------------------------------------------------------------------
  272. void errorHalt() {
  273. // Print minimal error data.
  274. // sd.errorPrint(&Serial);
  275. // Print extended error info - uses extra bytes of flash.
  276. sd.printSdError(&Serial);
  277. // Try to save data.
  278. binFile.close();
  279. fatalBlink();
  280. }
  281. //------------------------------------------------------------------------------
  282. void printUnusedStack() {
  283. Serial.print(F("\nUnused stack: "));
  284. Serial.println(UnusedStack());
  285. }
  286. //------------------------------------------------------------------------------
  287. #if USE_RTC
  288. #if USE_RTC == 1
  289. RTC_DS1307 rtc;
  290. #elif USE_RTC == 2
  291. RTC_DS3231 rtc;
  292. #elif USE_RTC == 3
  293. RTC_PCF8523 rtc;
  294. #else // USE_RTC == type
  295. #error USE_RTC type not implemented.
  296. #endif // USE_RTC == type
  297. // Call back for file timestamps. Only called for file create and sync().
  298. void dateTime(uint16_t* date, uint16_t* time, uint8_t* ms10) {
  299. DateTime now = rtc.now();
  300. // Return date using FS_DATE macro to format fields.
  301. *date = FS_DATE(now.year(), now.month(), now.day());
  302. // Return time using FS_TIME macro to format fields.
  303. *time = FS_TIME(now.hour(), now.minute(), now.second());
  304. // Return low time bits in units of 10 ms.
  305. *ms10 = now.second() & 1 ? 100 : 0;
  306. }
  307. #endif // USE_RTC
  308. //==============================================================================
  309. #if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2
  310. #error unexpected ADC prescaler bits
  311. #endif
  312. //------------------------------------------------------------------------------
  313. inline bool adcActive() {return (1 << ADIE) & ADCSRA;}
  314. //------------------------------------------------------------------------------
  315. // initialize ADC and timer1
  316. void adcInit(metadata_t* meta) {
  317. uint8_t adps; // prescaler bits for ADCSRA
  318. uint32_t ticks = F_CPU*SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles.
  319. if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) {
  320. error("Invalid ADC reference");
  321. }
  322. #ifdef ADC_PRESCALER
  323. if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) {
  324. error("Invalid ADC prescaler");
  325. }
  326. adps = ADC_PRESCALER;
  327. #else // ADC_PRESCALER
  328. // Allow extra cpu cycles to change ADC settings if more than one pin.
  329. int32_t adcCycles = (ticks - ISR_TIMER0)/PIN_COUNT - ISR_SETUP_ADC;
  330. for (adps = 7; adps > 0; adps--) {
  331. if (adcCycles >= (MIN_ADC_CYCLES << adps)) {
  332. break;
  333. }
  334. }
  335. #endif // ADC_PRESCALER
  336. meta->adcFrequency = F_CPU >> adps;
  337. if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) {
  338. error("Sample Rate Too High");
  339. }
  340. #if ROUND_SAMPLE_INTERVAL
  341. // Round so interval is multiple of ADC clock.
  342. ticks += 1 << (adps - 1);
  343. ticks >>= adps;
  344. ticks <<= adps;
  345. #endif // ROUND_SAMPLE_INTERVAL
  346. if (PIN_COUNT > BLOCK_MAX_COUNT || PIN_COUNT > PIN_NUM_DIM) {
  347. error("Too many pins");
  348. }
  349. meta->pinCount = PIN_COUNT;
  350. meta->recordEightBits = RECORD_EIGHT_BITS;
  351. for (int i = 0; i < PIN_COUNT; i++) {
  352. uint8_t pin = PIN_LIST[i];
  353. if (pin >= NUM_ANALOG_INPUTS) {
  354. error("Invalid Analog pin number");
  355. }
  356. meta->pinNumber[i] = pin;
  357. // Set ADC reference and low three bits of analog pin number.
  358. adcmux[i] = (pin & 7) | ADC_REF;
  359. if (RECORD_EIGHT_BITS) {
  360. adcmux[i] |= 1 << ADLAR;
  361. }
  362. // If this is the first pin, trigger on timer/counter 1 compare match B.
  363. adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0;
  364. #ifdef MUX5
  365. if (pin > 7) {
  366. adcsrb[i] |= (1 << MUX5);
  367. }
  368. #endif // MUX5
  369. adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps;
  370. // First pin triggers on timer 1 compare match B rest are free running.
  371. adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC;
  372. }
  373. // Setup timer1
  374. TCCR1A = 0;
  375. uint8_t tshift;
  376. if (ticks < 0X10000) {
  377. // no prescale, CTC mode
  378. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
  379. tshift = 0;
  380. } else if (ticks < 0X10000*8) {
  381. // prescale 8, CTC mode
  382. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
  383. tshift = 3;
  384. } else if (ticks < 0X10000*64) {
  385. // prescale 64, CTC mode
  386. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10);
  387. tshift = 6;
  388. } else if (ticks < 0X10000*256) {
  389. // prescale 256, CTC mode
  390. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);
  391. tshift = 8;
  392. } else if (ticks < 0X10000*1024) {
  393. // prescale 1024, CTC mode
  394. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10);
  395. tshift = 10;
  396. } else {
  397. error("Sample Rate Too Slow");
  398. }
  399. // divide by prescaler
  400. ticks >>= tshift;
  401. // set TOP for timer reset
  402. ICR1 = ticks - 1;
  403. // compare for ADC start
  404. OCR1B = 0;
  405. // multiply by prescaler
  406. ticks <<= tshift;
  407. // Sample interval in CPU clock ticks.
  408. meta->sampleInterval = ticks;
  409. meta->cpuFrequency = F_CPU;
  410. float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval;
  411. Serial.print(F("Sample pins:"));
  412. for (uint8_t i = 0; i < meta->pinCount; i++) {
  413. Serial.print(' ');
  414. Serial.print(meta->pinNumber[i], DEC);
  415. }
  416. Serial.println();
  417. Serial.print(F("ADC bits: "));
  418. Serial.println(meta->recordEightBits ? 8 : 10);
  419. Serial.print(F("ADC clock kHz: "));
  420. Serial.println(meta->adcFrequency/1000);
  421. Serial.print(F("Sample Rate: "));
  422. Serial.println(sampleRate);
  423. Serial.print(F("Sample interval usec: "));
  424. Serial.println(1000000.0/sampleRate);
  425. }
  426. //------------------------------------------------------------------------------
  427. // enable ADC and timer1 interrupts
  428. void adcStart() {
  429. // initialize ISR
  430. adcindex = 1;
  431. isrBuf = nullptr;
  432. isrOver = 0;
  433. isrStop = false;
  434. // Clear any pending interrupt.
  435. ADCSRA |= 1 << ADIF;
  436. // Setup for first pin.
  437. ADMUX = adcmux[0];
  438. ADCSRB = adcsrb[0];
  439. ADCSRA = adcsra[0];
  440. // Enable timer1 interrupts.
  441. timerError = false;
  442. timerFlag = false;
  443. TCNT1 = 0;
  444. TIFR1 = 1 << OCF1B;
  445. TIMSK1 = 1 << OCIE1B;
  446. }
  447. //------------------------------------------------------------------------------
  448. inline void adcStop() {
  449. TIMSK1 = 0;
  450. ADCSRA = 0;
  451. }
  452. //------------------------------------------------------------------------------
  453. // Convert binary file to csv file.
  454. void binaryToCsv() {
  455. uint8_t lastPct = 0;
  456. block_t* pd;
  457. metadata_t* pm;
  458. uint32_t t0 = millis();
  459. // Use fast buffered print class.
  460. BufferedPrint<file_t, 64> bp(&csvFile);
  461. block_t binBuffer[FIFO_DIM];
  462. assert(sizeof(block_t) == sizeof(metadata_t));
  463. binFile.rewind();
  464. uint32_t tPct = millis();
  465. bool doMeta = true;
  466. while (!Serial.available()) {
  467. pd = binBuffer;
  468. int nb = binFile.read(binBuffer, sizeof(binBuffer));
  469. if (nb < 0) {
  470. error("read binFile failed");
  471. }
  472. size_t nd = nb/sizeof(block_t);
  473. if (nd < 1) {
  474. break;
  475. }
  476. if (doMeta) {
  477. doMeta = false;
  478. pm = (metadata_t*)pd++;
  479. if (PIN_COUNT != pm->pinCount) {
  480. error("Invalid pinCount");
  481. }
  482. bp.print(F("Interval,"));
  483. float intervalMicros = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency;
  484. bp.print(intervalMicros, 4);
  485. bp.println(F(",usec"));
  486. for (uint8_t i = 0; i < PIN_COUNT; i++) {
  487. if (i) {
  488. bp.print(',');
  489. }
  490. bp.print(F("pin"));
  491. bp.print(pm->pinNumber[i]);
  492. }
  493. bp.println();
  494. if (nd-- == 1) {
  495. break;
  496. }
  497. }
  498. for (size_t i = 0; i < nd; i++, pd++) {
  499. if (pd->overrun) {
  500. bp.print(F("OVERRUN,"));
  501. bp.println(pd->overrun);
  502. }
  503. for (size_t j = 0; j < pd->count; j += PIN_COUNT) {
  504. for (size_t i = 0; i < PIN_COUNT; i++) {
  505. if (!bp.printField(pd->data[i + j], i == (PIN_COUNT-1) ? '\n' : ',')) {
  506. error("printField failed");
  507. }
  508. }
  509. }
  510. }
  511. if ((millis() - tPct) > 1000) {
  512. uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100);
  513. if (pct != lastPct) {
  514. tPct = millis();
  515. lastPct = pct;
  516. Serial.print(pct, DEC);
  517. Serial.println('%');
  518. }
  519. }
  520. }
  521. if (!bp.sync() || !csvFile.close()) {
  522. error("close csvFile failed");
  523. }
  524. Serial.print(F("Done: "));
  525. Serial.print(0.001*(millis() - t0));
  526. Serial.println(F(" Seconds"));
  527. }
  528. //------------------------------------------------------------------------------
  529. void clearSerialInput() {
  530. uint32_t m = micros();
  531. do {
  532. if (Serial.read() >= 0) {
  533. m = micros();
  534. }
  535. } while (micros() - m < 10000);
  536. }
  537. //------------------------------------------------------------------------------
  538. void createBinFile() {
  539. binFile.close();
  540. while (sd.exists(binName)) {
  541. char* p = strchr(binName, '.');
  542. if (!p) {
  543. error("no dot in filename");
  544. }
  545. while (true) {
  546. p--;
  547. if (p < binName || *p < '0' || *p > '9') {
  548. error("Can't create file name");
  549. }
  550. if (p[0] != '9') {
  551. p[0]++;
  552. break;
  553. }
  554. p[0] = '0';
  555. }
  556. }
  557. Serial.print(F("Opening: "));
  558. Serial.println(binName);
  559. if (!binFile.open(binName, O_RDWR | O_CREAT)) {
  560. error("open binName failed");
  561. }
  562. Serial.print(F("Allocating: "));
  563. Serial.print(MAX_FILE_SIZE_MiB);
  564. Serial.println(F(" MiB"));
  565. if (!binFile.preAllocate(MAX_FILE_SIZE)) {
  566. error("preAllocate failed");
  567. }
  568. }
  569. //------------------------------------------------------------------------------
  570. bool createCsvFile() {
  571. char csvName[NAME_DIM];
  572. if (!binFile.isOpen()) {
  573. Serial.println(F("No current binary file"));
  574. return false;
  575. }
  576. binFile.getName(csvName, sizeof(csvName));
  577. char* dot = strchr(csvName, '.');
  578. if (!dot) {
  579. error("no dot in binName");
  580. }
  581. strcpy(dot + 1, "csv");
  582. if (!csvFile.open(csvName, O_WRONLY|O_CREAT|O_TRUNC)) {
  583. error("open csvFile failed");
  584. }
  585. Serial.print(F("Writing: "));
  586. Serial.print(csvName);
  587. Serial.println(F(" - type any character to stop"));
  588. return true;
  589. }
  590. //------------------------------------------------------------------------------
  591. // log data
  592. void logData() {
  593. uint32_t t0;
  594. uint32_t t1;
  595. uint32_t overruns =0;
  596. uint32_t count = 0;
  597. uint32_t maxLatencyUsec = 0;
  598. size_t maxFifoUse = 0;
  599. block_t fifoBuffer[FIFO_DIM];
  600. adcInit((metadata_t*)fifoBuffer);
  601. // Write metadata.
  602. if (sizeof(metadata_t) != binFile.write(fifoBuffer, sizeof(metadata_t))) {
  603. error("Write metadata failed");
  604. }
  605. fifoCount = 0;
  606. fifoHead = 0;
  607. fifoTail = 0;
  608. fifoData = fifoBuffer;
  609. // Initialize all blocks to save ISR overhead.
  610. memset(fifoBuffer, 0, sizeof(fifoBuffer));
  611. Serial.println(F("Logging - type any character to stop"));
  612. // Wait for Serial Idle.
  613. Serial.flush();
  614. delay(10);
  615. t0 = millis();
  616. t1 = t0;
  617. // Start logging interrupts.
  618. adcStart();
  619. while (1) {
  620. uint32_t m;
  621. noInterrupts();
  622. size_t tmpFifoCount = fifoCount;
  623. interrupts();
  624. if (tmpFifoCount) {
  625. block_t* pBlock = fifoData + fifoTail;
  626. // Write block to SD.
  627. m = micros();
  628. if (sizeof(block_t) != binFile.write(pBlock, sizeof(block_t))) {
  629. error("write data failed");
  630. }
  631. m = micros() - m;
  632. t1 = millis();
  633. if (m > maxLatencyUsec) {
  634. maxLatencyUsec = m;
  635. }
  636. if (tmpFifoCount >maxFifoUse) {
  637. maxFifoUse = tmpFifoCount;
  638. }
  639. count += pBlock->count;
  640. // Add overruns and possibly light LED.
  641. if (pBlock->overrun) {
  642. overruns += pBlock->overrun;
  643. if (ERROR_LED_PIN >= 0) {
  644. digitalWrite(ERROR_LED_PIN, HIGH);
  645. }
  646. }
  647. // Initialize empty block to save ISR overhead.
  648. pBlock->count = 0;
  649. pBlock->overrun = 0;
  650. fifoTail = fifoTail < (FIFO_DIM - 1) ? fifoTail + 1 : 0;
  651. noInterrupts();
  652. fifoCount--;
  653. interrupts();
  654. if (binFile.curPosition() >= MAX_FILE_SIZE) {
  655. // File full so stop ISR calls.
  656. adcStop();
  657. break;
  658. }
  659. }
  660. if (timerError) {
  661. error("Missed timer event - rate too high");
  662. }
  663. if (Serial.available()) {
  664. // Stop ISR interrupts.
  665. isrStop = true;
  666. }
  667. if (fifoCount == 0 && !adcActive()) {
  668. break;
  669. }
  670. }
  671. Serial.println();
  672. // Truncate file if recording stopped early.
  673. if (binFile.curPosition() < MAX_FILE_SIZE) {
  674. Serial.println(F("Truncating file"));
  675. Serial.flush();
  676. if (!binFile.truncate()) {
  677. error("Can't truncate file");
  678. }
  679. }
  680. Serial.print(F("Max write latency usec: "));
  681. Serial.println(maxLatencyUsec);
  682. Serial.print(F("Record time sec: "));
  683. Serial.println(0.001*(t1 - t0), 3);
  684. Serial.print(F("Sample count: "));
  685. Serial.println(count/PIN_COUNT);
  686. Serial.print(F("Overruns: "));
  687. Serial.println(overruns);
  688. Serial.print(F("FIFO_DIM: "));
  689. Serial.println(FIFO_DIM);
  690. Serial.print(F("maxFifoUse: "));
  691. Serial.println(maxFifoUse + 1); // include ISR use.
  692. Serial.println(F("Done"));
  693. }
  694. //------------------------------------------------------------------------------
  695. void openBinFile() {
  696. char name[NAME_DIM];
  697. clearSerialInput();
  698. Serial.println(F("Enter file name"));
  699. if (!serialReadLine(name, sizeof(name))) {
  700. return;
  701. }
  702. if (!sd.exists(name)) {
  703. Serial.println(name);
  704. Serial.println(F("File does not exist"));
  705. return;
  706. }
  707. binFile.close();
  708. if (!binFile.open(name, O_RDWR)) {
  709. Serial.println(name);
  710. Serial.println(F("open failed"));
  711. return;
  712. }
  713. Serial.println(F("File opened"));
  714. }
  715. //------------------------------------------------------------------------------
  716. // Print data file to Serial
  717. void printData() {
  718. block_t buf;
  719. if (!binFile.isOpen()) {
  720. Serial.println(F("No current binary file"));
  721. return;
  722. }
  723. binFile.rewind();
  724. if (binFile.read(&buf , sizeof(buf)) != sizeof(buf)) {
  725. error("Read metadata failed");
  726. }
  727. Serial.println(F("Type any character to stop"));
  728. delay(1000);
  729. while (!Serial.available() &&
  730. binFile.read(&buf , sizeof(buf)) == sizeof(buf)) {
  731. if (buf.count == 0) {
  732. break;
  733. }
  734. if (buf.overrun) {
  735. Serial.print(F("OVERRUN,"));
  736. Serial.println(buf.overrun);
  737. }
  738. for (size_t i = 0; i < buf.count; i++) {
  739. Serial.print(buf.data[i], DEC);
  740. if ((i+1)%PIN_COUNT) {
  741. Serial.print(',');
  742. } else {
  743. Serial.println();
  744. }
  745. }
  746. }
  747. Serial.println(F("Done"));
  748. }
  749. //------------------------------------------------------------------------------
  750. bool serialReadLine(char* str, size_t size) {
  751. size_t n = 0;
  752. while(!Serial.available()) {
  753. }
  754. while (true) {
  755. int c = Serial.read();
  756. if (c < ' ') break;
  757. str[n++] = c;
  758. if (n >= size) {
  759. Serial.println(F("input too long"));
  760. return false;
  761. }
  762. uint32_t m = millis();
  763. while (!Serial.available() && (millis() - m) < 100){}
  764. if (!Serial.available()) break;
  765. }
  766. str[n] = 0;
  767. return true;
  768. }
  769. //------------------------------------------------------------------------------
  770. void setup(void) {
  771. if (ERROR_LED_PIN >= 0) {
  772. pinMode(ERROR_LED_PIN, OUTPUT);
  773. }
  774. Serial.begin(9600);
  775. while(!Serial) {}
  776. Serial.println(F("Type any character to begin."));
  777. while(!Serial.available()) {}
  778. FillStack();
  779. // Read the first sample pin to init the ADC.
  780. analogRead(PIN_LIST[0]);
  781. #if !ENABLE_DEDICATED_SPI
  782. Serial.println(F(
  783. "\nFor best performance edit SdFatConfig.h\n"
  784. "and set ENABLE_DEDICATED_SPI nonzero"));
  785. #endif // !ENABLE_DEDICATED_SPI
  786. // Initialize SD.
  787. if (!sd.begin(SD_CONFIG)) {
  788. error("sd.begin failed");
  789. }
  790. #if USE_RTC
  791. if (!rtc.begin()) {
  792. error("rtc.begin failed");
  793. }
  794. if (!rtc.isrunning()) {
  795. // Set RTC to sketch compile date & time.
  796. // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  797. error("RTC is NOT running!");
  798. } else {
  799. Serial.println(F("RTC is running"));
  800. }
  801. // Set callback
  802. FsDateTime::setCallback(dateTime);
  803. #endif // USE_RTC
  804. }
  805. //------------------------------------------------------------------------------
  806. void loop(void) {
  807. printUnusedStack();
  808. // Read any Serial data.
  809. clearSerialInput();
  810. Serial.println();
  811. Serial.println(F("type:"));
  812. Serial.println(F("b - open existing bin file"));
  813. Serial.println(F("c - convert file to csv"));
  814. Serial.println(F("l - list files"));
  815. Serial.println(F("p - print data to Serial"));
  816. Serial.println(F("r - record ADC data"));
  817. while(!Serial.available()) {
  818. yield();
  819. }
  820. char c = tolower(Serial.read());
  821. Serial.println();
  822. if (ERROR_LED_PIN >= 0) {
  823. digitalWrite(ERROR_LED_PIN, LOW);
  824. }
  825. // Read any Serial data.
  826. clearSerialInput();
  827. if (c == 'b') {
  828. openBinFile();
  829. } else if (c == 'c') {
  830. if (createCsvFile()) {
  831. binaryToCsv();
  832. }
  833. } else if (c == 'l') {
  834. Serial.println(F("ls:"));
  835. sd.ls(&Serial, LS_DATE | LS_SIZE);
  836. } else if (c == 'p') {
  837. printData();
  838. } else if (c == 'r') {
  839. createBinFile();
  840. logData();
  841. } else {
  842. Serial.println(F("Invalid entry"));
  843. }
  844. }
  845. #else // __AVR__
  846. #error This program is only for AVR.
  847. #endif // __AVR__