You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.9KB

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