Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

average.ino 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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("AVG_TEST.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) sd.errorHalt("sdout failed");
  21. sdout.close();
  22. }
  23. //------------------------------------------------------------------------------
  24. void calcAverage() {
  25. uint16_t n = 0; // count of input numbers
  26. double num; // current input number
  27. double sum = 0; // sum of input numbers
  28. // open the input file
  29. ifstream sdin("AVG_TEST.TXT");
  30. // check for an open failure
  31. if (!sdin) sd.errorHalt("sdin failed");
  32. // read and sum the numbers
  33. while (sdin >> num) {
  34. n++;
  35. sum += num;
  36. }
  37. // print the results
  38. cout << "sum of " << n << " numbers = " << sum << endl;
  39. cout << "average = " << sum/n << endl;
  40. }
  41. //------------------------------------------------------------------------------
  42. void setup() {
  43. Serial.begin(9600);
  44. while (!Serial) {} // wait for Leonardo
  45. // pstr stores strings in flash to save RAM
  46. cout << pstr("Type any character to start\n");
  47. while (Serial.read() <= 0) {}
  48. delay(400); // Catch Due reset problem
  49. // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  50. // breadboards. use SPI_FULL_SPEED for better performance.
  51. if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();
  52. // write the test file
  53. writeTestFile();
  54. // read the test file and calculate the average
  55. calcAverage();
  56. }
  57. //------------------------------------------------------------------------------
  58. void loop() {}