DS18B20.ino 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <ESP8266WiFi.h>
  2. #include <ESP8266mDNS.h>
  3. #include <ESP8266WebServer.h>
  4. #include <OneWire.h>
  5. #include <DallasTemperature.h>
  6. #define ONE_WIRE_BUS 2
  7. const char* type = "temperature";
  8. const char* location = "xxx";
  9. const char* ssid = "xxx"; // Your ssid
  10. const char* password = "xxx"; // Your Password
  11. OneWire oneWire(ONE_WIRE_BUS);
  12. DallasTemperature sensors(&oneWire);
  13. ESP8266WebServer server(80);
  14. void setup() {
  15. // Connect to WiFi network
  16. WiFi.begin(ssid, password);
  17. while (WiFi.status() != WL_CONNECTED) {
  18. delay(500);
  19. }
  20. MDNS.begin((String)"sensor-" + type + "-" + location);
  21. sensors.begin();
  22. // Start the server
  23. server.on("/temperature/celcius", [](){
  24. server.send(200, "application/json", getCelcius());
  25. });
  26. server.begin();
  27. }
  28. String getCelcius() {
  29. //get the temperature in celcius
  30. sensors.requestTemperatures();
  31. float temp = sensors.getTempCByIndex(0);
  32. return "{\"temperature\":" + String(temp) + ", \"location\": \"" + location + "\", \"type\":\"" + type + "\"}";
  33. }
  34. void loop(){
  35. server.handleClient();
  36. }