AvrAdcLogger.ino 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. Max SPI rate for AVR is 10 MHx.
  144. #define SPI_CLOCK SD_SCK_MHZ(10)
  145. #if ENABLE_DEDICATED_SPI
  146. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SPI_CLOCK)
  147. #else // ENABLE_DEDICATED_SPI
  148. #define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SPI_CLOCK)
  149. #endif // ENABLE_DEDICATED_SPI
  150. #if SD_FAT_TYPE == 0
  151. SdFat sd;
  152. typedef File file_t;
  153. #elif SD_FAT_TYPE == 1
  154. SdFat32 sd;
  155. typedef File32 file_t;
  156. #elif SD_FAT_TYPE == 2
  157. SdExFat sd;
  158. typedef ExFile file_t;
  159. #elif SD_FAT_TYPE == 3
  160. SdFs sd;
  161. typedef FsFile file_t;
  162. #else // SD_FAT_TYPE
  163. #error Invalid SD_FAT_TYPE
  164. #endif // SD_FAT_TYPE
  165. file_t binFile;
  166. file_t csvFile;
  167. char binName[] = LOG_FILE_NAME;
  168. #if RECORD_EIGHT_BITS
  169. const size_t BLOCK_MAX_COUNT = PIN_COUNT*(DATA_DIM8/PIN_COUNT);
  170. typedef block8_t block_t;
  171. #else // RECORD_EIGHT_BITS
  172. const size_t BLOCK_MAX_COUNT = PIN_COUNT*(DATA_DIM16/PIN_COUNT);
  173. typedef block16_t block_t;
  174. #endif // RECORD_EIGHT_BITS
  175. // Size of FIFO in blocks.
  176. size_t const FIFO_DIM = FIFO_SIZE_BYTES/sizeof(block_t);
  177. block_t* fifoData;
  178. volatile size_t fifoCount = 0; // volatile - shared, ISR and background.
  179. size_t fifoHead = 0; // Only accessed by ISR during logging.
  180. size_t fifoTail = 0; // Only accessed by writer during logging.
  181. //==============================================================================
  182. // Interrupt Service Routines
  183. // Disable ADC interrupt if true.
  184. volatile bool isrStop = false;
  185. // Pointer to current buffer.
  186. block_t* isrBuf = nullptr;
  187. // overrun count
  188. uint16_t isrOver = 0;
  189. // ADC configuration for each pin.
  190. uint8_t adcmux[PIN_COUNT];
  191. uint8_t adcsra[PIN_COUNT];
  192. uint8_t adcsrb[PIN_COUNT];
  193. uint8_t adcindex = 1;
  194. // Insure no timer events are missed.
  195. volatile bool timerError = false;
  196. volatile bool timerFlag = false;
  197. //------------------------------------------------------------------------------
  198. // ADC done interrupt.
  199. ISR(ADC_vect) {
  200. // Read ADC data.
  201. #if RECORD_EIGHT_BITS
  202. uint8_t d = ADCH;
  203. #else // RECORD_EIGHT_BITS
  204. // This will access ADCL first.
  205. uint16_t d = ADC;
  206. #endif // RECORD_EIGHT_BITS
  207. if (!isrBuf) {
  208. if (fifoCount < FIFO_DIM) {
  209. isrBuf = fifoData + fifoHead;
  210. } else {
  211. // no buffers - count overrun
  212. if (isrOver < 0XFFFF) {
  213. isrOver++;
  214. }
  215. // Avoid missed timer error.
  216. timerFlag = false;
  217. return;
  218. }
  219. }
  220. // Start ADC for next pin
  221. if (PIN_COUNT > 1) {
  222. ADMUX = adcmux[adcindex];
  223. ADCSRB = adcsrb[adcindex];
  224. ADCSRA = adcsra[adcindex];
  225. if (adcindex == 0) {
  226. timerFlag = false;
  227. }
  228. adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0;
  229. } else {
  230. timerFlag = false;
  231. }
  232. // Store ADC data.
  233. isrBuf->data[isrBuf->count++] = d;
  234. // Check for buffer full.
  235. if (isrBuf->count >= BLOCK_MAX_COUNT) {
  236. fifoHead = fifoHead < (FIFO_DIM - 1) ? fifoHead + 1 : 0;
  237. fifoCount++;
  238. // Check for end logging.
  239. if (isrStop) {
  240. adcStop();
  241. return;
  242. }
  243. // Set buffer needed and clear overruns.
  244. isrBuf = nullptr;
  245. isrOver = 0;
  246. }
  247. }
  248. //------------------------------------------------------------------------------
  249. // timer1 interrupt to clear OCF1B
  250. ISR(TIMER1_COMPB_vect) {
  251. // Make sure ADC ISR responded to timer event.
  252. if (timerFlag) {
  253. timerError = true;
  254. }
  255. timerFlag = true;
  256. }
  257. //==============================================================================
  258. // Error messages stored in flash.
  259. #define error(msg) (Serial.println(F(msg)),errorHalt())
  260. #define assert(e) ((e) ? (void)0 : error("assert: " #e))
  261. //------------------------------------------------------------------------------
  262. //
  263. void fatalBlink() {
  264. while (true) {
  265. if (ERROR_LED_PIN >= 0) {
  266. digitalWrite(ERROR_LED_PIN, HIGH);
  267. delay(200);
  268. digitalWrite(ERROR_LED_PIN, LOW);
  269. delay(200);
  270. }
  271. }
  272. }
  273. //------------------------------------------------------------------------------
  274. void errorHalt() {
  275. // Print minimal error data.
  276. // sd.errorPrint(&Serial);
  277. // Print extended error info - uses extra bytes of flash.
  278. sd.printSdError(&Serial);
  279. // Try to save data.
  280. binFile.close();
  281. fatalBlink();
  282. }
  283. //------------------------------------------------------------------------------
  284. void printUnusedStack() {
  285. Serial.print(F("\nUnused stack: "));
  286. Serial.println(UnusedStack());
  287. }
  288. //------------------------------------------------------------------------------
  289. #if USE_RTC
  290. #if USE_RTC == 1
  291. RTC_DS1307 rtc;
  292. #elif USE_RTC == 2
  293. RTC_DS3231 rtc;
  294. #elif USE_RTC == 3
  295. RTC_PCF8523 rtc;
  296. #else // USE_RTC == type
  297. #error USE_RTC type not implemented.
  298. #endif // USE_RTC == type
  299. // Call back for file timestamps. Only called for file create and sync().
  300. void dateTime(uint16_t* date, uint16_t* time, uint8_t* ms10) {
  301. DateTime now = rtc.now();
  302. // Return date using FS_DATE macro to format fields.
  303. *date = FS_DATE(now.year(), now.month(), now.day());
  304. // Return time using FS_TIME macro to format fields.
  305. *time = FS_TIME(now.hour(), now.minute(), now.second());
  306. // Return low time bits in units of 10 ms.
  307. *ms10 = now.second() & 1 ? 100 : 0;
  308. }
  309. #endif // USE_RTC
  310. //==============================================================================
  311. #if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2
  312. #error unexpected ADC prescaler bits
  313. #endif
  314. //------------------------------------------------------------------------------
  315. inline bool adcActive() {return (1 << ADIE) & ADCSRA;}
  316. //------------------------------------------------------------------------------
  317. // initialize ADC and timer1
  318. void adcInit(metadata_t* meta) {
  319. uint8_t adps; // prescaler bits for ADCSRA
  320. uint32_t ticks = F_CPU*SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles.
  321. if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) {
  322. error("Invalid ADC reference");
  323. }
  324. #ifdef ADC_PRESCALER
  325. if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) {
  326. error("Invalid ADC prescaler");
  327. }
  328. adps = ADC_PRESCALER;
  329. #else // ADC_PRESCALER
  330. // Allow extra cpu cycles to change ADC settings if more than one pin.
  331. int32_t adcCycles = (ticks - ISR_TIMER0)/PIN_COUNT - ISR_SETUP_ADC;
  332. for (adps = 7; adps > 0; adps--) {
  333. if (adcCycles >= (MIN_ADC_CYCLES << adps)) {
  334. break;
  335. }
  336. }
  337. #endif // ADC_PRESCALER
  338. meta->adcFrequency = F_CPU >> adps;
  339. if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) {
  340. error("Sample Rate Too High");
  341. }
  342. #if ROUND_SAMPLE_INTERVAL
  343. // Round so interval is multiple of ADC clock.
  344. ticks += 1 << (adps - 1);
  345. ticks >>= adps;
  346. ticks <<= adps;
  347. #endif // ROUND_SAMPLE_INTERVAL
  348. if (PIN_COUNT > BLOCK_MAX_COUNT || PIN_COUNT > PIN_NUM_DIM) {
  349. error("Too many pins");
  350. }
  351. meta->pinCount = PIN_COUNT;
  352. meta->recordEightBits = RECORD_EIGHT_BITS;
  353. for (int i = 0; i < PIN_COUNT; i++) {
  354. uint8_t pin = PIN_LIST[i];
  355. if (pin >= NUM_ANALOG_INPUTS) {
  356. error("Invalid Analog pin number");
  357. }
  358. meta->pinNumber[i] = pin;
  359. // Set ADC reference and low three bits of analog pin number.
  360. adcmux[i] = (pin & 7) | ADC_REF;
  361. if (RECORD_EIGHT_BITS) {
  362. adcmux[i] |= 1 << ADLAR;
  363. }
  364. // If this is the first pin, trigger on timer/counter 1 compare match B.
  365. adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0;
  366. #ifdef MUX5
  367. if (pin > 7) {
  368. adcsrb[i] |= (1 << MUX5);
  369. }
  370. #endif // MUX5
  371. adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps;
  372. // First pin triggers on timer 1 compare match B rest are free running.
  373. adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC;
  374. }
  375. // Setup timer1
  376. TCCR1A = 0;
  377. uint8_t tshift;
  378. if (ticks < 0X10000) {
  379. // no prescale, CTC mode
  380. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
  381. tshift = 0;
  382. } else if (ticks < 0X10000*8) {
  383. // prescale 8, CTC mode
  384. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
  385. tshift = 3;
  386. } else if (ticks < 0X10000*64) {
  387. // prescale 64, CTC mode
  388. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10);
  389. tshift = 6;
  390. } else if (ticks < 0X10000*256) {
  391. // prescale 256, CTC mode
  392. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);
  393. tshift = 8;
  394. } else if (ticks < 0X10000*1024) {
  395. // prescale 1024, CTC mode
  396. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10);
  397. tshift = 10;
  398. } else {
  399. error("Sample Rate Too Slow");
  400. }
  401. // divide by prescaler
  402. ticks >>= tshift;
  403. // set TOP for timer reset
  404. ICR1 = ticks - 1;
  405. // compare for ADC start
  406. OCR1B = 0;
  407. // multiply by prescaler
  408. ticks <<= tshift;
  409. // Sample interval in CPU clock ticks.
  410. meta->sampleInterval = ticks;
  411. meta->cpuFrequency = F_CPU;
  412. float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval;
  413. Serial.print(F("Sample pins:"));
  414. for (uint8_t i = 0; i < meta->pinCount; i++) {
  415. Serial.print(' ');
  416. Serial.print(meta->pinNumber[i], DEC);
  417. }
  418. Serial.println();
  419. Serial.print(F("ADC bits: "));
  420. Serial.println(meta->recordEightBits ? 8 : 10);
  421. Serial.print(F("ADC clock kHz: "));
  422. Serial.println(meta->adcFrequency/1000);
  423. Serial.print(F("Sample Rate: "));
  424. Serial.println(sampleRate);
  425. Serial.print(F("Sample interval usec: "));
  426. Serial.println(1000000.0/sampleRate);
  427. }
  428. //------------------------------------------------------------------------------
  429. // enable ADC and timer1 interrupts
  430. void adcStart() {
  431. // initialize ISR
  432. adcindex = 1;
  433. isrBuf = nullptr;
  434. isrOver = 0;
  435. isrStop = false;
  436. // Clear any pending interrupt.
  437. ADCSRA |= 1 << ADIF;
  438. // Setup for first pin.
  439. ADMUX = adcmux[0];
  440. ADCSRB = adcsrb[0];
  441. ADCSRA = adcsra[0];
  442. // Enable timer1 interrupts.
  443. timerError = false;
  444. timerFlag = false;
  445. TCNT1 = 0;
  446. TIFR1 = 1 << OCF1B;
  447. TIMSK1 = 1 << OCIE1B;
  448. }
  449. //------------------------------------------------------------------------------
  450. inline void adcStop() {
  451. TIMSK1 = 0;
  452. ADCSRA = 0;
  453. }
  454. //------------------------------------------------------------------------------
  455. // Convert binary file to csv file.
  456. void binaryToCsv() {
  457. uint8_t lastPct = 0;
  458. block_t* pd;
  459. metadata_t* pm;
  460. uint32_t t0 = millis();
  461. // Use fast buffered print class.
  462. BufferedPrint<file_t, 64> bp(&csvFile);
  463. block_t binBuffer[FIFO_DIM];
  464. assert(sizeof(block_t) == sizeof(metadata_t));
  465. binFile.rewind();
  466. uint32_t tPct = millis();
  467. bool doMeta = true;
  468. while (!Serial.available()) {
  469. pd = binBuffer;
  470. int nb = binFile.read(binBuffer, sizeof(binBuffer));
  471. if (nb < 0) {
  472. error("read binFile failed");
  473. }
  474. size_t nd = nb/sizeof(block_t);
  475. if (nd < 1) {
  476. break;
  477. }
  478. if (doMeta) {
  479. doMeta = false;
  480. pm = (metadata_t*)pd++;
  481. if (PIN_COUNT != pm->pinCount) {
  482. error("Invalid pinCount");
  483. }
  484. bp.print(F("Interval,"));
  485. float intervalMicros = 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], i == (PIN_COUNT-1) ? '\n' : ',')) {
  508. error("printField failed");
  509. }
  510. }
  511. }
  512. }
  513. if ((millis() - tPct) > 1000) {
  514. uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100);
  515. if (pct != lastPct) {
  516. tPct = millis();
  517. lastPct = pct;
  518. Serial.print(pct, DEC);
  519. Serial.println('%');
  520. }
  521. }
  522. }
  523. if (!bp.sync() || !csvFile.close()) {
  524. error("close csvFile failed");
  525. }
  526. Serial.print(F("Done: "));
  527. Serial.print(0.001*(millis() - t0));
  528. Serial.println(F(" Seconds"));
  529. }
  530. //------------------------------------------------------------------------------
  531. void clearSerialInput() {
  532. uint32_t m = micros();
  533. do {
  534. if (Serial.read() >= 0) {
  535. m = micros();
  536. }
  537. } while (micros() - m < 10000);
  538. }
  539. //------------------------------------------------------------------------------
  540. void createBinFile() {
  541. binFile.close();
  542. while (sd.exists(binName)) {
  543. char* p = strchr(binName, '.');
  544. if (!p) {
  545. error("no dot in filename");
  546. }
  547. while (true) {
  548. p--;
  549. if (p < binName || *p < '0' || *p > '9') {
  550. error("Can't create file name");
  551. }
  552. if (p[0] != '9') {
  553. p[0]++;
  554. break;
  555. }
  556. p[0] = '0';
  557. }
  558. }
  559. Serial.print(F("Opening: "));
  560. Serial.println(binName);
  561. if (!binFile.open(binName, O_RDWR | O_CREAT)) {
  562. error("open binName failed");
  563. }
  564. Serial.print(F("Allocating: "));
  565. Serial.print(MAX_FILE_SIZE_MiB);
  566. Serial.println(F(" MiB"));
  567. if (!binFile.preAllocate(MAX_FILE_SIZE)) {
  568. error("preAllocate failed");
  569. }
  570. }
  571. //------------------------------------------------------------------------------
  572. bool createCsvFile() {
  573. char csvName[NAME_DIM];
  574. if (!binFile.isOpen()) {
  575. Serial.println(F("No current binary file"));
  576. return false;
  577. }
  578. binFile.getName(csvName, sizeof(csvName));
  579. char* dot = strchr(csvName, '.');
  580. if (!dot) {
  581. error("no dot in binName");
  582. }
  583. strcpy(dot + 1, "csv");
  584. if (!csvFile.open(csvName, O_WRONLY|O_CREAT|O_TRUNC)) {
  585. error("open csvFile failed");
  586. }
  587. Serial.print(F("Writing: "));
  588. Serial.print(csvName);
  589. Serial.println(F(" - type any character to stop"));
  590. return true;
  591. }
  592. //------------------------------------------------------------------------------
  593. // log data
  594. void logData() {
  595. uint32_t t0;
  596. uint32_t t1;
  597. uint32_t overruns =0;
  598. uint32_t count = 0;
  599. uint32_t maxLatencyUsec = 0;
  600. size_t maxFifoUse = 0;
  601. block_t fifoBuffer[FIFO_DIM];
  602. adcInit((metadata_t*)fifoBuffer);
  603. // Write metadata.
  604. if (sizeof(metadata_t) != binFile.write(fifoBuffer, sizeof(metadata_t))) {
  605. error("Write metadata failed");
  606. }
  607. fifoCount = 0;
  608. fifoHead = 0;
  609. fifoTail = 0;
  610. fifoData = fifoBuffer;
  611. // Initialize all blocks to save ISR overhead.
  612. memset(fifoBuffer, 0, sizeof(fifoBuffer));
  613. Serial.println(F("Logging - type any character to stop"));
  614. // Wait for Serial Idle.
  615. Serial.flush();
  616. delay(10);
  617. t0 = millis();
  618. t1 = t0;
  619. // Start logging interrupts.
  620. adcStart();
  621. while (1) {
  622. uint32_t m;
  623. noInterrupts();
  624. size_t tmpFifoCount = fifoCount;
  625. interrupts();
  626. if (tmpFifoCount) {
  627. block_t* pBlock = fifoData + fifoTail;
  628. // Write block to SD.
  629. m = micros();
  630. if (sizeof(block_t) != binFile.write(pBlock, sizeof(block_t))) {
  631. error("write data failed");
  632. }
  633. m = micros() - m;
  634. t1 = millis();
  635. if (m > maxLatencyUsec) {
  636. maxLatencyUsec = m;
  637. }
  638. if (tmpFifoCount >maxFifoUse) {
  639. maxFifoUse = tmpFifoCount;
  640. }
  641. count += pBlock->count;
  642. // Add overruns and possibly light LED.
  643. if (pBlock->overrun) {
  644. overruns += pBlock->overrun;
  645. if (ERROR_LED_PIN >= 0) {
  646. digitalWrite(ERROR_LED_PIN, HIGH);
  647. }
  648. }
  649. // Initialize empty block to save ISR overhead.
  650. pBlock->count = 0;
  651. pBlock->overrun = 0;
  652. fifoTail = fifoTail < (FIFO_DIM - 1) ? fifoTail + 1 : 0;
  653. noInterrupts();
  654. fifoCount--;
  655. interrupts();
  656. if (binFile.curPosition() >= MAX_FILE_SIZE) {
  657. // File full so stop ISR calls.
  658. adcStop();
  659. break;
  660. }
  661. }
  662. if (timerError) {
  663. error("Missed timer event - rate too high");
  664. }
  665. if (Serial.available()) {
  666. // Stop ISR interrupts.
  667. isrStop = true;
  668. }
  669. if (fifoCount == 0 && !adcActive()) {
  670. break;
  671. }
  672. }
  673. Serial.println();
  674. // Truncate file if recording stopped early.
  675. if (binFile.curPosition() < MAX_FILE_SIZE) {
  676. Serial.println(F("Truncating file"));
  677. Serial.flush();
  678. if (!binFile.truncate()) {
  679. error("Can't truncate file");
  680. }
  681. }
  682. Serial.print(F("Max write latency usec: "));
  683. Serial.println(maxLatencyUsec);
  684. Serial.print(F("Record time sec: "));
  685. Serial.println(0.001*(t1 - t0), 3);
  686. Serial.print(F("Sample count: "));
  687. Serial.println(count/PIN_COUNT);
  688. Serial.print(F("Overruns: "));
  689. Serial.println(overruns);
  690. Serial.print(F("FIFO_DIM: "));
  691. Serial.println(FIFO_DIM);
  692. Serial.print(F("maxFifoUse: "));
  693. Serial.println(maxFifoUse + 1); // include ISR use.
  694. Serial.println(F("Done"));
  695. }
  696. //------------------------------------------------------------------------------
  697. void openBinFile() {
  698. char name[NAME_DIM];
  699. clearSerialInput();
  700. Serial.println(F("Enter file name"));
  701. if (!serialReadLine(name, sizeof(name))) {
  702. return;
  703. }
  704. if (!sd.exists(name)) {
  705. Serial.println(name);
  706. Serial.println(F("File does not exist"));
  707. return;
  708. }
  709. binFile.close();
  710. if (!binFile.open(name, O_RDWR)) {
  711. Serial.println(name);
  712. Serial.println(F("open failed"));
  713. return;
  714. }
  715. Serial.println(F("File opened"));
  716. }
  717. //------------------------------------------------------------------------------
  718. // Print data file to Serial
  719. void printData() {
  720. block_t buf;
  721. if (!binFile.isOpen()) {
  722. Serial.println(F("No current binary file"));
  723. return;
  724. }
  725. binFile.rewind();
  726. if (binFile.read(&buf , sizeof(buf)) != sizeof(buf)) {
  727. error("Read metadata failed");
  728. }
  729. Serial.println(F("Type any character to stop"));
  730. delay(1000);
  731. while (!Serial.available() &&
  732. binFile.read(&buf , sizeof(buf)) == sizeof(buf)) {
  733. if (buf.count == 0) {
  734. break;
  735. }
  736. if (buf.overrun) {
  737. Serial.print(F("OVERRUN,"));
  738. Serial.println(buf.overrun);
  739. }
  740. for (size_t i = 0; i < buf.count; i++) {
  741. Serial.print(buf.data[i], DEC);
  742. if ((i+1)%PIN_COUNT) {
  743. Serial.print(',');
  744. } else {
  745. Serial.println();
  746. }
  747. }
  748. }
  749. Serial.println(F("Done"));
  750. }
  751. //------------------------------------------------------------------------------
  752. bool serialReadLine(char* str, size_t size) {
  753. size_t n = 0;
  754. while(!Serial.available()) {
  755. }
  756. while (true) {
  757. int c = Serial.read();
  758. if (c < ' ') break;
  759. str[n++] = c;
  760. if (n >= size) {
  761. Serial.println(F("input too long"));
  762. return false;
  763. }
  764. uint32_t m = millis();
  765. while (!Serial.available() && (millis() - m) < 100){}
  766. if (!Serial.available()) break;
  767. }
  768. str[n] = 0;
  769. return true;
  770. }
  771. //------------------------------------------------------------------------------
  772. void setup(void) {
  773. if (ERROR_LED_PIN >= 0) {
  774. pinMode(ERROR_LED_PIN, OUTPUT);
  775. }
  776. Serial.begin(9600);
  777. while(!Serial) {}
  778. Serial.println(F("Type any character to begin."));
  779. while(!Serial.available()) {}
  780. FillStack();
  781. // Read the first sample pin to init the ADC.
  782. analogRead(PIN_LIST[0]);
  783. #if !ENABLE_DEDICATED_SPI
  784. Serial.println(F(
  785. "\nFor best performance edit SdFatConfig.h\n"
  786. "and set ENABLE_DEDICATED_SPI nonzero"));
  787. #endif // !ENABLE_DEDICATED_SPI
  788. // Initialize SD.
  789. if (!sd.begin(SD_CONFIG)) {
  790. error("sd.begin failed");
  791. }
  792. #if USE_RTC
  793. if (!rtc.begin()) {
  794. error("rtc.begin failed");
  795. }
  796. if (!rtc.isrunning()) {
  797. // Set RTC to sketch compile date & time.
  798. // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  799. error("RTC is NOT running!");
  800. } else {
  801. Serial.println(F("RTC is running"));
  802. }
  803. // Set callback
  804. FsDateTime::setCallback(dateTime);
  805. #endif // USE_RTC
  806. }
  807. //------------------------------------------------------------------------------
  808. void loop(void) {
  809. printUnusedStack();
  810. // Read any Serial data.
  811. clearSerialInput();
  812. Serial.println();
  813. Serial.println(F("type:"));
  814. Serial.println(F("b - open existing bin file"));
  815. Serial.println(F("c - convert file to csv"));
  816. Serial.println(F("l - list files"));
  817. Serial.println(F("p - print data to Serial"));
  818. Serial.println(F("r - record ADC data"));
  819. while(!Serial.available()) {
  820. SysCall::yield();
  821. }
  822. char c = tolower(Serial.read());
  823. Serial.println();
  824. if (ERROR_LED_PIN >= 0) {
  825. digitalWrite(ERROR_LED_PIN, LOW);
  826. }
  827. // Read any Serial data.
  828. clearSerialInput();
  829. if (c == 'b') {
  830. openBinFile();
  831. } else if (c == 'c') {
  832. if (createCsvFile()) {
  833. binaryToCsv();
  834. }
  835. } else if (c == 'l') {
  836. Serial.println(F("ls:"));
  837. sd.ls(&Serial, LS_DATE | LS_SIZE);
  838. } else if (c == 'p') {
  839. printData();
  840. } else if (c == 'r') {
  841. createBinFile();
  842. logData();
  843. } else {
  844. Serial.println(F("Invalid entry"));
  845. }
  846. }
  847. #else // __AVR__
  848. #error This program is only for AVR.
  849. #endif // __AVR__