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 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
8 vuotta sitten
10 vuotta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Calculate the sum and average of a list of floating point numbers
  3. */
  4. #include <SPI.h>
  5. #include "SdFat.h"
  6. #include "sdios.h"
  7. // SD chip select pin
  8. const uint8_t chipSelect = SS;
  9. // object for the SD file system
  10. SdFat sd;
  11. // define a serial output stream
  12. ArduinoOutStream cout(Serial);
  13. //------------------------------------------------------------------------------
  14. void writeTestFile() {
  15. // open the output file
  16. ofstream sdout("AvgTest.txt");
  17. // write a series of float numbers
  18. for (int16_t i = -1001; i < 2000; i += 13) {
  19. sdout << 0.1 * i << endl;
  20. }
  21. if (!sdout) {
  22. sd.errorHalt("sdout failed");
  23. }
  24. sdout.close();
  25. }
  26. //------------------------------------------------------------------------------
  27. void calcAverage() {
  28. uint16_t n = 0; // count of input numbers
  29. double num; // current input number
  30. double sum = 0; // sum of input numbers
  31. // open the input file
  32. ifstream sdin("AvgTest.txt");
  33. // check for an open failure
  34. if (!sdin) {
  35. sd.errorHalt("sdin failed");
  36. }
  37. // read and sum the numbers
  38. while (sdin >> num) {
  39. n++;
  40. sum += num;
  41. }
  42. // print the results
  43. cout << "sum of " << n << " numbers = " << sum << endl;
  44. cout << "average = " << sum/n << endl;
  45. }
  46. //------------------------------------------------------------------------------
  47. void setup() {
  48. Serial.begin(9600);
  49. // Wait for USB Serial
  50. while (!Serial) {
  51. SysCall::yield();
  52. }
  53. // F() stores strings in flash to save RAM
  54. cout << F("Type any character to start\n");
  55. while (!Serial.available()) {
  56. SysCall::yield();
  57. }
  58. // Initialize at the highest speed supported by the board that is
  59. // not over 50 MHz. Try a lower speed if SPI errors occur.
  60. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
  61. sd.initErrorHalt();
  62. }
  63. // write the test file
  64. writeTestFile();
  65. // read the test file and calculate the average
  66. calcAverage();
  67. }
  68. //------------------------------------------------------------------------------
  69. void loop() {}