Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

AnalogBinLogger.ino 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 <SdFatUtil.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) {return (ht + 1) & (QUEUE_DIM -1);}
  152. //==============================================================================
  153. // Interrupt Service Routines
  154. // Pointer to current buffer.
  155. block_t* isrBuf;
  156. // Need new buffer if true.
  157. bool isrBufNeeded = true;
  158. // overrun count
  159. uint16_t isrOver = 0;
  160. // ADC configuration for each pin.
  161. uint8_t adcmux[PIN_COUNT];
  162. uint8_t adcsra[PIN_COUNT];
  163. uint8_t adcsrb[PIN_COUNT];
  164. uint8_t adcindex = 1;
  165. // Insure no timer events are missed.
  166. volatile bool timerError = false;
  167. volatile bool timerFlag = false;
  168. //------------------------------------------------------------------------------
  169. // ADC done interrupt.
  170. ISR(ADC_vect) {
  171. // Read ADC data.
  172. #if RECORD_EIGHT_BITS
  173. uint8_t d = ADCH;
  174. #else // RECORD_EIGHT_BITS
  175. // This will access ADCL first.
  176. uint16_t d = ADC;
  177. #endif // RECORD_EIGHT_BITS
  178. if (isrBufNeeded && emptyHead == emptyTail) {
  179. // no buffers - count overrun
  180. if (isrOver < 0XFFFF) isrOver++;
  181. // Avoid missed timer error.
  182. timerFlag = false;
  183. return;
  184. }
  185. // Start ADC
  186. if (PIN_COUNT > 1) {
  187. ADMUX = adcmux[adcindex];
  188. ADCSRB = adcsrb[adcindex];
  189. ADCSRA = adcsra[adcindex];
  190. if (adcindex == 0) timerFlag = false;
  191. adcindex = adcindex < (PIN_COUNT - 1) ? adcindex + 1 : 0;
  192. } else {
  193. timerFlag = false;
  194. }
  195. // Check for buffer needed.
  196. if (isrBufNeeded) {
  197. // Remove buffer from empty queue.
  198. isrBuf = emptyQueue[emptyTail];
  199. emptyTail = queueNext(emptyTail);
  200. isrBuf->count = 0;
  201. isrBuf->overrun = isrOver;
  202. isrBufNeeded = false;
  203. }
  204. // Store ADC data.
  205. isrBuf->data[isrBuf->count++] = d;
  206. // Check for buffer full.
  207. if (isrBuf->count >= PIN_COUNT*SAMPLES_PER_BLOCK) {
  208. // Put buffer isrIn full queue.
  209. uint8_t tmp = fullHead; // Avoid extra fetch of volatile fullHead.
  210. fullQueue[tmp] = (block_t*)isrBuf;
  211. fullHead = queueNext(tmp);
  212. // Set buffer needed and clear overruns.
  213. isrBufNeeded = true;
  214. isrOver = 0;
  215. }
  216. }
  217. //------------------------------------------------------------------------------
  218. // timer1 interrupt to clear OCF1B
  219. ISR(TIMER1_COMPB_vect) {
  220. // Make sure ADC ISR responded to timer event.
  221. if (timerFlag) timerError = true;
  222. timerFlag = true;
  223. }
  224. //==============================================================================
  225. // Error messages stored in flash.
  226. #define error(msg) errorFlash(F(msg))
  227. //------------------------------------------------------------------------------
  228. void errorFlash(const __FlashStringHelper* msg) {
  229. sd.errorPrint(msg);
  230. fatalBlink();
  231. }
  232. //------------------------------------------------------------------------------
  233. //
  234. void fatalBlink() {
  235. while (true) {
  236. if (ERROR_LED_PIN >= 0) {
  237. digitalWrite(ERROR_LED_PIN, HIGH);
  238. delay(200);
  239. digitalWrite(ERROR_LED_PIN, LOW);
  240. delay(200);
  241. }
  242. }
  243. }
  244. //==============================================================================
  245. #if ADPS0 != 0 || ADPS1 != 1 || ADPS2 != 2
  246. #error unexpected ADC prescaler bits
  247. #endif
  248. //------------------------------------------------------------------------------
  249. // initialize ADC and timer1
  250. void adcInit(metadata_t* meta) {
  251. uint8_t adps; // prescaler bits for ADCSRA
  252. uint32_t ticks = F_CPU*SAMPLE_INTERVAL + 0.5; // Sample interval cpu cycles.
  253. if (ADC_REF & ~((1 << REFS0) | (1 << REFS1))) {
  254. error("Invalid ADC reference");
  255. }
  256. #ifdef ADC_PRESCALER
  257. if (ADC_PRESCALER > 7 || ADC_PRESCALER < 2) {
  258. error("Invalid ADC prescaler");
  259. }
  260. adps = ADC_PRESCALER;
  261. #else // ADC_PRESCALER
  262. // Allow extra cpu cycles to change ADC settings if more than one pin.
  263. int32_t adcCycles = (ticks - ISR_TIMER0)/PIN_COUNT;
  264. - (PIN_COUNT > 1 ? ISR_SETUP_ADC : 0);
  265. for (adps = 7; adps > 0; adps--) {
  266. if (adcCycles >= (MIN_ADC_CYCLES << adps)) break;
  267. }
  268. #endif // ADC_PRESCALER
  269. meta->adcFrequency = F_CPU >> adps;
  270. if (meta->adcFrequency > (RECORD_EIGHT_BITS ? 2000000 : 1000000)) {
  271. error("Sample Rate Too High");
  272. }
  273. #if ROUND_SAMPLE_INTERVAL
  274. // Round so interval is multiple of ADC clock.
  275. ticks += 1 << (adps - 1);
  276. ticks >>= adps;
  277. ticks <<= adps;
  278. #endif // ROUND_SAMPLE_INTERVAL
  279. if (PIN_COUNT > sizeof(meta->pinNumber)/sizeof(meta->pinNumber[0])) {
  280. error("Too many pins");
  281. }
  282. meta->pinCount = PIN_COUNT;
  283. meta->recordEightBits = RECORD_EIGHT_BITS;
  284. for (int i = 0; i < PIN_COUNT; i++) {
  285. uint8_t pin = PIN_LIST[i];
  286. if (pin >= NUM_ANALOG_INPUTS) error("Invalid Analog pin number");
  287. meta->pinNumber[i] = pin;
  288. // Set ADC reference and low three bits of analog pin number.
  289. adcmux[i] = (pin & 7) | ADC_REF;
  290. if (RECORD_EIGHT_BITS) adcmux[i] |= 1 << ADLAR;
  291. // If this is the first pin, trigger on timer/counter 1 compare match B.
  292. adcsrb[i] = i == 0 ? (1 << ADTS2) | (1 << ADTS0) : 0;
  293. #ifdef MUX5
  294. if (pin > 7) adcsrb[i] |= (1 << MUX5);
  295. #endif // MUX5
  296. adcsra[i] = (1 << ADEN) | (1 << ADIE) | adps;
  297. adcsra[i] |= i == 0 ? 1 << ADATE : 1 << ADSC;
  298. }
  299. // Setup timer1
  300. TCCR1A = 0;
  301. uint8_t tshift;
  302. if (ticks < 0X10000) {
  303. // no prescale, CTC mode
  304. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10);
  305. tshift = 0;
  306. } else if (ticks < 0X10000*8) {
  307. // prescale 8, CTC mode
  308. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);
  309. tshift = 3;
  310. } else if (ticks < 0X10000*64) {
  311. // prescale 64, CTC mode
  312. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11) | (1 << CS10);
  313. tshift = 6;
  314. } else if (ticks < 0X10000*256) {
  315. // prescale 256, CTC mode
  316. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);
  317. tshift = 8;
  318. } else if (ticks < 0X10000*1024) {
  319. // prescale 1024, CTC mode
  320. TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (1 << CS10);
  321. tshift = 10;
  322. } else {
  323. error("Sample Rate Too Slow");
  324. }
  325. // divide by prescaler
  326. ticks >>= tshift;
  327. // set TOP for timer reset
  328. ICR1 = ticks - 1;
  329. // compare for ADC start
  330. OCR1B = 0;
  331. // multiply by prescaler
  332. ticks <<= tshift;
  333. // Sample interval in CPU clock ticks.
  334. meta->sampleInterval = ticks;
  335. meta->cpuFrequency = F_CPU;
  336. float sampleRate = (float)meta->cpuFrequency/meta->sampleInterval;
  337. Serial.print(F("Sample pins:"));
  338. for (int i = 0; i < meta->pinCount; i++) {
  339. Serial.print(' ');
  340. Serial.print(meta->pinNumber[i], DEC);
  341. }
  342. Serial.println();
  343. Serial.print(F("ADC bits: "));
  344. Serial.println(meta->recordEightBits ? 8 : 10);
  345. Serial.print(F("ADC clock kHz: "));
  346. Serial.println(meta->adcFrequency/1000);
  347. Serial.print(F("Sample Rate: "));
  348. Serial.println(sampleRate);
  349. Serial.print(F("Sample interval usec: "));
  350. Serial.println(1000000.0/sampleRate, 4);
  351. }
  352. //------------------------------------------------------------------------------
  353. // enable ADC and timer1 interrupts
  354. void adcStart() {
  355. // initialize ISR
  356. isrBufNeeded = true;
  357. isrOver = 0;
  358. adcindex = 1;
  359. // Clear any pending interrupt.
  360. ADCSRA |= 1 << ADIF;
  361. // Setup for first pin.
  362. ADMUX = adcmux[0];
  363. ADCSRB = adcsrb[0];
  364. ADCSRA = adcsra[0];
  365. // Enable timer1 interrupts.
  366. timerError = false;
  367. timerFlag = false;
  368. TCNT1 = 0;
  369. TIFR1 = 1 << OCF1B;
  370. TIMSK1 = 1 << OCIE1B;
  371. }
  372. //------------------------------------------------------------------------------
  373. void adcStop() {
  374. TIMSK1 = 0;
  375. ADCSRA = 0;
  376. }
  377. //------------------------------------------------------------------------------
  378. // Convert binary file to CSV file.
  379. void binaryToCsv() {
  380. uint8_t lastPct = 0;
  381. block_t buf;
  382. metadata_t* pm;
  383. uint32_t t0 = millis();
  384. char csvName[13];
  385. StdioStream csvStream;
  386. if (!binFile.isOpen()) {
  387. Serial.println(F("No current binary file"));
  388. return;
  389. }
  390. binFile.rewind();
  391. if (!binFile.read(&buf , 512) == 512) error("Read metadata failed");
  392. // Create a new CSV file.
  393. strcpy(csvName, binName);
  394. strcpy_P(&csvName[BASE_NAME_SIZE + 3], PSTR("CSV"));
  395. if (!csvStream.fopen(csvName, "w")) {
  396. error("open csvStream failed");
  397. }
  398. Serial.println();
  399. Serial.print(F("Writing: "));
  400. Serial.print(csvName);
  401. Serial.println(F(" - type any character to stop"));
  402. pm = (metadata_t*)&buf;
  403. csvStream.print(F("Interval,"));
  404. float intervalMicros = 1.0e6*pm->sampleInterval/(float)pm->cpuFrequency;
  405. csvStream.print(intervalMicros, 4);
  406. csvStream.println(F(",usec"));
  407. for (uint8_t i = 0; i < pm->pinCount; i++) {
  408. if (i) csvStream.putc(',');
  409. csvStream.print(F("pin"));
  410. csvStream.print(pm->pinNumber[i]);
  411. }
  412. csvStream.println();
  413. uint32_t tPct = millis();
  414. while (!Serial.available() && binFile.read(&buf, 512) == 512) {
  415. uint16_t i;
  416. if (buf.count == 0) break;
  417. if (buf.overrun) {
  418. csvStream.print(F("OVERRUN,"));
  419. csvStream.println(buf.overrun);
  420. }
  421. for (uint16_t j = 0; j < buf.count; j += PIN_COUNT) {
  422. for (uint16_t i = 0; i < PIN_COUNT; i++) {
  423. if (i) csvStream.putc(',');
  424. csvStream.print(buf.data[i + j]);
  425. }
  426. csvStream.println();
  427. }
  428. if ((millis() - tPct) > 1000) {
  429. uint8_t pct = binFile.curPosition()/(binFile.fileSize()/100);
  430. if (pct != lastPct) {
  431. tPct = millis();
  432. lastPct = pct;
  433. Serial.print(pct, DEC);
  434. Serial.println('%');
  435. }
  436. }
  437. if (Serial.available()) break;
  438. }
  439. csvStream.fclose();
  440. Serial.print(F("Done: "));
  441. Serial.print(0.001*(millis() - t0));
  442. Serial.println(F(" Seconds"));
  443. }
  444. //------------------------------------------------------------------------------
  445. // read data file and check for overruns
  446. void checkOverrun() {
  447. bool headerPrinted = false;
  448. block_t buf;
  449. uint32_t bgnBlock, endBlock;
  450. uint32_t bn = 0;
  451. if (!binFile.isOpen()) {
  452. Serial.println(F("No current binary file"));
  453. return;
  454. }
  455. if (!binFile.contiguousRange(&bgnBlock, &endBlock)) {
  456. error("contiguousRange failed");
  457. }
  458. binFile.rewind();
  459. Serial.println();
  460. Serial.println(F("Checking overrun errors - type any character to stop"));
  461. if (!binFile.read(&buf , 512) == 512) {
  462. error("Read metadata failed");
  463. }
  464. bn++;
  465. while (binFile.read(&buf, 512) == 512) {
  466. if (buf.count == 0) break;
  467. if (buf.overrun) {
  468. if (!headerPrinted) {
  469. Serial.println();
  470. Serial.println(F("Overruns:"));
  471. Serial.println(F("fileBlockNumber,sdBlockNumber,overrunCount"));
  472. headerPrinted = true;
  473. }
  474. Serial.print(bn);
  475. Serial.print(',');
  476. Serial.print(bgnBlock + bn);
  477. Serial.print(',');
  478. Serial.println(buf.overrun);
  479. }
  480. bn++;
  481. }
  482. if (!headerPrinted) {
  483. Serial.println(F("No errors found"));
  484. } else {
  485. Serial.println(F("Done"));
  486. }
  487. }
  488. //------------------------------------------------------------------------------
  489. // dump data file to Serial
  490. void dumpData() {
  491. block_t buf;
  492. if (!binFile.isOpen()) {
  493. Serial.println(F("No current binary file"));
  494. return;
  495. }
  496. binFile.rewind();
  497. if (binFile.read(&buf , 512) != 512) {
  498. error("Read metadata failed");
  499. }
  500. Serial.println();
  501. Serial.println(F("Type any character to stop"));
  502. delay(1000);
  503. while (!Serial.available() && binFile.read(&buf , 512) == 512) {
  504. if (buf.count == 0) break;
  505. if (buf.overrun) {
  506. Serial.print(F("OVERRUN,"));
  507. Serial.println(buf.overrun);
  508. }
  509. for (uint16_t i = 0; i < buf.count; i++) {
  510. Serial.print(buf.data[i], DEC);
  511. if ((i+1)%PIN_COUNT) {
  512. Serial.print(',');
  513. } else {
  514. Serial.println();
  515. }
  516. }
  517. }
  518. Serial.println(F("Done"));
  519. }
  520. //------------------------------------------------------------------------------
  521. // log data
  522. // max number of blocks to erase per erase call
  523. uint32_t const ERASE_SIZE = 262144L;
  524. void logData() {
  525. uint32_t bgnBlock, endBlock;
  526. // Allocate extra buffer space.
  527. block_t block[BUFFER_BLOCK_COUNT];
  528. Serial.println();
  529. // Initialize ADC and timer1.
  530. adcInit((metadata_t*) &block[0]);
  531. // Find unused file name.
  532. if (BASE_NAME_SIZE > 6) {
  533. error("FILE_BASE_NAME too long");
  534. }
  535. while (sd.exists(binName)) {
  536. if (binName[BASE_NAME_SIZE + 1] != '9') {
  537. binName[BASE_NAME_SIZE + 1]++;
  538. } else {
  539. binName[BASE_NAME_SIZE + 1] = '0';
  540. if (binName[BASE_NAME_SIZE] == '9') {
  541. error("Can't create file name");
  542. }
  543. binName[BASE_NAME_SIZE]++;
  544. }
  545. }
  546. // Delete old tmp file.
  547. if (sd.exists(TMP_FILE_NAME)) {
  548. Serial.println(F("Deleting tmp file"));
  549. if (!sd.remove(TMP_FILE_NAME)) {
  550. error("Can't remove tmp file");
  551. }
  552. }
  553. // Create new file.
  554. Serial.println(F("Creating new file"));
  555. binFile.close();
  556. if (!binFile.createContiguous(sd.vwd(),
  557. TMP_FILE_NAME, 512 * FILE_BLOCK_COUNT)) {
  558. error("createContiguous failed");
  559. }
  560. // Get the address of the file on the SD.
  561. if (!binFile.contiguousRange(&bgnBlock, &endBlock)) {
  562. error("contiguousRange failed");
  563. }
  564. // Use SdFat's internal buffer.
  565. uint8_t* cache = (uint8_t*)sd.vol()->cacheClear();
  566. if (cache == 0) error("cacheClear failed");
  567. // Flash erase all data in the file.
  568. Serial.println(F("Erasing all data"));
  569. uint32_t bgnErase = bgnBlock;
  570. uint32_t endErase;
  571. while (bgnErase < endBlock) {
  572. endErase = bgnErase + ERASE_SIZE;
  573. if (endErase > endBlock) endErase = endBlock;
  574. if (!sd.card()->erase(bgnErase, endErase)) {
  575. error("erase failed");
  576. }
  577. bgnErase = endErase + 1;
  578. }
  579. // Start a multiple block write.
  580. if (!sd.card()->writeStart(bgnBlock, FILE_BLOCK_COUNT)) {
  581. error("writeBegin failed");
  582. }
  583. // Write metadata.
  584. if (!sd.card()->writeData((uint8_t*)&block[0])) {
  585. error("Write metadata failed");
  586. }
  587. // Initialize queues.
  588. emptyHead = emptyTail = 0;
  589. fullHead = fullTail = 0;
  590. // Use SdFat buffer for one block.
  591. emptyQueue[emptyHead] = (block_t*)cache;
  592. emptyHead = queueNext(emptyHead);
  593. // Put rest of buffers in the empty queue.
  594. for (uint8_t i = 0; i < BUFFER_BLOCK_COUNT; i++) {
  595. emptyQueue[emptyHead] = &block[i];
  596. emptyHead = queueNext(emptyHead);
  597. }
  598. // Give SD time to prepare for big write.
  599. delay(1000);
  600. Serial.println(F("Logging - type any character to stop"));
  601. // Wait for Serial Idle.
  602. Serial.flush();
  603. delay(10);
  604. uint32_t bn = 1;
  605. uint32_t t0 = millis();
  606. uint32_t t1 = t0;
  607. uint32_t overruns = 0;
  608. uint32_t count = 0;
  609. uint32_t maxLatency = 0;
  610. // Start logging interrupts.
  611. adcStart();
  612. while (1) {
  613. if (fullHead != fullTail) {
  614. // Get address of block to write.
  615. block_t* pBlock = fullQueue[fullTail];
  616. // Write block to SD.
  617. uint32_t usec = micros();
  618. if (!sd.card()->writeData((uint8_t*)pBlock)) {
  619. error("write data failed");
  620. }
  621. usec = micros() - usec;
  622. t1 = millis();
  623. if (usec > maxLatency) maxLatency = usec;
  624. count += pBlock->count;
  625. // Add overruns and possibly light LED.
  626. if (pBlock->overrun) {
  627. overruns += pBlock->overrun;
  628. if (ERROR_LED_PIN >= 0) {
  629. digitalWrite(ERROR_LED_PIN, HIGH);
  630. }
  631. }
  632. // Move block to empty queue.
  633. emptyQueue[emptyHead] = pBlock;
  634. emptyHead = queueNext(emptyHead);
  635. fullTail = queueNext(fullTail);
  636. bn++;
  637. if (bn == FILE_BLOCK_COUNT) {
  638. // File full so stop ISR calls.
  639. adcStop();
  640. break;
  641. }
  642. }
  643. if (timerError) {
  644. error("Missed timer event - rate too high");
  645. }
  646. if (Serial.available()) {
  647. // Stop ISR calls.
  648. adcStop();
  649. if (isrBuf != 0 && isrBuf->count >= PIN_COUNT) {
  650. // Truncate to last complete sample.
  651. isrBuf->count = PIN_COUNT*(isrBuf->count/PIN_COUNT);
  652. // Put buffer in full queue.
  653. fullQueue[fullHead] = isrBuf;
  654. fullHead = queueNext(fullHead);
  655. isrBuf = 0;
  656. }
  657. if (fullHead == fullTail) break;
  658. }
  659. }
  660. if (!sd.card()->writeStop()) {
  661. error("writeStop failed");
  662. }
  663. // Truncate file if recording stopped early.
  664. if (bn != FILE_BLOCK_COUNT) {
  665. Serial.println(F("Truncating file"));
  666. if (!binFile.truncate(512L * bn)) {
  667. error("Can't truncate file");
  668. }
  669. }
  670. if (!binFile.rename(sd.vwd(), binName)) {
  671. error("Can't rename file");
  672. }
  673. Serial.print(F("File renamed: "));
  674. Serial.println(binName);
  675. Serial.print(F("Max block write usec: "));
  676. Serial.println(maxLatency);
  677. Serial.print(F("Record time sec: "));
  678. Serial.println(0.001*(t1 - t0), 3);
  679. Serial.print(F("Sample count: "));
  680. Serial.println(count/PIN_COUNT);
  681. Serial.print(F("Samples/sec: "));
  682. Serial.println((1000.0/PIN_COUNT)*count/(t1-t0));
  683. Serial.print(F("Overruns: "));
  684. Serial.println(overruns);
  685. Serial.println(F("Done"));
  686. }
  687. //------------------------------------------------------------------------------
  688. void setup(void) {
  689. if (ERROR_LED_PIN >= 0) {
  690. pinMode(ERROR_LED_PIN, OUTPUT);
  691. }
  692. Serial.begin(9600);
  693. // Read the first sample pin to init the ADC.
  694. analogRead(PIN_LIST[0]);
  695. Serial.print(F("FreeRam: "));
  696. Serial.println(FreeRam());
  697. // initialize file system.
  698. if (!sd.begin(SD_CS_PIN, SPI_FULL_SPEED)) {
  699. sd.initErrorPrint();
  700. fatalBlink();
  701. }
  702. }
  703. //------------------------------------------------------------------------------
  704. void loop(void) {
  705. // discard any input
  706. while (Serial.read() >= 0) {}
  707. Serial.println();
  708. Serial.println(F("type:"));
  709. Serial.println(F("c - convert file to CSV"));
  710. Serial.println(F("d - dump data to Serial"));
  711. Serial.println(F("e - overrun error details"));
  712. Serial.println(F("r - record ADC data"));
  713. while(!Serial.available()) {}
  714. char c = tolower(Serial.read());
  715. if (ERROR_LED_PIN >= 0) {
  716. digitalWrite(ERROR_LED_PIN, LOW);
  717. }
  718. // Read any extra Serial data.
  719. do {
  720. delay(10);
  721. } while (Serial.read() >= 0);
  722. if (c == 'c') {
  723. binaryToCsv();
  724. } else if (c == 'd') {
  725. dumpData();
  726. } else if (c == 'e') {
  727. checkOverrun();
  728. } else if (c == 'r') {
  729. logData();
  730. } else {
  731. Serial.println(F("Invalid entry"));
  732. }
  733. }
  734. #else // __AVR__
  735. #error This program is only for AVR.
  736. #endif // __AVR__