ESP8266でいろんなセンサー

     

TAGS:

⌛️ 4 min.

いろんなセンサでMQTT

以下の、DHT11とHC-SR501と感光性センサーを使いました。

全部買っても、500円しませんでした。

コード

DHT11はArduino向けのDHTライブラリを使って対応。HC-SR501は、デジタルで出力されるので、ピンを読むだけ、感光性センサーもアナログ値のPINを読むだけなので、なんてことない処理ですが、参考までに、以下がコードです。なお、どのセンサーも読むだけなので、Settableはfalseです。

#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);
		}
	}

}

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です