UserDataDemo.ino 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. //
  2. // FILE: UserDataDemo.ino
  3. // AUTHOR: Rob Tillaart
  4. // VERSION: 0.1.0
  5. // PURPOSE: use of alarm field as user identification demo
  6. // DATE: 2019-12-23
  7. // URL:
  8. //
  9. // Released to the public domain
  10. //
  11. #include <OneWire.h>
  12. #include <DallasTemperature.h>
  13. #define ONE_WIRE_BUS 2
  14. OneWire oneWire(ONE_WIRE_BUS);
  15. DallasTemperature sensors(&oneWire);
  16. uint8_t deviceCount = 0;
  17. // Add 4 prepared sensors to the bus
  18. // use the UserDataWriteBatch demo to prepare 4 different labeled sensors
  19. struct
  20. {
  21. int id;
  22. DeviceAddress addr;
  23. } T[4];
  24. float getTempByID(int id)
  25. {
  26. for (uint8_t index = 0; index < deviceCount; index++)
  27. {
  28. if (T[index].id == id)
  29. {
  30. return sensors.getTempC(T[index].addr);
  31. }
  32. }
  33. return -999;
  34. }
  35. void printAddress(DeviceAddress deviceAddress)
  36. {
  37. for (uint8_t i = 0; i < 8; i++)
  38. {
  39. // zero pad the address if necessary
  40. if (deviceAddress[i] < 16) Serial.print("0");
  41. Serial.print(deviceAddress[i], HEX);
  42. }
  43. }
  44. void setup(void)
  45. {
  46. Serial.begin(115200);
  47. Serial.println(__FILE__);
  48. Serial.println("Dallas Temperature Demo");
  49. sensors.begin();
  50. // count devices
  51. deviceCount = sensors.getDeviceCount();
  52. Serial.print("#devices: ");
  53. Serial.println(deviceCount);
  54. // Read ID's per sensor
  55. // and put them in T array
  56. for (uint8_t index = 0; index < deviceCount; index++)
  57. {
  58. // go through sensors
  59. sensors.getAddress(T[index].addr, index);
  60. T[index].id = sensors.getUserData(T[index].addr);
  61. }
  62. // Check all 4 sensors are set
  63. for (uint8_t index = 0; index < deviceCount; index++)
  64. {
  65. Serial.println();
  66. Serial.println(T[index].id);
  67. printAddress(T[index].addr);
  68. Serial.println();
  69. }
  70. Serial.println();
  71. }
  72. void loop(void)
  73. {
  74. Serial.println();
  75. Serial.print(millis());
  76. Serial.println("\treq temp");
  77. sensors.requestTemperatures();
  78. Serial.print(millis());
  79. Serial.println("\tGet temp by address");
  80. for (int i = 0; i < 4; i++)
  81. {
  82. Serial.print(millis());
  83. Serial.print("\t temp:\t");
  84. Serial.println(sensors.getTempC(T[i].addr));
  85. }
  86. Serial.print(millis());
  87. Serial.println("\tGet temp by ID"); // assume ID = 0, 1, 2, 3
  88. for (int id = 0; id < 4; id++)
  89. {
  90. Serial.print(millis());
  91. Serial.print("\t temp:\t");
  92. Serial.println(getTempByID(id));
  93. }
  94. delay(1000);
  95. }
  96. // END OF FILE