WaitForConversion2.ino 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // Sample of using Async reading of Dallas Temperature Sensors
  3. //
  4. #include <OneWire.h>
  5. #include <DallasTemperature.h>
  6. // Data wire is plugged into port 2 on the Arduino
  7. #define ONE_WIRE_BUS 2
  8. // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  9. OneWire oneWire(ONE_WIRE_BUS);
  10. // Pass our oneWire reference to Dallas Temperature.
  11. DallasTemperature sensors(&oneWire);
  12. DeviceAddress tempDeviceAddress;
  13. int resolution = 12;
  14. unsigned long lastTempRequest = 0;
  15. int delayInMillis = 0;
  16. float temperature = 0.0;
  17. int idle = 0;
  18. //
  19. // SETUP
  20. //
  21. void setup(void)
  22. {
  23. Serial.begin(115200);
  24. Serial.println("Dallas Temperature Control Library - Async Demo");
  25. Serial.print("Library Version: ");
  26. Serial.println(DALLASTEMPLIBVERSION);
  27. Serial.println("\n");
  28. sensors.begin();
  29. sensors.getAddress(tempDeviceAddress, 0);
  30. sensors.setResolution(tempDeviceAddress, resolution);
  31. sensors.setWaitForConversion(false);
  32. sensors.requestTemperatures();
  33. delayInMillis = 750 / (1 << (12 - resolution));
  34. lastTempRequest = millis();
  35. pinMode(13, OUTPUT);
  36. }
  37. void loop(void)
  38. {
  39. if (millis() - lastTempRequest >= delayInMillis) // waited long enough??
  40. {
  41. digitalWrite(13, LOW);
  42. Serial.print(" Temperature: ");
  43. temperature = sensors.getTempCByIndex(0);
  44. Serial.println(temperature, resolution - 8);
  45. Serial.print(" Resolution: ");
  46. Serial.println(resolution);
  47. Serial.print("Idle counter: ");
  48. Serial.println(idle);
  49. Serial.println();
  50. idle = 0;
  51. // immediately after fetching the temperature we request a new sample
  52. // in the async modus
  53. // for the demo we let the resolution change to show differences
  54. resolution++;
  55. if (resolution > 12) resolution = 9;
  56. sensors.setResolution(tempDeviceAddress, resolution);
  57. sensors.requestTemperatures();
  58. delayInMillis = 750 / (1 << (12 - resolution));
  59. lastTempRequest = millis();
  60. }
  61. digitalWrite(13, HIGH);
  62. // we can do usefull things here
  63. // for the demo we just count the idle time in millis
  64. delay(1);
  65. idle++;
  66. }