Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

887 lines
26KB

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