AnalogBinLogger.ino 24 KB

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