選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

829 行
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 = 100;
  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;
  272. - (PIN_COUNT > 1 ? ISR_SETUP_ADC : 0);
  273. for (adps = 7; adps > 0; adps--) {
  274. if (adcCycles >= (MIN_ADC_CYCLES << adps)) {
  275. break;
  276. }
  277. }
  278. #endif // ADC_PRESCALER
  279. meta->adcFrequency = F_CPU >> adps;
  280. if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) {
  281. error("Sample Rate Too High");
  282. }
  283. #if ROUND_SAMPLE_INTERVAL
  284. // Round so interval is multiple of ADC clock.
  285. ticks += 1 << (adps - 1);
  286. ticks >>= adps;
  287. ticks <<= adps;
  288. #endif // ROUND_SAMPLE_INTERVAL
  289. if (PIN_COUNT > sizeof(meta->pinNumber)/sizeof(meta->pinNumber[0])) {
  290. error("Too many pins");
  291. }
  292. meta->pinCount = PIN_COUNT;
  293. meta->recordEightBits = RECORD_EIGHT_BITS;
  294. for (int i = 0; i < PIN_COUNT; i++) {
  295. uint8_t pin = PIN_LIST[i];
  296. if (pin >= NUM_ANALOG_INPUTS) {
  297. error("Invalid Analog pin number");
  298. }
  299. meta->pinNumber[i] = pin;
  300. // Set ADC reference and low three bits of analog pin number.
  301. adcmux[i] = (pin & 7) | ADC_REF;
  302. if (RECORD_EIGHT_BITS) {
  303. adcmux[i] |= 1 << ADLAR;
  304. }
  305. // If this is the first pin, trigger on timer/counter 1 compare match B.
  306. adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0;
  307. #ifdef MUX5
  308. if (pin > 7) {
  309. adcsrb[i] |= (1 << MUX5);
  310. }
  311. #endif // MUX5
  312. adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps;
  313. adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC;
  314. }
  315. // Setup timer1
  316. TCCR1A = 0;
  317. uint8_t tshift;
  318. if (ticks < 0X10000) {
  319. // no prescale, CTC mode
  320. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
  321. tshift = 0;
  322. } else if (ticks < 0X10000*8) {
  323. // prescale 8, CTC mode
  324. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
  325. tshift = 3;
  326. } else if (ticks < 0X10000*64) {
  327. // prescale 64, CTC mode
  328. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10);
  329. tshift = 6;
  330. } else if (ticks < 0X10000*256) {
  331. // prescale 256, CTC mode
  332. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);
  333. tshift = 8;
  334. } else if (ticks < 0X10000*1024) {
  335. // prescale 1024, CTC mode
  336. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10);
  337. tshift = 10;
  338. } else {
  339. error("Sample Rate Too Slow");
  340. }
  341. // divide by prescaler
  342. ticks >>= tshift;
  343. // set TOP for timer reset
  344. ICR1 = ticks - 1;
  345. // compare for ADC start
  346. OCR1B = 0;
  347. // multiply by prescaler
  348. ticks <<= tshift;
  349. // Sample interval in CPU clock ticks.
  350. meta->sampleInterval = ticks;
  351. meta->cpuFrequency = F_CPU;
  352. float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval;
  353. Serial.print(F("Sample pins:"));
  354. for (int i = 0; i < meta->pinCount; i++) {
  355. Serial.print(' ');
  356. Serial.print(meta->pinNumber[i], DEC);
  357. }
  358. Serial.println();
  359. Serial.print(F("ADC bits: "));
  360. Serial.println(meta->recordEightBits ? 8 : 10);
  361. Serial.print(F("ADC clock kHz: "));
  362. Serial.println(meta->adcFrequency/1000);
  363. Serial.print(F("Sample Rate: "));
  364. Serial.println(sampleRate);
  365. Serial.print(F("Sample interval usec: "));
  366. Serial.println(1000000.0/sampleRate, 4);
  367. }
  368. //------------------------------------------------------------------------------
  369. // enable ADC and timer1 interrupts
  370. void adcStart() {
  371. // initialize ISR
  372. isrBufNeeded = true;
  373. isrOver = 0;
  374. adcindex = 1;
  375. // Clear any pending interrupt.
  376. ADCSRA |= 1 << ADIF;
  377. // Setup for first pin.
  378. ADMUX = adcmux[0];
  379. ADCSRB = adcsrb[0];
  380. ADCSRA = adcsra[0];
  381. // Enable timer1 interrupts.
  382. timerError = false;
  383. timerFlag = false;
  384. TCNT1 = 0;
  385. TIFR1 = 1 << OCF1B;
  386. TIMSK1 = 1 << OCIE1B;
  387. }
  388. //------------------------------------------------------------------------------
  389. void adcStop() {
  390. TIMSK1 = 0;
  391. ADCSRA = 0;
  392. }
  393. //------------------------------------------------------------------------------
  394. // Convert binary file to csv file.
  395. void binaryToCsv() {
  396. uint8_t lastPct = 0;
  397. block_t buf;
  398. metadata_t* pm;
  399. uint32_t t0 = millis();
  400. char csvName[13];
  401. StdioStream csvStream;
  402. if (!binFile.isOpen()) {
  403. Serial.println(F("No current binary file"));
  404. return;
  405. }
  406. binFile.rewind();
  407. if (!binFile.read(&buf , 512) == 512) {
  408. error("Read metadata failed");
  409. }
  410. // Create a new csv file.
  411. strcpy(csvName, binName);
  412. strcpy(&csvName[BASE_NAME_SIZE + 3], "csv");
  413. if (!csvStream.fopen(csvName, "w")) {
  414. error("open csvStream failed");
  415. }
  416. Serial.println();
  417. Serial.print(F("Writing: "));
  418. Serial.print(csvName);
  419. Serial.println(F(" - type any character to stop"));
  420. pm = (metadata_t*)&buf;
  421. csvStream.print(F("Interval,"));
  422. float intervalMicros = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency;
  423. csvStream.print(intervalMicros, 4);
  424. csvStream.println(F(",usec"));
  425. for (uint8_t i = 0; i < pm->pinCount; i++) {
  426. if (i) {
  427. csvStream.putc(',');
  428. }
  429. csvStream.print(F("pin"));
  430. csvStream.print(pm->pinNumber[i]);
  431. }
  432. csvStream.println();
  433. uint32_t tPct = millis();
  434. while (!Serial.available() && binFile.read(&buf, 512) == 512) {
  435. uint16_t i;
  436. if (buf.count == 0) {
  437. break;
  438. }
  439. if (buf.overrun) {
  440. csvStream.print(F("OVERRUN,"));
  441. csvStream.println(buf.overrun);
  442. }
  443. for (uint16_t j = 0; j < buf.count; j += PIN_COUNT) {
  444. for (uint16_t i = 0; i < PIN_COUNT; i++) {
  445. if (i) {
  446. csvStream.putc(',');
  447. }
  448. csvStream.print(buf.data[i + j]);
  449. }
  450. csvStream.println();
  451. }
  452. if ((millis() - tPct) > 1000) {
  453. uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100);
  454. if (pct != lastPct) {
  455. tPct = millis();
  456. lastPct = pct;
  457. Serial.print(pct, DEC);
  458. Serial.println('%');
  459. }
  460. }
  461. if (Serial.available()) {
  462. break;
  463. }
  464. }
  465. csvStream.fclose();
  466. Serial.print(F("Done: "));
  467. Serial.print(0.001*(millis() - t0));
  468. Serial.println(F(" Seconds"));
  469. }
  470. //------------------------------------------------------------------------------
  471. // read data file and check for overruns
  472. void checkOverrun() {
  473. bool headerPrinted = false;
  474. block_t buf;
  475. uint32_t bgnBlock, endBlock;
  476. uint32_t bn = 0;
  477. if (!binFile.isOpen()) {
  478. Serial.println(F("No current binary file"));
  479. return;
  480. }
  481. if (!binFile.contiguousRange(&bgnBlock, &endBlock)) {
  482. error("contiguousRange failed");
  483. }
  484. binFile.rewind();
  485. Serial.println();
  486. Serial.println(F("Checking overrun errors - type any character to stop"));
  487. if (!binFile.read(&buf , 512) == 512) {
  488. error("Read metadata failed");
  489. }
  490. bn++;
  491. while (binFile.read(&buf, 512) == 512) {
  492. if (buf.count == 0) {
  493. break;
  494. }
  495. if (buf.overrun) {
  496. if (!headerPrinted) {
  497. Serial.println();
  498. Serial.println(F("Overruns:"));
  499. Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount"));
  500. headerPrinted = true;
  501. }
  502. Serial.print(bn);
  503. Serial.print(',');
  504. Serial.print(bgnBlock + bn);
  505. Serial.print(',');
  506. Serial.println(buf.overrun);
  507. }
  508. bn++;
  509. }
  510. if (!headerPrinted) {
  511. Serial.println(F("No errors found"));
  512. } else {
  513. Serial.println(F("Done"));
  514. }
  515. }
  516. //------------------------------------------------------------------------------
  517. // dump data file to Serial
  518. void dumpData() {
  519. block_t buf;
  520. if (!binFile.isOpen()) {
  521. Serial.println(F("No current binary file"));
  522. return;
  523. }
  524. binFile.rewind();
  525. if (binFile.read(&buf , 512) != 512) {
  526. error("Read metadata failed");
  527. }
  528. Serial.println();
  529. Serial.println(F("Type any character to stop"));
  530. delay(1000);
  531. while (!Serial.available() && binFile.read(&buf , 512) == 512) {
  532. if (buf.count == 0) {
  533. break;
  534. }
  535. if (buf.overrun) {
  536. Serial.print(F("OVERRUN,"));
  537. Serial.println(buf.overrun);
  538. }
  539. for (uint16_t i = 0; i < buf.count; i++) {
  540. Serial.print(buf.data[i], DEC);
  541. if ((i+1)%PIN_COUNT) {
  542. Serial.print(',');
  543. } else {
  544. Serial.println();
  545. }
  546. }
  547. }
  548. Serial.println(F("Done"));
  549. }
  550. //------------------------------------------------------------------------------
  551. // log data
  552. // max number of blocks to erase per erase call
  553. uint32_t const ERASE_SIZE = 262144L;
  554. void logData() {
  555. uint32_t bgnBlock, endBlock;
  556. // Allocate extra buffer space.
  557. block_t block[BUFFER_BLOCK_COUNT];
  558. Serial.println();
  559. // Initialize ADC and timer1.
  560. adcInit((metadata_t*) &block[0]);
  561. // Find unused file name.
  562. if (BASE_NAME_SIZE > 6) {
  563. error("FILE_BASE_NAME too long");
  564. }
  565. while (sd.exists(binName)) {
  566. if (binName[BASE_NAME_SIZE + 1] != '9') {
  567. binName[BASE_NAME_SIZE + 1]++;
  568. } else {
  569. binName[BASE_NAME_SIZE + 1] = '0';
  570. if (binName[BASE_NAME_SIZE] == '9') {
  571. error("Can't create file name");
  572. }
  573. binName[BASE_NAME_SIZE]++;
  574. }
  575. }
  576. // Delete old tmp file.
  577. if (sd.exists(TMP_FILE_NAME)) {
  578. Serial.println(F("Deleting tmp file"));
  579. if (!sd.remove(TMP_FILE_NAME)) {
  580. error("Can't remove tmp file");
  581. }
  582. }
  583. // Create new file.
  584. Serial.println(F("Creating new file"));
  585. binFile.close();
  586. if (!binFile.createContiguous(sd.vwd(),
  587. TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) {
  588. error("createContiguous failed");
  589. }
  590. // Get the address of the file on the SD.
  591. if (!binFile.contiguousRange(&bgnBlock, &endBlock)) {
  592. error("contiguousRange failed");
  593. }
  594. // Use SdFat's internal buffer.
  595. uint8_t* cache = (uint8_t*)sd.vol()->cacheClear();
  596. if (cache == 0) {
  597. error("cacheClear failed");
  598. }
  599. // Flash erase all data in the file.
  600. Serial.println(F("Erasing all data"));
  601. uint32_t bgnErase = bgnBlock;
  602. uint32_t endErase;
  603. while (bgnErase < endBlock) {
  604. endErase = bgnErase + ERASE_SIZE;
  605. if (endErase > endBlock) {
  606. endErase = endBlock;
  607. }
  608. if (!sd.card()->erase(bgnErase, endErase)) {
  609. error("erase failed");
  610. }
  611. bgnErase = endErase + 1;
  612. }
  613. // Start a multiple block write.
  614. if (!sd.card()->writeStart(bgnBlock, FILE_BLOCK_COUNT)) {
  615. error("writeBegin failed");
  616. }
  617. // Write metadata.
  618. if (!sd.card()->writeData((uint8_t*)&block[0])) {
  619. error("Write metadata failed");
  620. }
  621. // Initialize queues.
  622. emptyHead = emptyTail = 0;
  623. fullHead = fullTail = 0;
  624. // Use SdFat buffer for one block.
  625. emptyQueue[emptyHead] = (block_t*)cache;
  626. emptyHead = queueNext(emptyHead);
  627. // Put rest of buffers in the empty queue.
  628. for (uint8_t i = 0; i < BUFFER_BLOCK_COUNT; i++) {
  629. emptyQueue[emptyHead] = &block[i];
  630. emptyHead = queueNext(emptyHead);
  631. }
  632. // Give SD time to prepare for big write.
  633. delay(1000);
  634. Serial.println(F("Logging - type any character to stop"));
  635. // Wait for Serial Idle.
  636. Serial.flush();
  637. delay(10);
  638. uint32_t bn = 1;
  639. uint32_t t0 = millis();
  640. uint32_t t1 = t0;
  641. uint32_t overruns = 0;
  642. uint32_t count = 0;
  643. uint32_t maxLatency = 0;
  644. // Start logging interrupts.
  645. adcStart();
  646. while (1) {
  647. if (fullHead != fullTail) {
  648. // Get address of block to write.
  649. block_t* pBlock = fullQueue[fullTail];
  650. // Write block to SD.
  651. uint32_t usec = micros();
  652. if (!sd.card()->writeData((uint8_t*)pBlock)) {
  653. error("write data failed");
  654. }
  655. usec = micros() - usec;
  656. t1 = millis();
  657. if (usec > maxLatency) {
  658. maxLatency = usec;
  659. }
  660. count += pBlock->count;
  661. // Add overruns and possibly light LED.
  662. if (pBlock->overrun) {
  663. overruns += pBlock->overrun;
  664. if (ERROR_LED_PIN >= 0) {
  665. digitalWrite(ERROR_LED_PIN, HIGH);
  666. }
  667. }
  668. // Move block to empty queue.
  669. emptyQueue[emptyHead] = pBlock;
  670. emptyHead = queueNext(emptyHead);
  671. fullTail = queueNext(fullTail);
  672. bn++;
  673. if (bn == FILE_BLOCK_COUNT) {
  674. // File full so stop ISR calls.
  675. adcStop();
  676. break;
  677. }
  678. }
  679. if (timerError) {
  680. error("Missed timer event - rate too high");
  681. }
  682. if (Serial.available()) {
  683. // Stop ISR calls.
  684. adcStop();
  685. if (isrBuf != 0 && isrBuf->count >= PIN_COUNT) {
  686. // Truncate to last complete sample.
  687. isrBuf->count = PIN_COUNT*(isrBuf->count/PIN_COUNT);
  688. // Put buffer in full queue.
  689. fullQueue[fullHead] = isrBuf;
  690. fullHead = queueNext(fullHead);
  691. isrBuf = 0;
  692. }
  693. if (fullHead == fullTail) {
  694. break;
  695. }
  696. }
  697. }
  698. if (!sd.card()->writeStop()) {
  699. error("writeStop failed");
  700. }
  701. // Truncate file if recording stopped early.
  702. if (bn != FILE_BLOCK_COUNT) {
  703. Serial.println(F("Truncating file"));
  704. if (!binFile.truncate(512L * bn)) {
  705. error("Can't truncate file");
  706. }
  707. }
  708. if (!binFile.rename(sd.vwd(), binName)) {
  709. error("Can't rename file");
  710. }
  711. Serial.print(F("File renamed: "));
  712. Serial.println(binName);
  713. Serial.print(F("Max block write usec: "));
  714. Serial.println(maxLatency);
  715. Serial.print(F("Record time sec: "));
  716. Serial.println(0.001*(t1 - t0), 3);
  717. Serial.print(F("Sample count: "));
  718. Serial.println(count/PIN_COUNT);
  719. Serial.print(F("Samples/sec: "));
  720. Serial.println((1000.0/PIN_COUNT)*count/(t1-t0));
  721. Serial.print(F("Overruns: "));
  722. Serial.println(overruns);
  723. Serial.println(F("Done"));
  724. }
  725. //------------------------------------------------------------------------------
  726. void setup(void) {
  727. if (ERROR_LED_PIN >= 0) {
  728. pinMode(ERROR_LED_PIN, OUTPUT);
  729. }
  730. Serial.begin(9600);
  731. // Read the first sample pin to init the ADC.
  732. analogRead(PIN_LIST[0]);
  733. Serial.print(F("FreeStack: "));
  734. Serial.println(FreeStack());
  735. // initialize file system.
  736. if (!sd.begin(SD_CS_PIN, SPI_FULL_SPEED)) {
  737. sd.initErrorPrint();
  738. fatalBlink();
  739. }
  740. }
  741. //------------------------------------------------------------------------------
  742. void loop(void) {
  743. // discard any input
  744. while (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. char c = tolower(Serial.read());
  753. if (ERROR_LED_PIN >= 0) {
  754. digitalWrite(ERROR_LED_PIN, LOW);
  755. }
  756. // Read any extra Serial data.
  757. do {
  758. delay(10);
  759. } while (Serial.read() >= 0);
  760. if (c == 'c') {
  761. binaryToCsv();
  762. } else if (c == 'd') {
  763. dumpData();
  764. } else if (c == 'e') {
  765. checkOverrun();
  766. } else if (c == 'r') {
  767. logData();
  768. } else {
  769. Serial.println(F("Invalid entry"));
  770. }
  771. }
  772. #else // __AVR__
  773. #error This program is only for AVR.
  774. #endif // __AVR__