您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

788 行
24KB

  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 13 512 byte buffers will be used.
  14. *
  15. * Each 512 byte data block in the file has a four byte header followed by up
  16. * to 508 bytes of data. (508 values in 8-bit mode or 254 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. * Data is written to the file using a SD multiple block write command.
  21. */
  22. #include <SdFat.h>
  23. #include <SdFatUtil.h>
  24. #include <StdioStream.h>
  25. #include "AnalogBinLogger.h"
  26. //------------------------------------------------------------------------------
  27. // Analog pin number list for a sample. Pins may be in any order and pin
  28. // numbers may be repeated.
  29. const uint8_t PIN_LIST[] = {0, 1, 2, 3, 4};
  30. //------------------------------------------------------------------------------
  31. // Sample rate in samples per second.
  32. const float SAMPLE_RATE = 5000; // Must be 0.25 or greater.
  33. // The interval between samples in seconds, SAMPLE_INTERVAL, may be set to a
  34. // constant instead of being calculated from SAMPLE_RATE. SAMPLE_RATE is not
  35. // used in the code below. For example, setting SAMPLE_INTERVAL = 2.0e-4
  36. // will result in a 200 microsecond sample interval.
  37. const float SAMPLE_INTERVAL = 1.0/SAMPLE_RATE;
  38. // Setting ROUND_SAMPLE_INTERVAL non-zero will cause the sample interval to
  39. // be rounded to a a multiple of the ADC clock period and will reduce sample
  40. // time jitter.
  41. #define ROUND_SAMPLE_INTERVAL 1
  42. //------------------------------------------------------------------------------
  43. // ADC clock rate.
  44. // The ADC clock rate is normally calculated from the pin count and sample
  45. // interval. The calculation attempts to use the lowest possible ADC clock
  46. // rate.
  47. //
  48. // You can select an ADC clock rate by defining the symbol ADC_PRESCALER to
  49. // one of these values. You must choose an appropriate ADC clock rate for
  50. // your sample interval.
  51. // #define ADC_PRESCALER 7 // F_CPU/128 125 kHz on an Uno
  52. // #define ADC_PRESCALER 6 // F_CPU/64 250 kHz on an Uno
  53. // #define ADC_PRESCALER 5 // F_CPU/32 500 kHz on an Uno
  54. // #define ADC_PRESCALER 4 // F_CPU/16 1000 kHz on an Uno
  55. // #define ADC_PRESCALER 3 // F_CPU/8 2000 kHz on an Uno (8-bit mode only)
  56. //------------------------------------------------------------------------------
  57. // Reference voltage. See the processor data-sheet for reference details.
  58. // uint8_t const ADC_REF = 0; // External Reference AREF pin.
  59. uint8_t const ADC_REF = (1 << REFS0); // Vcc Reference.
  60. // uint8_t const ADC_REF = (1 << REFS1); // Internal 1.1 (only 644 1284P Mega)
  61. // uint8_t const ADC_REF = (1 << REFS1) | (1 << REFS0); // Internal 1.1 or 2.56
  62. //------------------------------------------------------------------------------
  63. // File definitions.
  64. //
  65. // Maximum file size in blocks.
  66. // The program creates a contiguous file with FILE_BLOCK_COUNT 512 byte blocks.
  67. // This file is flash erased using special SD commands. The file will be
  68. // truncated if logging is stopped early.
  69. const uint32_t FILE_BLOCK_COUNT = 256000;
  70. // log file base name. Must be six characters or less.
  71. #define FILE_BASE_NAME "ANALOG"
  72. // Set RECORD_EIGHT_BITS non-zero to record only the high 8-bits of the ADC.
  73. #define RECORD_EIGHT_BITS 0
  74. //------------------------------------------------------------------------------
  75. // Pin definitions.
  76. //
  77. // Digital pin to indicate an error, set to -1 if not used.
  78. // The led blinks for fatal errors. The led goes on solid for SD write
  79. // overrun errors and logging continues.
  80. const int8_t ERROR_LED_PIN = 3;
  81. // SD chip select pin.
  82. const uint8_t SD_CS_PIN = SS;
  83. //------------------------------------------------------------------------------
  84. // Buffer definitions.
  85. //
  86. // The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT additional
  87. // buffers. QUEUE_DIM must be a power of two larger than
  88. //(BUFFER_BLOCK_COUNT + 1).
  89. //
  90. #if RAMEND < 0X8FF
  91. #error Too little SRAM
  92. //
  93. #elif RAMEND < 0X10FF
  94. // Use total of two 512 byte buffers.
  95. const uint8_t BUFFER_BLOCK_COUNT = 1;
  96. // Dimension for queues of 512 byte SD blocks.
  97. const uint8_t QUEUE_DIM = 4; // Must be a power of two!
  98. //
  99. #elif RAMEND < 0X20FF
  100. // Use total of five 512 byte buffers.
  101. const uint8_t BUFFER_BLOCK_COUNT = 4;
  102. // Dimension for queues of 512 byte SD blocks.
  103. const uint8_t QUEUE_DIM = 8; // Must be a power of two!
  104. //
  105. #elif RAMEND < 0X40FF
  106. // Use total of 13 512 byte buffers.
  107. const uint8_t BUFFER_BLOCK_COUNT = 12;
  108. // Dimension for queues of 512 byte SD blocks.
  109. const uint8_t QUEUE_DIM = 16; // Must be a power of two!
  110. //
  111. #else // RAMEND
  112. // Use total of 29 512 byte buffers.
  113. const uint8_t BUFFER_BLOCK_COUNT = 28;
  114. // Dimension for queues of 512 byte SD blocks.
  115. const uint8_t QUEUE_DIM = 32; // Must be a power of two!
  116. #endif // RAMEND
  117. //==============================================================================
  118. // End of configuration constants.
  119. //==============================================================================
  120. // Temporary log file. Will be deleted if a reset or power failure occurs.
  121. #define TMP_FILE_NAME "TMP_LOG.BIN"
  122. // Size of file base name. Must not be larger than six.
  123. const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
  124. // Number of analog pins to log.
  125. const uint8_t PIN_COUNT = sizeof(PIN_LIST)/sizeof(PIN_LIST[0]);
  126. // Minimum ADC clock cycles per sample interval
  127. const uint16_t MIN_ADC_CYCLES = 15;
  128. // Extra cpu cycles to setup ADC with more than one pin per sample.
  129. const uint16_t ISR_SETUP_ADC = 100;
  130. // Maximum cycles for timer0 system interrupt, millis, micros.
  131. const uint16_t ISR_TIMER0 = 160;
  132. //==============================================================================
  133. SdFat sd;
  134. SdBaseFile binFile;
  135. char binName[13] = FILE_BASE_NAME "00.BIN";
  136. #if RECORD_EIGHT_BITS
  137. const size_t SAMPLES_PER_BLOCK = DATA_DIM8/PIN_COUNT;
  138. typedef block8_t block_t;
  139. #else // RECORD_EIGHT_BITS
  140. const size_t SAMPLES_PER_BLOCK = DATA_DIM16/PIN_COUNT;
  141. typedef block16_t block_t;
  142. #endif // RECORD_EIGHT_BITS
  143. block_t* emptyQueue[QUEUE_DIM];
  144. uint8_t emptyHead;
  145. uint8_t emptyTail;
  146. block_t* fullQueue[QUEUE_DIM];
  147. volatile uint8_t fullHead; // volatile insures non-interrupt code sees changes.
  148. uint8_t fullTail;
  149. // queueNext assumes QUEUE_DIM is a power of two
  150. inline uint8_t queueNext(uint8_t ht) {return (ht + 1) & (QUEUE_DIM -1);}
  151. //==============================================================================
  152. // Interrupt Service Routines
  153. // Pointer to current buffer.
  154. block_t* isrBuf;
  155. // Need new buffer if true.
  156. bool isrBufNeeded = true;
  157. // overrun count
  158. uint16_t isrOver = 0;
  159. // ADC configuration for each pin.
  160. uint8_t adcmux[PIN_COUNT];
  161. uint8_t adcsra[PIN_COUNT];
  162. uint8_t adcsrb[PIN_COUNT];
  163. uint8_t adcindex = 1;
  164. // Insure no timer events are missed.
  165. volatile bool timerError = false;
  166. volatile bool timerFlag = false;
  167. //------------------------------------------------------------------------------
  168. // ADC done interrupt.
  169. ISR(ADC_vect) {
  170. // Read ADC data.
  171. #if RECORD_EIGHT_BITS
  172. uint8_t d = ADCH;
  173. #else // RECORD_EIGHT_BITS
  174. // This will access ADCL first.
  175. uint16_t d = ADC;
  176. #endif // RECORD_EIGHT_BITS
  177. if (isrBufNeeded && emptyHead == emptyTail) {
  178. // no buffers - count overrun
  179. if (isrOver < 0XFFFF) isrOver++;
  180. // Avoid missed timer error.
  181. timerFlag = false;
  182. return;
  183. }
  184. // Start ADC
  185. if (PIN_COUNT > 1) {
  186. ADMUX = adcmux[adcindex];
  187. ADCSRB = adcsrb[adcindex];
  188. ADCSRA = adcsra[adcindex];
  189. if (adcindex == 0) timerFlag = false;
  190. adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0;
  191. } else {
  192. timerFlag = false;
  193. }
  194. // Check for buffer needed.
  195. if (isrBufNeeded) {
  196. // Remove buffer from empty queue.
  197. isrBuf = emptyQueue[emptyTail];
  198. emptyTail = queueNext(emptyTail);
  199. isrBuf->count = 0;
  200. isrBuf->overrun = isrOver;
  201. isrBufNeeded = false;
  202. }
  203. // Store ADC data.
  204. isrBuf->data[isrBuf->count++] = d;
  205. // Check for buffer full.
  206. if (isrBuf->count >= PIN_COUNT*SAMPLES_PER_BLOCK) {
  207. // Put buffer isrIn full queue.
  208. uint8_t tmp = fullHead; // Avoid extra fetch of volatile fullHead.
  209. fullQueue[tmp] = (block_t*)isrBuf;
  210. fullHead = queueNext(tmp);
  211. // Set buffer needed and clear overruns.
  212. isrBufNeeded = true;
  213. isrOver = 0;
  214. }
  215. }
  216. //------------------------------------------------------------------------------
  217. // timer1 interrupt to clear OCF1B
  218. ISR(TIMER1_COMPB_vect) {
  219. // Make sure ADC ISR responded to timer event.
  220. if (timerFlag) timerError = true;
  221. timerFlag = true;
  222. }
  223. //==============================================================================
  224. // Error messages stored in flash.
  225. #define error(msg) error_P(PSTR(msg))
  226. //------------------------------------------------------------------------------
  227. void error_P(const char* msg) {
  228. sd.errorPrint_P(msg);
  229. fatalBlink();
  230. }
  231. //------------------------------------------------------------------------------
  232. //
  233. void fatalBlink() {
  234. while (true) {
  235. if (ERROR_LED_PIN >= 0) {
  236. digitalWrite(ERROR_LED_PIN, HIGH);
  237. delay(200);
  238. digitalWrite(ERROR_LED_PIN, LOW);
  239. delay(200);
  240. }
  241. }
  242. }
  243. //==============================================================================
  244. #if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2
  245. #error unexpected ADC prescaler bits
  246. #endif
  247. //------------------------------------------------------------------------------
  248. // initialize ADC and timer1
  249. void adcInit(metadata_t* meta) {
  250. uint8_t adps; // prescaler bits for ADCSRA
  251. uint32_t ticks = F_CPU*SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles.
  252. if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) {
  253. error("Invalid ADC reference");
  254. }
  255. #ifdef ADC_PRESCALER
  256. if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) {
  257. error("Invalid ADC prescaler");
  258. }
  259. adps = ADC_PRESCALER;
  260. #else // ADC_PRESCALER
  261. // Allow extra cpu cycles to change ADC settings if more than one pin.
  262. int32_t adcCycles = (ticks - ISR_TIMER0)/PIN_COUNT;
  263. - (PIN_COUNT > 1 ? ISR_SETUP_ADC : 0);
  264. for (adps = 7; adps > 0; adps--) {
  265. if (adcCycles >= (MIN_ADC_CYCLES << adps)) break;
  266. }
  267. #endif // ADC_PRESCALER
  268. meta->adcFrequency = F_CPU >> adps;
  269. if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) {
  270. error("Sample Rate Too High");
  271. }
  272. #if ROUND_SAMPLE_INTERVAL
  273. // Round so interval is multiple of ADC clock.
  274. ticks += 1 << (adps - 1);
  275. ticks >>= adps;
  276. ticks <<= adps;
  277. #endif // ROUND_SAMPLE_INTERVAL
  278. if (PIN_COUNT > sizeof(meta->pinNumber)/sizeof(meta->pinNumber[0])) {
  279. error("Too many pins");
  280. }
  281. meta->pinCount = PIN_COUNT;
  282. meta->recordEightBits = RECORD_EIGHT_BITS;
  283. for (int i = 0; i < PIN_COUNT; i++) {
  284. uint8_t pin = PIN_LIST[i];
  285. if (pin >= NUM_ANALOG_INPUTS) error("Invalid Analog pin number");
  286. meta->pinNumber[i] = pin;
  287. // Set ADC reference and low three bits of analog pin number.
  288. adcmux[i] = (pin & 7) | ADC_REF;
  289. if (RECORD_EIGHT_BITS) adcmux[i] |= 1 << ADLAR;
  290. // If this is the first pin, trigger on timer/counter 1 compare match B.
  291. adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0;
  292. #ifdef MUX5
  293. if (pin > 7) adcsrb[i] |= (1 << MUX5);
  294. #endif // MUX5
  295. adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps;
  296. adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC;
  297. }
  298. // Setup timer1
  299. TCCR1A = 0;
  300. uint8_t tshift;
  301. if (ticks < 0X10000) {
  302. // no prescale, CTC mode
  303. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
  304. tshift = 0;
  305. } else if (ticks < 0X10000*8) {
  306. // prescale 8, CTC mode
  307. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
  308. tshift = 3;
  309. } else if (ticks < 0X10000*64) {
  310. // prescale 64, CTC mode
  311. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10);
  312. tshift = 6;
  313. } else if (ticks < 0X10000*256) {
  314. // prescale 256, CTC mode
  315. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);
  316. tshift = 8;
  317. } else if (ticks < 0X10000*1024) {
  318. // prescale 1024, CTC mode
  319. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10);
  320. tshift = 10;
  321. } else {
  322. error("Sample Rate Too Slow");
  323. }
  324. // divide by prescaler
  325. ticks >>= tshift;
  326. // set TOP for timer reset
  327. ICR1 = ticks - 1;
  328. // compare for ADC start
  329. OCR1B = 0;
  330. // multiply by prescaler
  331. ticks <<= tshift;
  332. // Sample interval in CPU clock ticks.
  333. meta->sampleInterval = ticks;
  334. meta->cpuFrequency = F_CPU;
  335. float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval;
  336. Serial.print(F("Sample pins:"));
  337. for (int i = 0; i < meta->pinCount; i++) {
  338. Serial.print(' ');
  339. Serial.print(meta->pinNumber[i], DEC);
  340. }
  341. Serial.println();
  342. Serial.print(F("ADC bits: "));
  343. Serial.println(meta->recordEightBits ? 8 : 10);
  344. Serial.print(F("ADC clock kHz: "));
  345. Serial.println(meta->adcFrequency/1000);
  346. Serial.print(F("Sample Rate: "));
  347. Serial.println(sampleRate);
  348. Serial.print(F("Sample interval usec: "));
  349. Serial.println(1000000.0/sampleRate, 4);
  350. }
  351. //------------------------------------------------------------------------------
  352. // enable ADC and timer1 interrupts
  353. void adcStart() {
  354. // initialize ISR
  355. isrBufNeeded = true;
  356. isrOver = 0;
  357. adcindex = 1;
  358. // Clear any pending interrupt.
  359. ADCSRA |= 1 << ADIF;
  360. // Setup for first pin.
  361. ADMUX = adcmux[0];
  362. ADCSRB = adcsrb[0];
  363. ADCSRA = adcsra[0];
  364. // Enable timer1 interrupts.
  365. timerError = false;
  366. timerFlag = false;
  367. TCNT1 = 0;
  368. TIFR1 = 1 << OCF1B;
  369. TIMSK1 = 1 << OCIE1B;
  370. }
  371. //------------------------------------------------------------------------------
  372. void adcStop() {
  373. TIMSK1 = 0;
  374. ADCSRA = 0;
  375. }
  376. //------------------------------------------------------------------------------
  377. // Convert binary file to CSV file.
  378. void binaryToCsv() {
  379. uint8_t lastPct = 0;
  380. block_t buf;
  381. metadata_t* pm;
  382. uint32_t t0 = millis();
  383. char csvName[13];
  384. StdioStream csvStream;
  385. if (!binFile.isOpen()) {
  386. Serial.println(F("No current binary file"));
  387. return;
  388. }
  389. binFile.rewind();
  390. if (!binFile.read(&buf , 512) == 512) error("Read metadata failed");
  391. // Create a new CSV file.
  392. strcpy(csvName, binName);
  393. strcpy_P(&csvName[BASE_NAME_SIZE + 3], PSTR("CSV"));
  394. if (!csvStream.fopen(csvName, "w")) {
  395. error("open csvStream failed");
  396. }
  397. Serial.println();
  398. Serial.print(F("Writing: "));
  399. Serial.print(csvName);
  400. Serial.println(F(" - type any character to stop"));
  401. pm = (metadata_t*)&buf;
  402. csvStream.print(F("Interval,"));
  403. float intervalMicros = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency;
  404. csvStream.print(intervalMicros, 4);
  405. csvStream.println(F(",usec"));
  406. for (uint8_t i = 0; i < pm->pinCount; i++) {
  407. if (i) csvStream.putc(',');
  408. csvStream.print(F("pin"));
  409. csvStream.print(pm->pinNumber[i]);
  410. }
  411. csvStream.println();
  412. uint32_t tPct = millis();
  413. while (!Serial.available() && binFile.read(&buf, 512) == 512) {
  414. uint16_t i;
  415. if (buf.count == 0) break;
  416. if (buf.overrun) {
  417. csvStream.print(F("OVERRUN,"));
  418. csvStream.println(buf.overrun);
  419. }
  420. for (uint16_t j = 0; j < buf.count; j += PIN_COUNT) {
  421. for (uint16_t i = 0; i < PIN_COUNT; i++) {
  422. if (i) csvStream.putc(',');
  423. csvStream.print(buf.data[i + j]);
  424. }
  425. csvStream.println();
  426. }
  427. if ((millis() - tPct) > 1000) {
  428. uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100);
  429. if (pct != lastPct) {
  430. tPct = millis();
  431. lastPct = pct;
  432. Serial.print(pct, DEC);
  433. Serial.println('%');
  434. }
  435. }
  436. if (Serial.available()) break;
  437. }
  438. csvStream.fclose();
  439. Serial.print(F("Done: "));
  440. Serial.print(0.001*(millis() - t0));
  441. Serial.println(F(" Seconds"));
  442. }
  443. //------------------------------------------------------------------------------
  444. // read data file and check for overruns
  445. void checkOverrun() {
  446. bool headerPrinted = false;
  447. block_t buf;
  448. uint32_t bgnBlock, endBlock;
  449. uint32_t bn = 0;
  450. if (!binFile.isOpen()) {
  451. Serial.println(F("No current binary file"));
  452. return;
  453. }
  454. if (!binFile.contiguousRange(&bgnBlock, &endBlock)) {
  455. error("contiguousRange failed");
  456. }
  457. binFile.rewind();
  458. Serial.println();
  459. Serial.println(F("Checking overrun errors - type any character to stop"));
  460. if (!binFile.read(&buf , 512) == 512) {
  461. error("Read metadata failed");
  462. }
  463. bn++;
  464. while (binFile.read(&buf, 512) == 512) {
  465. if (buf.count == 0) break;
  466. if (buf.overrun) {
  467. if (!headerPrinted) {
  468. Serial.println();
  469. Serial.println(F("Overruns:"));
  470. Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount"));
  471. headerPrinted = true;
  472. }
  473. Serial.print(bn);
  474. Serial.print(',');
  475. Serial.print(bgnBlock + bn);
  476. Serial.print(',');
  477. Serial.println(buf.overrun);
  478. }
  479. bn++;
  480. }
  481. if (!headerPrinted) {
  482. Serial.println(F("No errors found"));
  483. } else {
  484. Serial.println(F("Done"));
  485. }
  486. }
  487. //------------------------------------------------------------------------------
  488. // dump data file to Serial
  489. void dumpData() {
  490. block_t buf;
  491. if (!binFile.isOpen()) {
  492. Serial.println(F("No current binary file"));
  493. return;
  494. }
  495. binFile.rewind();
  496. if (binFile.read(&buf , 512) != 512) {
  497. error("Read metadata failed");
  498. }
  499. Serial.println();
  500. Serial.println(F("Type any character to stop"));
  501. delay(1000);
  502. while (!Serial.available() && binFile.read(&buf , 512) == 512) {
  503. if (buf.count == 0) break;
  504. if (buf.overrun) {
  505. Serial.print(F("OVERRUN,"));
  506. Serial.println(buf.overrun);
  507. }
  508. for (uint16_t i = 0; i < buf.count; i++) {
  509. Serial.print(buf.data[i], DEC);
  510. if ((i+1)%PIN_COUNT) {
  511. Serial.print(',');
  512. } else {
  513. Serial.println();
  514. }
  515. }
  516. }
  517. Serial.println(F("Done"));
  518. }
  519. //------------------------------------------------------------------------------
  520. // log data
  521. // max number of blocks to erase per erase call
  522. uint32_t const ERASE_SIZE = 262144L;
  523. void logData() {
  524. uint32_t bgnBlock, endBlock;
  525. // Allocate extra buffer space.
  526. block_t block[BUFFER_BLOCK_COUNT];
  527. Serial.println();
  528. // Initialize ADC and timer1.
  529. adcInit((metadata_t*) &block[0]);
  530. // Find unused file name.
  531. if (BASE_NAME_SIZE > 6) {
  532. error("FILE_BASE_NAME too long");
  533. }
  534. while (sd.exists(binName)) {
  535. if (binName[BASE_NAME_SIZE + 1] != '9') {
  536. binName[BASE_NAME_SIZE + 1]++;
  537. } else {
  538. binName[BASE_NAME_SIZE + 1] = '0';
  539. if (binName[BASE_NAME_SIZE] == '9') {
  540. error("Can't create file name");
  541. }
  542. binName[BASE_NAME_SIZE]++;
  543. }
  544. }
  545. // Delete old tmp file.
  546. if (sd.exists(TMP_FILE_NAME)) {
  547. Serial.println(F("Deleting tmp file"));
  548. if (!sd.remove(TMP_FILE_NAME)) {
  549. error("Can't remove tmp file");
  550. }
  551. }
  552. // Create new file.
  553. Serial.println(F("Creating new file"));
  554. binFile.close();
  555. if (!binFile.createContiguous(sd.vwd(),
  556. TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) {
  557. error("createContiguous failed");
  558. }
  559. // Get the address of the file on the SD.
  560. if (!binFile.contiguousRange(&bgnBlock, &endBlock)) {
  561. error("contiguousRange failed");
  562. }
  563. // Use SdFat's internal buffer.
  564. uint8_t* cache = (uint8_t*)sd.vol()->cacheClear();
  565. if (cache == 0) error("cacheClear failed");
  566. // Flash erase all data in the file.
  567. Serial.println(F("Erasing all data"));
  568. uint32_t bgnErase = bgnBlock;
  569. uint32_t endErase;
  570. while (bgnErase < endBlock) {
  571. endErase = bgnErase + ERASE_SIZE;
  572. if (endErase > endBlock) endErase = endBlock;
  573. if (!sd.card()->erase(bgnErase, endErase)) {
  574. error("erase failed");
  575. }
  576. bgnErase = endErase + 1;
  577. }
  578. // Start a multiple block write.
  579. if (!sd.card()->writeStart(bgnBlock, FILE_BLOCK_COUNT)) {
  580. error("writeBegin failed");
  581. }
  582. // Write metadata.
  583. if (!sd.card()->writeData((uint8_t*)&block[0])) {
  584. error("Write metadata failed");
  585. }
  586. // Initialize queues.
  587. emptyHead = emptyTail = 0;
  588. fullHead = fullTail = 0;
  589. // Use SdFat buffer for one block.
  590. emptyQueue[emptyHead] = (block_t*)cache;
  591. emptyHead = queueNext(emptyHead);
  592. // Put rest of buffers in the empty queue.
  593. for (uint8_t i = 0; i < BUFFER_BLOCK_COUNT; i++) {
  594. emptyQueue[emptyHead] = &block[i];
  595. emptyHead = queueNext(emptyHead);
  596. }
  597. // Give SD time to prepare for big write.
  598. delay(1000);
  599. Serial.println(F("Logging - type any character to stop"));
  600. // Wait for Serial Idle.
  601. Serial.flush();
  602. delay(10);
  603. uint32_t bn = 1;
  604. uint32_t t0 = millis();
  605. uint32_t t1 = t0;
  606. uint32_t overruns = 0;
  607. uint32_t count = 0;
  608. uint32_t maxLatency = 0;
  609. // Start logging interrupts.
  610. adcStart();
  611. while (1) {
  612. if (fullHead != fullTail) {
  613. // Get address of block to write.
  614. block_t* pBlock = fullQueue[fullTail];
  615. // Write block to SD.
  616. uint32_t usec = micros();
  617. if (!sd.card()->writeData((uint8_t*)pBlock)) {
  618. error("write data failed");
  619. }
  620. usec = micros() - usec;
  621. t1 = millis();
  622. if (usec > maxLatency) maxLatency = usec;
  623. count += pBlock->count;
  624. // Add overruns and possibly light LED.
  625. if (pBlock->overrun) {
  626. overruns += pBlock->overrun;
  627. if (ERROR_LED_PIN >= 0) {
  628. digitalWrite(ERROR_LED_PIN, HIGH);
  629. }
  630. }
  631. // Move block to empty queue.
  632. emptyQueue[emptyHead] = pBlock;
  633. emptyHead = queueNext(emptyHead);
  634. fullTail = queueNext(fullTail);
  635. bn++;
  636. if (bn == FILE_BLOCK_COUNT) {
  637. // File full so stop ISR calls.
  638. adcStop();
  639. break;
  640. }
  641. }
  642. if (timerError) {
  643. error("Missed timer event - rate too high");
  644. }
  645. if (Serial.available()) {
  646. // Stop ISR calls.
  647. adcStop();
  648. if (isrBuf != 0 && isrBuf->count >= PIN_COUNT) {
  649. // Truncate to last complete sample.
  650. isrBuf->count = PIN_COUNT*(isrBuf->count/PIN_COUNT);
  651. // Put buffer in full queue.
  652. fullQueue[fullHead] = isrBuf;
  653. fullHead = queueNext(fullHead);
  654. isrBuf = 0;
  655. }
  656. if (fullHead == fullTail) break;
  657. }
  658. }
  659. if (!sd.card()->writeStop()) {
  660. error("writeStop failed");
  661. }
  662. // Truncate file if recording stopped early.
  663. if (bn != FILE_BLOCK_COUNT) {
  664. Serial.println(F("Truncating file"));
  665. if (!binFile.truncate(512L * bn)) {
  666. error("Can't truncate file");
  667. }
  668. }
  669. if (!binFile.rename(sd.vwd(), binName)) {
  670. error("Can't rename file");
  671. }
  672. Serial.print(F("File renamed: "));
  673. Serial.println(binName);
  674. Serial.print(F("Max block write usec: "));
  675. Serial.println(maxLatency);
  676. Serial.print(F("Record time sec: "));
  677. Serial.println(0.001*(t1 - t0), 3);
  678. Serial.print(F("Sample count: "));
  679. Serial.println(count/PIN_COUNT);
  680. Serial.print(F("Samples/sec: "));
  681. Serial.println((1000.0/PIN_COUNT)*count/(t1-t0));
  682. Serial.print(F("Overruns: "));
  683. Serial.println(overruns);
  684. Serial.println(F("Done"));
  685. }
  686. //------------------------------------------------------------------------------
  687. void setup(void) {
  688. if (ERROR_LED_PIN >= 0) {
  689. pinMode(ERROR_LED_PIN, OUTPUT);
  690. }
  691. Serial.begin(9600);
  692. // Read the first sample pin to init the ADC.
  693. analogRead(PIN_LIST[0]);
  694. Serial.print(F("FreeRam: "));
  695. Serial.println(FreeRam());
  696. // initialize file system.
  697. if (!sd.begin(SD_CS_PIN, SPI_FULL_SPEED)) {
  698. sd.initErrorPrint();
  699. fatalBlink();
  700. }
  701. }
  702. //------------------------------------------------------------------------------
  703. void loop(void) {
  704. // discard any input
  705. while (Serial.read() >= 0) {}
  706. Serial.println();
  707. Serial.println(F("type:"));
  708. Serial.println(F("c - convert file to CSV"));
  709. Serial.println(F("d - dump data to Serial"));
  710. Serial.println(F("e - overrun error details"));
  711. Serial.println(F("r - record ADC data"));
  712. while(!Serial.available()) {}
  713. char c = tolower(Serial.read());
  714. if (ERROR_LED_PIN >= 0) {
  715. digitalWrite(ERROR_LED_PIN, LOW);
  716. }
  717. // Read any extra Serial data.
  718. do {
  719. delay(10);
  720. } while (Serial.read() >= 0);
  721. if (c == 'c') {
  722. binaryToCsv();
  723. } else if (c == 'd') {
  724. dumpData();
  725. } else if (c == 'e') {
  726. checkOverrun();
  727. } else if (c == 'r') {
  728. logData();
  729. } else {
  730. Serial.println(F("Invalid entry"));
  731. }
  732. }