AvrAdcLogger.ino 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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 "AvrAdcLogger.h"
  24. #include "BufferedPrint.h"
  25. #include "FreeStack.h"
  26. #include "SdFat.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 =
  319. F_CPU * SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles.
  320. if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) {
  321. error("Invalid ADC reference");
  322. }
  323. #ifdef ADC_PRESCALER
  324. if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) {
  325. error("Invalid ADC prescaler");
  326. }
  327. adps = ADC_PRESCALER;
  328. #else // ADC_PRESCALER
  329. // Allow extra cpu cycles to change ADC settings if more than one pin.
  330. int32_t adcCycles = (ticks - ISR_TIMER0) / PIN_COUNT - ISR_SETUP_ADC;
  331. for (adps = 7; adps > 0; adps--) {
  332. if (adcCycles >= (MIN_ADC_CYCLES << adps)) {
  333. break;
  334. }
  335. }
  336. #endif // ADC_PRESCALER
  337. meta->adcFrequency = F_CPU >> adps;
  338. if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) {
  339. error("Sample Rate Too High");
  340. }
  341. #if ROUND_SAMPLE_INTERVAL
  342. // Round so interval is multiple of ADC clock.
  343. ticks += 1 << (adps - 1);
  344. ticks >>= adps;
  345. ticks <<= adps;
  346. #endif // ROUND_SAMPLE_INTERVAL
  347. if (PIN_COUNT > BLOCK_MAX_COUNT || PIN_COUNT > PIN_NUM_DIM) {
  348. error("Too many pins");
  349. }
  350. meta->pinCount = PIN_COUNT;
  351. meta->recordEightBits = RECORD_EIGHT_BITS;
  352. for (int i = 0; i < PIN_COUNT; i++) {
  353. uint8_t pin = PIN_LIST[i];
  354. if (pin >= NUM_ANALOG_INPUTS) {
  355. error("Invalid Analog pin number");
  356. }
  357. meta->pinNumber[i] = pin;
  358. // Set ADC reference and low three bits of analog pin number.
  359. adcmux[i] = (pin & 7) | ADC_REF;
  360. if (RECORD_EIGHT_BITS) {
  361. adcmux[i] |= 1 << ADLAR;
  362. }
  363. // If this is the first pin, trigger on timer/counter 1 compare match B.
  364. adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0;
  365. #ifdef MUX5
  366. if (pin > 7) {
  367. adcsrb[i] |= (1 << MUX5);
  368. }
  369. #endif // MUX5
  370. adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps;
  371. // First pin triggers on timer 1 compare match B rest are free running.
  372. adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC;
  373. }
  374. // Setup timer1
  375. TCCR1A = 0;
  376. uint8_t tshift;
  377. if (ticks < 0X10000) {
  378. // no prescale, CTC mode
  379. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
  380. tshift = 0;
  381. } else if (ticks < 0X10000 * 8) {
  382. // prescale 8, CTC mode
  383. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
  384. tshift = 3;
  385. } else if (ticks < 0X10000 * 64) {
  386. // prescale 64, CTC mode
  387. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10);
  388. tshift = 6;
  389. } else if (ticks < 0X10000 * 256) {
  390. // prescale 256, CTC mode
  391. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);
  392. tshift = 8;
  393. } else if (ticks < 0X10000 * 1024) {
  394. // prescale 1024, CTC mode
  395. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10);
  396. tshift = 10;
  397. } else {
  398. error("Sample Rate Too Slow");
  399. }
  400. // divide by prescaler
  401. ticks >>= tshift;
  402. // set TOP for timer reset
  403. ICR1 = ticks - 1;
  404. // compare for ADC start
  405. OCR1B = 0;
  406. // multiply by prescaler
  407. ticks <<= tshift;
  408. // Sample interval in CPU clock ticks.
  409. meta->sampleInterval = ticks;
  410. meta->cpuFrequency = F_CPU;
  411. float sampleRate = (float)meta->cpuFrequency / meta->sampleInterval;
  412. Serial.print(F("Sample pins:"));
  413. for (uint8_t i = 0; i < meta->pinCount; i++) {
  414. Serial.print(' ');
  415. Serial.print(meta->pinNumber[i], DEC);
  416. }
  417. Serial.println();
  418. Serial.print(F("ADC bits: "));
  419. Serial.println(meta->recordEightBits ? 8 : 10);
  420. Serial.print(F("ADC clock kHz: "));
  421. Serial.println(meta->adcFrequency / 1000);
  422. Serial.print(F("Sample Rate: "));
  423. Serial.println(sampleRate);
  424. Serial.print(F("Sample interval usec: "));
  425. Serial.println(1000000.0 / sampleRate);
  426. }
  427. //------------------------------------------------------------------------------
  428. // enable ADC and timer1 interrupts
  429. void adcStart() {
  430. // initialize ISR
  431. adcindex = 1;
  432. isrBuf = nullptr;
  433. isrOver = 0;
  434. isrStop = false;
  435. // Clear any pending interrupt.
  436. ADCSRA |= 1 << ADIF;
  437. // Setup for first pin.
  438. ADMUX = adcmux[0];
  439. ADCSRB = adcsrb[0];
  440. ADCSRA = adcsra[0];
  441. // Enable timer1 interrupts.
  442. timerError = false;
  443. timerFlag = false;
  444. TCNT1 = 0;
  445. TIFR1 = 1 << OCF1B;
  446. TIMSK1 = 1 << OCIE1B;
  447. }
  448. //------------------------------------------------------------------------------
  449. inline void adcStop() {
  450. TIMSK1 = 0;
  451. ADCSRA = 0;
  452. }
  453. //------------------------------------------------------------------------------
  454. // Convert binary file to csv file.
  455. void binaryToCsv() {
  456. uint8_t lastPct = 0;
  457. block_t* pd;
  458. metadata_t* pm;
  459. uint32_t t0 = millis();
  460. // Use fast buffered print class.
  461. BufferedPrint<file_t, 64> bp(&csvFile);
  462. block_t binBuffer[FIFO_DIM];
  463. assert(sizeof(block_t) == sizeof(metadata_t));
  464. binFile.rewind();
  465. uint32_t tPct = millis();
  466. bool doMeta = true;
  467. while (!Serial.available()) {
  468. pd = binBuffer;
  469. int nb = binFile.read(binBuffer, sizeof(binBuffer));
  470. if (nb < 0) {
  471. error("read binFile failed");
  472. }
  473. size_t nd = nb / sizeof(block_t);
  474. if (nd < 1) {
  475. break;
  476. }
  477. if (doMeta) {
  478. doMeta = false;
  479. pm = (metadata_t*)pd++;
  480. if (PIN_COUNT != pm->pinCount) {
  481. error("Invalid pinCount");
  482. }
  483. bp.print(F("Interval,"));
  484. float intervalMicros =
  485. 1.0e6 * pm->sampleInterval / (float)pm->cpuFrequency;
  486. bp.print(intervalMicros, 4);
  487. bp.println(F(",usec"));
  488. for (uint8_t i = 0; i < PIN_COUNT; i++) {
  489. if (i) {
  490. bp.print(',');
  491. }
  492. bp.print(F("pin"));
  493. bp.print(pm->pinNumber[i]);
  494. }
  495. bp.println();
  496. if (nd-- == 1) {
  497. break;
  498. }
  499. }
  500. for (size_t i = 0; i < nd; i++, pd++) {
  501. if (pd->overrun) {
  502. bp.print(F("OVERRUN,"));
  503. bp.println(pd->overrun);
  504. }
  505. for (size_t j = 0; j < pd->count; j += PIN_COUNT) {
  506. for (size_t i = 0; i < PIN_COUNT; i++) {
  507. if (!bp.printField(pd->data[i + j],
  508. i == (PIN_COUNT - 1) ? '\n' : ',')) {
  509. error("printField failed");
  510. }
  511. }
  512. }
  513. }
  514. if ((millis() - tPct) > 1000) {
  515. uint8_t pct = binFile.curPosition() / (binFile.fileSize() / 100);
  516. if (pct != lastPct) {
  517. tPct = millis();
  518. lastPct = pct;
  519. Serial.print(pct, DEC);
  520. Serial.println('%');
  521. }
  522. }
  523. }
  524. if (!bp.sync() || !csvFile.close()) {
  525. error("close csvFile failed");
  526. }
  527. Serial.print(F("Done: "));
  528. Serial.print(0.001 * (millis() - t0));
  529. Serial.println(F(" Seconds"));
  530. }
  531. //------------------------------------------------------------------------------
  532. void clearSerialInput() {
  533. uint32_t m = micros();
  534. do {
  535. if (Serial.read() >= 0) {
  536. m = micros();
  537. }
  538. } while (micros() - m < 10000);
  539. }
  540. //------------------------------------------------------------------------------
  541. void createBinFile() {
  542. binFile.close();
  543. while (sd.exists(binName)) {
  544. char* p = strchr(binName, '.');
  545. if (!p) {
  546. error("no dot in filename");
  547. }
  548. while (true) {
  549. p--;
  550. if (p < binName || *p < '0' || *p > '9') {
  551. error("Can't create file name");
  552. }
  553. if (p[0] != '9') {
  554. p[0]++;
  555. break;
  556. }
  557. p[0] = '0';
  558. }
  559. }
  560. Serial.print(F("Opening: "));
  561. Serial.println(binName);
  562. if (!binFile.open(binName, O_RDWR | O_CREAT)) {
  563. error("open binName failed");
  564. }
  565. Serial.print(F("Allocating: "));
  566. Serial.print(MAX_FILE_SIZE_MiB);
  567. Serial.println(F(" MiB"));
  568. if (!binFile.preAllocate(MAX_FILE_SIZE)) {
  569. error("preAllocate failed");
  570. }
  571. }
  572. //------------------------------------------------------------------------------
  573. bool createCsvFile() {
  574. char csvName[NAME_DIM];
  575. if (!binFile.isOpen()) {
  576. Serial.println(F("No current binary file"));
  577. return false;
  578. }
  579. binFile.getName(csvName, sizeof(csvName));
  580. char* dot = strchr(csvName, '.');
  581. if (!dot) {
  582. error("no dot in binName");
  583. }
  584. strcpy(dot + 1, "csv");
  585. if (!csvFile.open(csvName, O_WRONLY | O_CREAT | O_TRUNC)) {
  586. error("open csvFile failed");
  587. }
  588. Serial.print(F("Writing: "));
  589. Serial.print(csvName);
  590. Serial.println(F(" - type any character to stop"));
  591. return true;
  592. }
  593. //------------------------------------------------------------------------------
  594. // log data
  595. void logData() {
  596. uint32_t t0;
  597. uint32_t t1;
  598. uint32_t overruns = 0;
  599. uint32_t count = 0;
  600. uint32_t maxLatencyUsec = 0;
  601. size_t maxFifoUse = 0;
  602. block_t fifoBuffer[FIFO_DIM];
  603. adcInit((metadata_t*)fifoBuffer);
  604. // Write metadata.
  605. if (sizeof(metadata_t) != binFile.write(fifoBuffer, sizeof(metadata_t))) {
  606. error("Write metadata failed");
  607. }
  608. fifoCount = 0;
  609. fifoHead = 0;
  610. fifoTail = 0;
  611. fifoData = fifoBuffer;
  612. // Initialize all blocks to save ISR overhead.
  613. memset(fifoBuffer, 0, sizeof(fifoBuffer));
  614. Serial.println(F("Logging - type any character to stop"));
  615. // Wait for Serial Idle.
  616. Serial.flush();
  617. delay(10);
  618. t0 = millis();
  619. t1 = t0;
  620. // Start logging interrupts.
  621. adcStart();
  622. while (1) {
  623. uint32_t m;
  624. noInterrupts();
  625. size_t tmpFifoCount = fifoCount;
  626. interrupts();
  627. if (tmpFifoCount) {
  628. block_t* pBlock = fifoData + fifoTail;
  629. // Write block to SD.
  630. m = micros();
  631. if (sizeof(block_t) != binFile.write(pBlock, sizeof(block_t))) {
  632. error("write data failed");
  633. }
  634. m = micros() - m;
  635. t1 = millis();
  636. if (m > maxLatencyUsec) {
  637. maxLatencyUsec = m;
  638. }
  639. if (tmpFifoCount > maxFifoUse) {
  640. maxFifoUse = tmpFifoCount;
  641. }
  642. count += pBlock->count;
  643. // Add overruns and possibly light LED.
  644. if (pBlock->overrun) {
  645. overruns += pBlock->overrun;
  646. if (ERROR_LED_PIN >= 0) {
  647. digitalWrite(ERROR_LED_PIN, HIGH);
  648. }
  649. }
  650. // Initialize empty block to save ISR overhead.
  651. pBlock->count = 0;
  652. pBlock->overrun = 0;
  653. fifoTail = fifoTail < (FIFO_DIM - 1) ? fifoTail + 1 : 0;
  654. noInterrupts();
  655. fifoCount--;
  656. interrupts();
  657. if (binFile.curPosition() >= MAX_FILE_SIZE) {
  658. // File full so stop ISR calls.
  659. adcStop();
  660. break;
  661. }
  662. }
  663. if (timerError) {
  664. error("Missed timer event - rate too high");
  665. }
  666. if (Serial.available()) {
  667. // Stop ISR interrupts.
  668. isrStop = true;
  669. }
  670. if (fifoCount == 0 && !adcActive()) {
  671. break;
  672. }
  673. }
  674. Serial.println();
  675. // Truncate file if recording stopped early.
  676. if (binFile.curPosition() < MAX_FILE_SIZE) {
  677. Serial.println(F("Truncating file"));
  678. Serial.flush();
  679. if (!binFile.truncate()) {
  680. error("Can't truncate file");
  681. }
  682. }
  683. Serial.print(F("Max write latency usec: "));
  684. Serial.println(maxLatencyUsec);
  685. Serial.print(F("Record time sec: "));
  686. Serial.println(0.001 * (t1 - t0), 3);
  687. Serial.print(F("Sample count: "));
  688. Serial.println(count / PIN_COUNT);
  689. Serial.print(F("Overruns: "));
  690. Serial.println(overruns);
  691. Serial.print(F("FIFO_DIM: "));
  692. Serial.println(FIFO_DIM);
  693. Serial.print(F("maxFifoUse: "));
  694. Serial.println(maxFifoUse + 1); // include ISR use.
  695. Serial.println(F("Done"));
  696. }
  697. //------------------------------------------------------------------------------
  698. void openBinFile() {
  699. char name[NAME_DIM];
  700. clearSerialInput();
  701. Serial.println(F("Enter file name"));
  702. if (!serialReadLine(name, sizeof(name))) {
  703. return;
  704. }
  705. if (!sd.exists(name)) {
  706. Serial.println(name);
  707. Serial.println(F("File does not exist"));
  708. return;
  709. }
  710. binFile.close();
  711. if (!binFile.open(name, O_RDWR)) {
  712. Serial.println(name);
  713. Serial.println(F("open failed"));
  714. return;
  715. }
  716. Serial.println(F("File opened"));
  717. }
  718. //------------------------------------------------------------------------------
  719. // Print data file to Serial
  720. void printData() {
  721. block_t buf;
  722. if (!binFile.isOpen()) {
  723. Serial.println(F("No current binary file"));
  724. return;
  725. }
  726. binFile.rewind();
  727. if (binFile.read(&buf, sizeof(buf)) != sizeof(buf)) {
  728. error("Read metadata failed");
  729. }
  730. Serial.println(F("Type any character to stop"));
  731. delay(1000);
  732. while (!Serial.available() &&
  733. binFile.read(&buf, sizeof(buf)) == sizeof(buf)) {
  734. if (buf.count == 0) {
  735. break;
  736. }
  737. if (buf.overrun) {
  738. Serial.print(F("OVERRUN,"));
  739. Serial.println(buf.overrun);
  740. }
  741. for (size_t i = 0; i < buf.count; i++) {
  742. Serial.print(buf.data[i], DEC);
  743. if ((i + 1) % PIN_COUNT) {
  744. Serial.print(',');
  745. } else {
  746. Serial.println();
  747. }
  748. }
  749. }
  750. Serial.println(F("Done"));
  751. }
  752. //------------------------------------------------------------------------------
  753. bool serialReadLine(char* str, size_t size) {
  754. size_t n = 0;
  755. while (!Serial.available()) {
  756. }
  757. while (true) {
  758. int c = Serial.read();
  759. if (c < ' ') break;
  760. str[n++] = c;
  761. if (n >= size) {
  762. Serial.println(F("input too long"));
  763. return false;
  764. }
  765. uint32_t m = millis();
  766. while (!Serial.available() && (millis() - m) < 100) {
  767. }
  768. if (!Serial.available()) break;
  769. }
  770. str[n] = 0;
  771. return true;
  772. }
  773. //------------------------------------------------------------------------------
  774. void setup(void) {
  775. if (ERROR_LED_PIN >= 0) {
  776. pinMode(ERROR_LED_PIN, OUTPUT);
  777. }
  778. Serial.begin(9600);
  779. while (!Serial) {
  780. }
  781. Serial.println(F("Type any character to begin."));
  782. while (!Serial.available()) {
  783. }
  784. FillStack();
  785. // Read the first sample pin to init the ADC.
  786. analogRead(PIN_LIST[0]);
  787. #if !ENABLE_DEDICATED_SPI
  788. Serial.println(
  789. F("\nFor best performance edit SdFatConfig.h\n"
  790. "and set ENABLE_DEDICATED_SPI nonzero"));
  791. #endif // !ENABLE_DEDICATED_SPI
  792. // Initialize SD.
  793. if (!sd.begin(SD_CONFIG)) {
  794. error("sd.begin failed");
  795. }
  796. #if USE_RTC
  797. if (!rtc.begin()) {
  798. error("rtc.begin failed");
  799. }
  800. if (!rtc.isrunning()) {
  801. // Set RTC to sketch compile date & time.
  802. // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  803. error("RTC is NOT running!");
  804. } else {
  805. Serial.println(F("RTC is running"));
  806. }
  807. // Set callback
  808. FsDateTime::setCallback(dateTime);
  809. #endif // USE_RTC
  810. }
  811. //------------------------------------------------------------------------------
  812. void loop(void) {
  813. printUnusedStack();
  814. // Read any Serial data.
  815. clearSerialInput();
  816. Serial.println();
  817. Serial.println(F("type:"));
  818. Serial.println(F("b - open existing bin file"));
  819. Serial.println(F("c - convert file to csv"));
  820. Serial.println(F("l - list files"));
  821. Serial.println(F("p - print data to Serial"));
  822. Serial.println(F("r - record ADC data"));
  823. while (!Serial.available()) {
  824. yield();
  825. }
  826. char c = tolower(Serial.read());
  827. Serial.println();
  828. if (ERROR_LED_PIN >= 0) {
  829. digitalWrite(ERROR_LED_PIN, LOW);
  830. }
  831. // Read any Serial data.
  832. clearSerialInput();
  833. if (c == 'b') {
  834. openBinFile();
  835. } else if (c == 'c') {
  836. if (createCsvFile()) {
  837. binaryToCsv();
  838. }
  839. } else if (c == 'l') {
  840. Serial.println(F("ls:"));
  841. sd.ls(&Serial, LS_DATE | LS_SIZE);
  842. } else if (c == 'p') {
  843. printData();
  844. } else if (c == 'r') {
  845. createBinFile();
  846. logData();
  847. } else {
  848. Serial.println(F("Invalid entry"));
  849. }
  850. }
  851. #else // __AVR__
  852. #error This program is only for AVR.
  853. #endif // __AVR__