Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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