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. // If an exFAT SD is required, the ExFatFormatter example will format
  37. // smaller cards with an exFAT file system.
  38. //
  39. // Note: Uno will not support SD_FAT_TYPE = 3.
  40. // SD_FAT_TYPE = 0 for SdFat/File as defined in SdFatConfig.h,
  41. // 1 for FAT16/FAT32, 2 for exFAT, 3 for FAT16/FAT32 and exFAT.
  42. #define SD_FAT_TYPE 2
  43. //------------------------------------------------------------------------------
  44. // Set USE_RTC nonzero for file timestamps.
  45. // RAM use will be marginal on Uno with RTClib.
  46. // Set USE_RTC nonzero for file timestamps.
  47. // RAM use will be marginal on Uno with RTClib.
  48. // 0 - RTC not used
  49. // 1 - DS1307
  50. // 2 - DS3231
  51. // 3 - PCF8523
  52. #define USE_RTC 0
  53. #if USE_RTC
  54. #include "RTClib.h"
  55. #endif // USE_RTC
  56. //------------------------------------------------------------------------------
  57. // Pin definitions.
  58. //
  59. // Digital pin to indicate an error, set to -1 if not used.
  60. // The led blinks for fatal errors. The led goes on solid for SD write
  61. // overrun errors and logging continues.
  62. const int8_t ERROR_LED_PIN = -1;
  63. // SD chip select pin.
  64. const uint8_t SD_CS_PIN = SS;
  65. //------------------------------------------------------------------------------
  66. // Analog pin number list for a sample. Pins may be in any order and pin
  67. // numbers may be repeated.
  68. const uint8_t PIN_LIST[] = {0, 1, 2, 3, 4};
  69. //------------------------------------------------------------------------------
  70. // Sample rate in samples per second.
  71. const float SAMPLE_RATE = 5000; // Must be 0.25 or greater.
  72. // The interval between samples in seconds, SAMPLE_INTERVAL, may be set to a
  73. // constant instead of being calculated from SAMPLE_RATE. SAMPLE_RATE is not
  74. // used in the code below. For example, setting SAMPLE_INTERVAL = 2.0e-4
  75. // will result in a 200 microsecond sample interval.
  76. const float SAMPLE_INTERVAL = 1.0/SAMPLE_RATE;
  77. // Setting ROUND_SAMPLE_INTERVAL non-zero will cause the sample interval to
  78. // be rounded to a a multiple of the ADC clock period and will reduce sample
  79. // time jitter.
  80. #define ROUND_SAMPLE_INTERVAL 1
  81. //------------------------------------------------------------------------------
  82. // Reference voltage. See the processor data-sheet for reference details.
  83. // uint8_t const ADC_REF = 0; // External Reference AREF pin.
  84. uint8_t const ADC_REF = (1 << REFS0); // Vcc Reference.
  85. // uint8_t const ADC_REF = (1 << REFS1); // Internal 1.1 (only 644 1284P Mega)
  86. // uint8_t const ADC_REF = (1 << REFS1) | (1 << REFS0); // Internal 1.1 or 2.56
  87. //------------------------------------------------------------------------------
  88. // File definitions.
  89. //
  90. // Maximum file size in bytes.
  91. // The program creates a contiguous file with MAX_FILE_SIZE_MiB bytes.
  92. // The file will be truncated if logging is stopped early.
  93. const uint32_t MAX_FILE_SIZE_MiB = 100; // 100 MiB file.
  94. // log file name. Integer field before dot will be incremented.
  95. #define LOG_FILE_NAME "AvrAdc00.bin"
  96. // Maximum length name including zero byte.
  97. const size_t NAME_DIM = 40;
  98. // Set RECORD_EIGHT_BITS non-zero to record only the high 8-bits of the ADC.
  99. #define RECORD_EIGHT_BITS 0
  100. //------------------------------------------------------------------------------
  101. // FIFO size definition. Use a multiple of 512 bytes for best performance.
  102. //
  103. #if RAMEND < 0X8FF
  104. #error SRAM too small
  105. #elif RAMEND < 0X10FF
  106. const size_t FIFO_SIZE_BYTES = 512;
  107. #elif RAMEND < 0X20FF
  108. const size_t FIFO_SIZE_BYTES = 4*512;
  109. #elif RAMEND < 0X40FF
  110. const size_t FIFO_SIZE_BYTES = 12*512;
  111. #else // RAMEND
  112. const size_t FIFO_SIZE_BYTES = 16*512;
  113. #endif // RAMEND
  114. //------------------------------------------------------------------------------
  115. // ADC clock rate.
  116. // The ADC clock rate is normally calculated from the pin count and sample
  117. // interval. The calculation attempts to use the lowest possible ADC clock
  118. // rate.
  119. //
  120. // You can select an ADC clock rate by defining the symbol ADC_PRESCALER to
  121. // one of these values. You must choose an appropriate ADC clock rate for
  122. // your sample interval.
  123. // #define ADC_PRESCALER 7 // F_CPU/128 125 kHz on an Uno
  124. // #define ADC_PRESCALER 6 // F_CPU/64 250 kHz on an Uno
  125. // #define ADC_PRESCALER 5 // F_CPU/32 500 kHz on an Uno
  126. // #define ADC_PRESCALER 4 // F_CPU/16 1000 kHz on an Uno
  127. // #define ADC_PRESCALER 3 // F_CPU/8 2000 kHz on an Uno (8-bit mode only)
  128. //==============================================================================
  129. // End of configuration constants.
  130. //==============================================================================
  131. // Temporary log file. Will be deleted if a reset or power failure occurs.
  132. #define TMP_FILE_NAME "tmp_adc.bin"
  133. // Number of analog pins to log.
  134. const uint8_t PIN_COUNT = sizeof(PIN_LIST)/sizeof(PIN_LIST[0]);
  135. // Minimum ADC clock cycles per sample interval
  136. const uint16_t MIN_ADC_CYCLES = 15;
  137. // Extra cpu cycles to setup ADC with more than one pin per sample.
  138. const uint16_t ISR_SETUP_ADC = PIN_COUNT > 1 ? 100 : 0;
  139. // Maximum cycles for timer0 system interrupt.
  140. const uint16_t ISR_TIMER0 = 160;
  141. //==============================================================================
  142. const uint32_t MAX_FILE_SIZE = MAX_FILE_SIZE_MiB << 20;
  143. // Select fastest interface.
  144. #if ENABLE_DEDICATED_SPI
  145. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI)
  146. #else // ENABLE_DEDICATED_SPI
  147. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI)
  148. #endif // ENABLE_DEDICATED_SPI
  149. #if SD_FAT_TYPE == 0
  150. SdFat sd;
  151. typedef File file_t;
  152. #elif SD_FAT_TYPE == 1
  153. SdFat32 sd;
  154. typedef File32 file_t;
  155. #elif SD_FAT_TYPE == 2
  156. SdExFat sd;
  157. typedef ExFile file_t;
  158. #elif SD_FAT_TYPE == 3
  159. SdFs sd;
  160. typedef FsFile file_t;
  161. #else // SD_FAT_TYPE
  162. #error Invalid SD_FAT_TYPE
  163. #endif // SD_FAT_TYPE
  164. file_t binFile;
  165. file_t csvFile;
  166. char binName[] = LOG_FILE_NAME;
  167. #if RECORD_EIGHT_BITS
  168. const size_t BLOCK_MAX_COUNT = PIN_COUNT*(DATA_DIM8/PIN_COUNT);
  169. typedef block8_t block_t;
  170. #else // RECORD_EIGHT_BITS
  171. const size_t BLOCK_MAX_COUNT = PIN_COUNT*(DATA_DIM16/PIN_COUNT);
  172. typedef block16_t block_t;
  173. #endif // RECORD_EIGHT_BITS
  174. // Size of FIFO in blocks.
  175. size_t const FIFO_DIM = FIFO_SIZE_BYTES/sizeof(block_t);
  176. block_t* fifoData;
  177. volatile size_t fifoCount = 0; // volatile - shared, ISR and background.
  178. size_t fifoHead = 0; // Only accessed by ISR during logging.
  179. size_t fifoTail = 0; // Only accessed by writer during logging.
  180. //==============================================================================
  181. // Interrupt Service Routines
  182. // Disable ADC interrupt if true.
  183. volatile bool isrStop = false;
  184. // Pointer to current buffer.
  185. block_t* isrBuf = nullptr;
  186. // overrun count
  187. uint16_t isrOver = 0;
  188. // ADC configuration for each pin.
  189. uint8_t adcmux[PIN_COUNT];
  190. uint8_t adcsra[PIN_COUNT];
  191. uint8_t adcsrb[PIN_COUNT];
  192. uint8_t adcindex = 1;
  193. // Insure no timer events are missed.
  194. volatile bool timerError = false;
  195. volatile bool timerFlag = false;
  196. //------------------------------------------------------------------------------
  197. // ADC done interrupt.
  198. ISR(ADC_vect) {
  199. // Read ADC data.
  200. #if RECORD_EIGHT_BITS
  201. uint8_t d = ADCH;
  202. #else // RECORD_EIGHT_BITS
  203. // This will access ADCL first.
  204. uint16_t d = ADC;
  205. #endif // RECORD_EIGHT_BITS
  206. if (!isrBuf) {
  207. if (fifoCount < FIFO_DIM) {
  208. isrBuf = fifoData + fifoHead;
  209. } else {
  210. // no buffers - count overrun
  211. if (isrOver < 0XFFFF) {
  212. isrOver++;
  213. }
  214. // Avoid missed timer error.
  215. timerFlag = false;
  216. return;
  217. }
  218. }
  219. // Start ADC for next pin
  220. if (PIN_COUNT > 1) {
  221. ADMUX = adcmux[adcindex];
  222. ADCSRB = adcsrb[adcindex];
  223. ADCSRA = adcsra[adcindex];
  224. if (adcindex == 0) {
  225. timerFlag = false;
  226. }
  227. adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0;
  228. } else {
  229. timerFlag = false;
  230. }
  231. // Store ADC data.
  232. isrBuf->data[isrBuf->count++] = d;
  233. // Check for buffer full.
  234. if (isrBuf->count >= BLOCK_MAX_COUNT) {
  235. fifoHead = fifoHead < (FIFO_DIM - 1) ? fifoHead + 1 : 0;
  236. fifoCount++;
  237. // Check for end logging.
  238. if (isrStop) {
  239. adcStop();
  240. return;
  241. }
  242. // Set buffer needed and clear overruns.
  243. isrBuf = nullptr;
  244. isrOver = 0;
  245. }
  246. }
  247. //------------------------------------------------------------------------------
  248. // timer1 interrupt to clear OCF1B
  249. ISR(TIMER1_COMPB_vect) {
  250. // Make sure ADC ISR responded to timer event.
  251. if (timerFlag) {
  252. timerError = true;
  253. }
  254. timerFlag = true;
  255. }
  256. //==============================================================================
  257. // Error messages stored in flash.
  258. #define error(msg) (Serial.println(F(msg)),errorHalt())
  259. #define assert(e) ((e) ? (void)0 : error("assert: " #e))
  260. //------------------------------------------------------------------------------
  261. //
  262. void fatalBlink() {
  263. while (true) {
  264. if (ERROR_LED_PIN >= 0) {
  265. digitalWrite(ERROR_LED_PIN, HIGH);
  266. delay(200);
  267. digitalWrite(ERROR_LED_PIN, LOW);
  268. delay(200);
  269. }
  270. }
  271. }
  272. //------------------------------------------------------------------------------
  273. void errorHalt() {
  274. // Print minimal error data.
  275. // sd.errorPrint(&Serial);
  276. // Print extended error info - uses extra bytes of flash.
  277. sd.printSdError(&Serial);
  278. // Try to save data.
  279. binFile.close();
  280. fatalBlink();
  281. }
  282. //------------------------------------------------------------------------------
  283. void printUnusedStack() {
  284. Serial.print(F("\nUnused stack: "));
  285. Serial.println(UnusedStack());
  286. }
  287. //------------------------------------------------------------------------------
  288. #if USE_RTC
  289. #if USE_RTC == 1
  290. RTC_DS1307 rtc;
  291. #elif USE_RTC == 2
  292. RTC_DS3231 rtc;
  293. #elif USE_RTC == 3
  294. RTC_PCF8523 rtc;
  295. #else // USE_RTC == type
  296. #error USE_RTC type not implemented.
  297. #endif // USE_RTC == type
  298. // Call back for file timestamps. Only called for file create and sync().
  299. void dateTime(uint16_t* date, uint16_t* time, uint8_t* ms10) {
  300. DateTime now = rtc.now();
  301. // Return date using FS_DATE macro to format fields.
  302. *date = FS_DATE(now.year(), now.month(), now.day());
  303. // Return time using FS_TIME macro to format fields.
  304. *time = FS_TIME(now.hour(), now.minute(), now.second());
  305. // Return low time bits in units of 10 ms.
  306. *ms10 = now.second() & 1 ? 100 : 0;
  307. }
  308. #endif // USE_RTC
  309. //==============================================================================
  310. #if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2
  311. #error unexpected ADC prescaler bits
  312. #endif
  313. //------------------------------------------------------------------------------
  314. inline bool adcActive() {return (1 << ADIE) & ADCSRA;}
  315. //------------------------------------------------------------------------------
  316. // initialize ADC and timer1
  317. void adcInit(metadata_t* meta) {
  318. uint8_t adps; // prescaler bits for ADCSRA
  319. uint32_t ticks = 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 = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency;
  485. bp.print(intervalMicros, 4);
  486. bp.println(F(",usec"));
  487. for (uint8_t i = 0; i < PIN_COUNT; i++) {
  488. if (i) {
  489. bp.print(',');
  490. }
  491. bp.print(F("pin"));
  492. bp.print(pm->pinNumber[i]);
  493. }
  494. bp.println();
  495. if (nd-- == 1) {
  496. break;
  497. }
  498. }
  499. for (size_t i = 0; i < nd; i++, pd++) {
  500. if (pd->overrun) {
  501. bp.print(F("OVERRUN,"));
  502. bp.println(pd->overrun);
  503. }
  504. for (size_t j = 0; j < pd->count; j += PIN_COUNT) {
  505. for (size_t i = 0; i < PIN_COUNT; i++) {
  506. if (!bp.printField(pd->data[i + j], i == (PIN_COUNT-1) ? '\n' : ',')) {
  507. error("printField failed");
  508. }
  509. }
  510. }
  511. }
  512. if ((millis() - tPct) > 1000) {
  513. uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100);
  514. if (pct != lastPct) {
  515. tPct = millis();
  516. lastPct = pct;
  517. Serial.print(pct, DEC);
  518. Serial.println('%');
  519. }
  520. }
  521. }
  522. if (!bp.sync() || !csvFile.close()) {
  523. error("close csvFile failed");
  524. }
  525. Serial.print(F("Done: "));
  526. Serial.print(0.001*(millis() - t0));
  527. Serial.println(F(" Seconds"));
  528. }
  529. //------------------------------------------------------------------------------
  530. void clearSerialInput() {
  531. uint32_t m = micros();
  532. do {
  533. if (Serial.read() >= 0) {
  534. m = micros();
  535. }
  536. } while (micros() - m < 10000);
  537. }
  538. //------------------------------------------------------------------------------
  539. void createBinFile() {
  540. binFile.close();
  541. while (sd.exists(binName)) {
  542. char* p = strchr(binName, '.');
  543. if (!p) {
  544. error("no dot in filename");
  545. }
  546. while (true) {
  547. p--;
  548. if (p < binName || *p < '0' || *p > '9') {
  549. error("Can't create file name");
  550. }
  551. if (p[0] != '9') {
  552. p[0]++;
  553. break;
  554. }
  555. p[0] = '0';
  556. }
  557. }
  558. Serial.print(F("Opening: "));
  559. Serial.println(binName);
  560. if (!binFile.open(binName, O_RDWR | O_CREAT)) {
  561. error("open binName failed");
  562. }
  563. Serial.print(F("Allocating: "));
  564. Serial.print(MAX_FILE_SIZE_MiB);
  565. Serial.println(F(" MiB"));
  566. if (!binFile.preAllocate(MAX_FILE_SIZE)) {
  567. error("preAllocate failed");
  568. }
  569. }
  570. //------------------------------------------------------------------------------
  571. bool createCsvFile() {
  572. char csvName[NAME_DIM];
  573. if (!binFile.isOpen()) {
  574. Serial.println(F("No current binary file"));
  575. return false;
  576. }
  577. binFile.getName(csvName, sizeof(csvName));
  578. char* dot = strchr(csvName, '.');
  579. if (!dot) {
  580. error("no dot in binName");
  581. }
  582. strcpy(dot + 1, "csv");
  583. if (!csvFile.open(csvName, O_WRONLY|O_CREAT|O_TRUNC)) {
  584. error("open csvFile failed");
  585. }
  586. Serial.print(F("Writing: "));
  587. Serial.print(csvName);
  588. Serial.println(F(" - type any character to stop"));
  589. return true;
  590. }
  591. //------------------------------------------------------------------------------
  592. // log data
  593. void logData() {
  594. uint32_t t0;
  595. uint32_t t1;
  596. uint32_t overruns =0;
  597. uint32_t count = 0;
  598. uint32_t maxLatencyUsec = 0;
  599. size_t maxFifoUse = 0;
  600. block_t fifoBuffer[FIFO_DIM];
  601. adcInit((metadata_t*)fifoBuffer);
  602. // Write metadata.
  603. if (sizeof(metadata_t) != binFile.write(fifoBuffer, sizeof(metadata_t))) {
  604. error("Write metadata failed");
  605. }
  606. fifoCount = 0;
  607. fifoHead = 0;
  608. fifoTail = 0;
  609. fifoData = fifoBuffer;
  610. // Initialize all blocks to save ISR overhead.
  611. memset(fifoBuffer, 0, sizeof(fifoBuffer));
  612. Serial.println(F("Logging - type any character to stop"));
  613. // Wait for Serial Idle.
  614. Serial.flush();
  615. delay(10);
  616. t0 = millis();
  617. t1 = t0;
  618. // Start logging interrupts.
  619. adcStart();
  620. while (1) {
  621. uint32_t m;
  622. noInterrupts();
  623. size_t tmpFifoCount = fifoCount;
  624. interrupts();
  625. if (tmpFifoCount) {
  626. block_t* pBlock = fifoData + fifoTail;
  627. // Write block to SD.
  628. m = micros();
  629. if (sizeof(block_t) != binFile.write(pBlock, sizeof(block_t))) {
  630. error("write data failed");
  631. }
  632. m = micros() - m;
  633. t1 = millis();
  634. if (m > maxLatencyUsec) {
  635. maxLatencyUsec = m;
  636. }
  637. if (tmpFifoCount >maxFifoUse) {
  638. maxFifoUse = tmpFifoCount;
  639. }
  640. count += pBlock->count;
  641. // Add overruns and possibly light LED.
  642. if (pBlock->overrun) {
  643. overruns += pBlock->overrun;
  644. if (ERROR_LED_PIN >= 0) {
  645. digitalWrite(ERROR_LED_PIN, HIGH);
  646. }
  647. }
  648. // Initialize empty block to save ISR overhead.
  649. pBlock->count = 0;
  650. pBlock->overrun = 0;
  651. fifoTail = fifoTail < (FIFO_DIM - 1) ? fifoTail + 1 : 0;
  652. noInterrupts();
  653. fifoCount--;
  654. interrupts();
  655. if (binFile.curPosition() >= MAX_FILE_SIZE) {
  656. // File full so stop ISR calls.
  657. adcStop();
  658. break;
  659. }
  660. }
  661. if (timerError) {
  662. error("Missed timer event - rate too high");
  663. }
  664. if (Serial.available()) {
  665. // Stop ISR interrupts.
  666. isrStop = true;
  667. }
  668. if (fifoCount == 0 && !adcActive()) {
  669. break;
  670. }
  671. }
  672. Serial.println();
  673. // Truncate file if recording stopped early.
  674. if (binFile.curPosition() < MAX_FILE_SIZE) {
  675. Serial.println(F("Truncating file"));
  676. Serial.flush();
  677. if (!binFile.truncate()) {
  678. error("Can't truncate file");
  679. }
  680. }
  681. Serial.print(F("Max write latency usec: "));
  682. Serial.println(maxLatencyUsec);
  683. Serial.print(F("Record time sec: "));
  684. Serial.println(0.001*(t1 - t0), 3);
  685. Serial.print(F("Sample count: "));
  686. Serial.println(count/PIN_COUNT);
  687. Serial.print(F("Overruns: "));
  688. Serial.println(overruns);
  689. Serial.print(F("FIFO_DIM: "));
  690. Serial.println(FIFO_DIM);
  691. Serial.print(F("maxFifoUse: "));
  692. Serial.println(maxFifoUse + 1); // include ISR use.
  693. Serial.println(F("Done"));
  694. }
  695. //------------------------------------------------------------------------------
  696. void openBinFile() {
  697. char name[NAME_DIM];
  698. clearSerialInput();
  699. Serial.println(F("Enter file name"));
  700. if (!serialReadLine(name, sizeof(name))) {
  701. return;
  702. }
  703. if (!sd.exists(name)) {
  704. Serial.println(name);
  705. Serial.println(F("File does not exist"));
  706. return;
  707. }
  708. binFile.close();
  709. if (!binFile.open(name, O_RDWR)) {
  710. Serial.println(name);
  711. Serial.println(F("open failed"));
  712. return;
  713. }
  714. Serial.println(F("File opened"));
  715. }
  716. //------------------------------------------------------------------------------
  717. // Print data file to Serial
  718. void printData() {
  719. block_t buf;
  720. if (!binFile.isOpen()) {
  721. Serial.println(F("No current binary file"));
  722. return;
  723. }
  724. binFile.rewind();
  725. if (binFile.read(&buf , sizeof(buf)) != sizeof(buf)) {
  726. error("Read metadata failed");
  727. }
  728. Serial.println(F("Type any character to stop"));
  729. delay(1000);
  730. while (!Serial.available() &&
  731. binFile.read(&buf , sizeof(buf)) == sizeof(buf)) {
  732. if (buf.count == 0) {
  733. break;
  734. }
  735. if (buf.overrun) {
  736. Serial.print(F("OVERRUN,"));
  737. Serial.println(buf.overrun);
  738. }
  739. for (size_t i = 0; i < buf.count; i++) {
  740. Serial.print(buf.data[i], DEC);
  741. if ((i+1)%PIN_COUNT) {
  742. Serial.print(',');
  743. } else {
  744. Serial.println();
  745. }
  746. }
  747. }
  748. Serial.println(F("Done"));
  749. }
  750. //------------------------------------------------------------------------------
  751. bool serialReadLine(char* str, size_t size) {
  752. size_t n = 0;
  753. while(!Serial.available()) {
  754. }
  755. while (true) {
  756. int c = Serial.read();
  757. if (c < ' ') break;
  758. str[n++] = c;
  759. if (n >= size) {
  760. Serial.println(F("input too long"));
  761. return false;
  762. }
  763. uint32_t m = millis();
  764. while (!Serial.available() && (millis() - m) < 100){}
  765. if (!Serial.available()) break;
  766. }
  767. str[n] = 0;
  768. return true;
  769. }
  770. //------------------------------------------------------------------------------
  771. void setup(void) {
  772. if (ERROR_LED_PIN >= 0) {
  773. pinMode(ERROR_LED_PIN, OUTPUT);
  774. }
  775. Serial.begin(9600);
  776. while(!Serial) {}
  777. Serial.println(F("Type any character to begin."));
  778. while(!Serial.available()) {}
  779. FillStack();
  780. // Read the first sample pin to init the ADC.
  781. analogRead(PIN_LIST[0]);
  782. #if !ENABLE_DEDICATED_SPI
  783. Serial.println(F(
  784. "\nFor best performance edit SdFatConfig.h\n"
  785. "and set ENABLE_DEDICATED_SPI nonzero"));
  786. #endif // !ENABLE_DEDICATED_SPI
  787. // Initialize SD.
  788. if (!sd.begin(SD_CONFIG)) {
  789. error("sd.begin failed");
  790. }
  791. #if USE_RTC
  792. if (!rtc.begin()) {
  793. error("rtc.begin failed");
  794. }
  795. if (!rtc.isrunning()) {
  796. // Set RTC to sketch compile date & time.
  797. // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  798. error("RTC is NOT running!");
  799. } else {
  800. Serial.println(F("RTC is running"));
  801. }
  802. // Set callback
  803. FsDateTime::setCallback(dateTime);
  804. #endif // USE_RTC
  805. }
  806. //------------------------------------------------------------------------------
  807. void loop(void) {
  808. printUnusedStack();
  809. // Read any Serial data.
  810. clearSerialInput();
  811. Serial.println();
  812. Serial.println(F("type:"));
  813. Serial.println(F("b - open existing bin file"));
  814. Serial.println(F("c - convert file to csv"));
  815. Serial.println(F("l - list files"));
  816. Serial.println(F("p - print data to Serial"));
  817. Serial.println(F("r - record ADC data"));
  818. while(!Serial.available()) {
  819. SysCall::yield();
  820. }
  821. char c = tolower(Serial.read());
  822. Serial.println();
  823. if (ERROR_LED_PIN >= 0) {
  824. digitalWrite(ERROR_LED_PIN, LOW);
  825. }
  826. // Read any Serial data.
  827. clearSerialInput();
  828. if (c == 'b') {
  829. openBinFile();
  830. } else if (c == 'c') {
  831. if (createCsvFile()) {
  832. binaryToCsv();
  833. }
  834. } else if (c == 'l') {
  835. Serial.println(F("ls:"));
  836. sd.ls(&Serial, LS_DATE | LS_SIZE);
  837. } else if (c == 'p') {
  838. printData();
  839. } else if (c == 'r') {
  840. createBinFile();
  841. logData();
  842. } else {
  843. Serial.println(F("Invalid entry"));
  844. }
  845. }
  846. #else // __AVR__
  847. #error This program is only for AVR.
  848. #endif // __AVR__