いろんなセンサでMQTT
以下の、DHT11とHC-SR501と感光性センサーを使いました。
全部買っても、500円しませんでした。
コード
DHT11はArduino向けのDHTライブラリを使って対応。HC-SR501は、デジタルで出力されるので、ピンを読むだけ、感光性センサーもアナログ値のPINを読むだけなので、なんてことない処理ですが、参考までに、以下がコードです。なお、どのセンサーも読むだけなので、Settableはfalseです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
#include "DHTesp.h" #include <LeifESPBaseHomie.h> // *** Don't forget to add your MQTT credentials to LeifESPBaseHomie\environment_setup.h. See environment_setup.h.example for details. *** // *** Don't forget to add your WiFi SSID/Key to LeifESPBase\environment_setup.h See environment_setup.h.example for details. *** //The code keeps track of whether it's running on a production unit //(let's say inside a ceiling-mounted box, inconvenient to get to) //or a development board on your bench, by way of checking the MAC address. //This reduces confusion while bench-testing new code before OTA upload to the production unit. //The bDeployedUnit flag is set at the beginning of the setup() function below. bool bDeployedUnit = false; const char *GetHostName() //this host name will reported to for example mDNS, telnet { if (bDeployedUnit) { return "sensor@room"; } return "sensor@roomdev"; } const char *GetHeadingText() //friendly system name, used for example for the HTTP page { if (bDeployedUnit) { return "sensor@room"; } else { return "sensor@roomdev"; } } // We'll need a place to save pointers to our created properties so that we can access them after creation. // HomieProperty * pPropLedInvert=NULL; // HomieProperty * pPropQuote=NULL; // HomieProperty * pPropColor=NULL; // HomieProperty * pPropBacklight=NULL; // HomieProperty * pPropSpeed=NULL; HomieProperty *pPropTemperature = NULL; HomieProperty *pPropHumidity = NULL; HomieProperty *pPropBrightness = NULL; HomieProperty *pPropHumanDetection = NULL; DHTesp dht; //this function will be called by all the URL handlers. //I truly suck at webdesign. You can do better. void genHtmlPage(String &output, const String &strInsert) { output.reserve(2048); output.concat("<!DOCTYPE html>"); output.concat("<html><head><style>table, th, td { border: 1px solid black; border-collapse: collapse;}th, td { padding: 5px;}</style></head>"); output.concat("<body>"); output.concat("<h2>"); output.concat(GetHeadingText()); output.concat("</h2>"); LeifHtmlMainPageCommonHeader(output); output.concat("<table><tr>"); output.concat("<td><a href=\"/\">Reload</a></td>"); output.concat("<td><a href=\"/ping\">Minimal test page</a></td>"); output.concat("<td><a href=\"/sysinfo\">System Info</a></td>"); output.concat("<td><a href=\"/invert\">Invert status LED</a></td>"); output.concat("</tr></table>"); output.concat(strInsert); output.concat("</body></html>"); } void handleRoot() { String strInsert; String strPage; genHtmlPage(strPage, strInsert); server.send(200, "text/html", strPage); } void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void setup() { //MAC address of your deployed (production) unit if (WiFi.macAddress() == "XX:XX:XX:XX:XX:XX") bDeployedUnit = true; //The LED is used for status indication. Flashes twice a second while connecting WiFi. //Flashes once every two seconds when connected. //By default, LED_BUILTIN is used for status output. 2 Hz flashing while connecting to WiFi, 0.5 Hz when connected. //You can use any pin by calling the LedSetStatusLedPin(x) function like below. -1 disables output altogether. //LeifSetStatusLedPin(-1); //No status LED output //LeifSetStatusLedPin(1); //ESP-01 on-board LED. This is actually the serial port so it will disable serial console output! LeifSetupBegin(); //starts initialization of the HTTP server and other objects. //Set your serial console to 115200 bps to see console output. The console will print the IP address and many other things. //Once you know the IP address you can connect to port 23 with a telnet client like PuTTY to see console output. //You'll need to enable the "Implicit CR option in every LF" on the Terminal Page in PuTTY. LeifUpdateCompileTime(); //Macro to capture __DATE__ and __TIME__ while compiling main sketch. //This way compile time as displayed by the main HTTP page will accurately reflect //sketch compile time, as opposed to library LeifESPBase compile time. server.onNotFound(handleNotFound); //serve 404 server.on("/", handleRoot); //serve root page, defined above. //define your own URL handlers here. // server.on("/invert", handleInvert); //invert the LED flashing pattern. LeifHomieSetupDefaults(); { HomieNode *pNode = homie.NewNode(); //We don't really need a hierarchy, but we must have at least one node -- so I'm going to call it properties. pNode->strID = "properties"; pNode->strFriendlyName = "Properties"; HomieProperty *pProp = NULL; // This parameter is fully functional. It controls whether the status LED is normally on or normally off. // It publishes its initial state (normally on = false) if there's no retained value, otherwise it uses the retained value. p // temperature/humidity sensor pPropTemperature = pProp = pNode->NewProperty(); pProp->strFriendlyName = "Temperature"; pProp->strID = "temperature"; pProp->strUnit = "degree"; pProp->bRetained = true; pProp->bSettable = false; pProp->datatype = homieFloat; pProp->SetValue("21.0"); // default value? // pProp->AddCallback([](HomieProperty * pSource) // { //this lambda function gets called when we receive a message on this property's topic. // // LeifSetInvertLedBlink(pSource->GetValue()=="true"); //controls whether the LED is normally off or normally on. // }); pPropHumidity = pProp = pNode->NewProperty(); pProp->strFriendlyName = "Humidity"; pProp->strID = "humidity"; pProp->strUnit = "%"; pProp->bRetained = true; pProp->bSettable = false; pProp->datatype = homieFloat; pProp->SetValue("50.0"); // default value? // pProp->AddCallback([](HomieProperty * pSource) // { //this lambda function gets called when we receive a message on this property's topic. // // LeifSetInvertLedBlink(pSource->GetValue()=="true"); //controls whether the LED is normally off or normally on. // }); pPropBrightness = pProp = pNode->NewProperty(); pProp->strFriendlyName = "Brightness"; pProp->strID = "brightness"; pProp->strUnit = ""; pProp->bRetained = true; pProp->bSettable = false; pProp->datatype = homieInt; pProp->SetValue("50"); // default value? // pProp->AddCallback([](HomieProperty * pSource) // { //this lambda function gets called when we receive a message on this property's topic. // // LeifSetInvertLedBlink(pSource->GetValue()=="true"); //controls whether the LED is normally off or normally on. // }); pPropHumanDetection = pProp = pNode->NewProperty(); pProp->strFriendlyName = "HumanDetection"; pProp->strID = "humandetection"; pProp->strUnit = ""; pProp->bRetained = true; pProp->bSettable = false; pProp->datatype = homieBool; pProp->SetBool(true); // default value? // pProp->AddCallback([](HomieProperty * pSource) // { //this lambda function gets called when we receive a message on this property's topic. // // LeifSetInvertLedBlink(pSource->GetValue()=="true"); //controls whether the LED is normally off or normally on. // }); // pProp->datatype=homieEnum; // pProp->strFormat="OFF,LOW,MEDIUM,HIGH"; // pProp->datatype=homieString; // pProp->bPublishEmptyString=false; // pProp->strFormat="0:1"; // pProp->SetValue("0.5"); //default value } homie.Init(); LeifSetupEnd(); //finishes initialization of the HTTP server and other objects // setup DHT11 dht.setup(16, DHTesp::DHT11); // Connect DHT sensor to GPIO 16 pinMode(5, INPUT); } void updateSensorValues() { char tempChar[10]; char humidChar[10]; char brightChar[10]; delay(dht.getMinimumSamplingPeriod()); float temperature = dht.getTemperature(); sprintf(tempChar, "%4.1f", temperature); pPropTemperature->SetValue(tempChar); float humidity = dht.getHumidity(); sprintf(humidChar, "%5.1f", humidity); pPropHumidity->SetValue(humidChar); Serial.print(dht.getStatusString()); Serial.print("\t"); Serial.print(humidity, 1); Serial.print("\t\t"); Serial.print(temperature, 1); Serial.println("."); int value = analogRead(A0); sprintf(brightChar, "%3d", value); pPropBrightness->SetValue(brightChar); Serial.print("Light Sensor : "); Serial.println(value); bool bValue = digitalRead(5); pPropHumanDetection->SetBool(bValue); Serial.print("Human Sensor : "); Serial.println(bValue); Serial.println("updated with using sensor value"); return; } void loop() { LeifLoop(); homie.Loop(); //Automatically reboot if we're unable to ping the gateway for 5 minutes. ESP8266 only for now! //LeifGatewayKeepalive(); //uncomment if desired if (Interval100()) { //True once every 100ms. Just for convenience. } if (Interval250()) { //True once every 250ms. Just for convenience. } if (Interval1000()) { //True once every second. Just for convenience. } if (Interval10s()) { // update temperature/humidity/brightness/human //True once every second. Just for convenience. updateSensorValues(); } if (Interval1000() && (seconds() % 60) == 0) //once a minute { String strUptime; LeifUptimeString(strUptime); String strUptimeWiFi; LeifSecondsToUptimeString(strUptimeWiFi, homie.GetUptimeSeconds_WiFi()); String strUptimeMQTT; LeifSecondsToUptimeString(strUptimeMQTT, homie.GetUptimeSeconds_MQTT()); //print a status message to the serial console and the telnet console. //you can disable the serial console by compiling with NO_SERIAL_DEBUG csprintf("Uptime=%s WiFi=%s MQTT=%s HeapFree=%u WiFi: %i\n", strUptime.c_str(), strUptimeWiFi.c_str(), strUptimeMQTT.c_str(), ESP.getFreeHeap(), WiFi.RSSI()); //publish something outside of the homie tree, too if (homie.IsConnected()) { String strTopic; strTopic = "mcu/"; strTopic += GetHostName(); strTopic += "/uptime"; homie.PublishDirect(strTopic, 2, false, strUptime); } } } |
Sponsor Link