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.

average.ino 1.9KB

10 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
10 jaren geleden
8 jaren geleden
10 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // Wait for USB Serial
  49. while (!Serial) {
  50. SysCall::yield();
  51. }
  52. // F() stores strings in flash to save RAM
  53. cout << F("Type any character to start\n");
  54. while (!Serial.available()) {
  55. SysCall::yield();
  56. }
  57. // Initialize at the highest speed supported by the board that is
  58. // not over 50 MHz. Try a lower speed if SPI errors occur.
  59. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
  60. sd.initErrorHalt();
  61. }
  62. // write the test file
  63. writeTestFile();
  64. // read the test file and calculate the average
  65. calcAverage();
  66. }
  67. //------------------------------------------------------------------------------
  68. void loop() {}