Last active
November 11, 2020 11:07
-
-
Save tkurki/d8d45dfb368b3b544542511e8e95a45b to your computer and use it in GitHub Desktop.
ESP8266 script to read DS18B20 sensors over 1W and broadcast Signal K JSON over udp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <OneWire.h> | |
#include <DallasTemperature.h> | |
#include <ESP8266WiFi.h> | |
#include <WiFiUdp.h> | |
#include <SPI.h> | |
#include <Wire.h> | |
#include <ESP8266WebServer.h> | |
#include <DNSServer.h> | |
#include <WifiServer.h> | |
WiFiUDP g_udp; | |
IPAddress broadcast; | |
WiFiServer server(80); | |
const int g_port = 8888; | |
#define ONE_WIRE_BUS D4 | |
OneWire oneWire(ONE_WIRE_BUS); | |
DallasTemperature sensors(&oneWire); | |
uint8_t count = 0; | |
void printAddress(DeviceAddress deviceAddress) { | |
for (uint8_t i = 0; i < 8; i++) | |
{ | |
if (deviceAddress[i] < 16) Serial.print("0"); | |
Serial.print(deviceAddress[i], HEX); | |
} | |
Serial.print(":"); | |
} | |
void setup(void) | |
{ | |
Serial.begin(9600); | |
Serial.println("Startup"); | |
WiFi.begin("XXX", "YYY"); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println("Connected..."); | |
Serial.println(WiFi.localIP()); | |
server.begin(); | |
Serial.println("Server started"); | |
broadcast = WiFi.localIP(); | |
//hardcoded broadcast address | |
broadcast[3] = 255; | |
Serial.println(broadcast); | |
g_udp.beginMulticast(WiFi.localIP(), broadcast, g_port); | |
} | |
void sendUdp(DeviceAddress deviceAddress, float value) { | |
printAddress(deviceAddress); | |
Serial.println(value); | |
g_udp.beginPacketMulticast(broadcast, g_port, WiFi.localIP()); | |
g_udp.print("{\"updates\":[{\"$source\":\"1w."); | |
for (uint8_t i = 0; i < 8; i++) | |
{ | |
if (deviceAddress[i] < 16) Serial.print("0"); | |
g_udp.print(deviceAddress[i], HEX); | |
} | |
g_udp.print(",\"values\":[{\"path\":\"temperature\",\"value\":"); | |
g_udp.print(value); | |
g_udp.print("}]}]}"); | |
g_udp.write("\n"); | |
Serial.println(g_udp.endPacket()); | |
yield(); | |
} | |
void loop(void) | |
{ | |
sensors.begin(); | |
int numberOfDevices = 0; | |
numberOfDevices = sensors.getDeviceCount(); | |
Serial.print(numberOfDevices, DEC); | |
Serial.println(" devices"); | |
sensors.requestTemperatures(); | |
DeviceAddress tempDeviceAddress; | |
for(int i=0;i<numberOfDevices; i++) { | |
if(sensors.getAddress(tempDeviceAddress, i)) | |
{ | |
float tempC = sensors.getTempC(tempDeviceAddress); | |
sendUdp(tempDeviceAddress, tempC); | |
} | |
} | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment