Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Calculate the sum and average of a list of floating point numbers
  3. */
  4. #include <SdFat.h>
  5. // SD chip select pin
  6. const uint8_t chipSelect = SS;
  7. // object for the SD file system
  8. SdFat sd;
  9. // define a serial output stream
  10. ArduinoOutStream cout(Serial);
  11. //------------------------------------------------------------------------------
  12. void writeTestFile() {
  13. // open the output file
  14. ofstream sdout("AVG_TEST.TXT");
  15. // write a series of float numbers
  16. for (int16_t i = -1001; i < 2000; i += 13) {
  17. sdout << 0.1 * i << endl;
  18. }
  19. if (!sdout) sd.errorHalt("sdout failed");
  20. sdout.close();
  21. }
  22. //------------------------------------------------------------------------------
  23. void calcAverage() {
  24. uint16_t n = 0; // count of input numbers
  25. double num; // current input number
  26. double sum = 0; // sum of input numbers
  27. // open the input file
  28. ifstream sdin("AVG_TEST.TXT");
  29. // check for an open failure
  30. if (!sdin) sd.errorHalt("sdin failed");
  31. // read and sum the numbers
  32. while (sdin >> num) {
  33. n++;
  34. sum += num;
  35. }
  36. // print the results
  37. cout << "sum of " << n << " numbers = " << sum << endl;
  38. cout << "average = " << sum/n << endl;
  39. }
  40. //------------------------------------------------------------------------------
  41. void setup() {
  42. Serial.begin(9600);
  43. while (!Serial) {} // wait for Leonardo
  44. // pstr stores strings in flash to save RAM
  45. cout << pstr("Type any character to start\n");
  46. while (Serial.read() <= 0) {}
  47. delay(400); // Catch Due reset problem
  48. // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  49. // breadboards. use SPI_FULL_SPEED for better performance.
  50. if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();
  51. // write the test file
  52. writeTestFile();
  53. // read the test file and calculate the average
  54. calcAverage();
  55. }
  56. //------------------------------------------------------------------------------
  57. void loop() {}