- Posts: 25
- Thank you received: 0
Please Log in or Create an account to join the conversation.
#include <MySensor.h>
#include <SPI.h>
#include <DHT.h>
#define CHILD_ID_HUM 0
#define CHILD_ID_TEMP 1
#define CHILD_ID_Relay 2
#define HUMIDITY_SENSOR_DIGITAL_PIN 3
#define RELAY_1 4 // Arduino Digital I/O pin number for relay Pin D4
#define NUMBER_OF_RELAYS 1 // Total number of attached relays
#define RELAY_ON 1 // GPIO value to write to turn on attached relay
#define RELAY_OFF 0 // GPIO value to write to turn off attached relay
DHT dht;
float lastTemp;
float lastHum;
boolean metric = true;
MyMessage msgHum(CHILD_ID_HUM, V_HUM);
MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
MySensor gw;
void setup()
{
// Initialize library and add callback for incoming messages
gw.begin(incomingMessage, AUTO, true);
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Relay and Temp and Humi", "1.0");
dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN);
// Send the Sketch Version Information to the Gateway
// Register all sensors to gw (they will be created as child devices)
gw.present(CHILD_ID_Relay, S_LIGHT);
gw.present(CHILD_ID_HUM, S_HUM);
gw.present(CHILD_ID_TEMP, S_TEMP);
metric = gw.getConfig().isMetric;
// Then set relay pins in output mode
pinMode(RELAY_1, OUTPUT);
// Set relay to last known state (using eeprom storage)
digitalWrite(RELAY_1, gw.loadState(CHILD_ID_Relay)?RELAY_ON:RELAY_OFF);
}
void loop()
{
// Alway process incoming messages whenever possible
gw.process();
delay(dht.getMinimumSamplingPeriod());
// Alway process incoming messages whenever possible
gw.process();
float temperature = dht.getTemperature();
if (isnan(temperature)) {
Serial.println("Failed reading temperature from DHT");
}
else if (temperature != lastTemp) {
lastTemp = temperature;
if (!metric) {
temperature = dht.toFahrenheit(temperature);
}
gw.send(msgTemp.set(temperature, 1));
Serial.print("T: ");
Serial.println(temperature);
}
float humidity = dht.getHumidity();
if (isnan(humidity)) {
Serial.println("Failed reading humidity from DHT");
}
else if (humidity != lastHum) {
lastHum = humidity;
gw.send(msgHum.set(humidity, 1));
Serial.print("H: ");
Serial.println(humidity);
}
}
void incomingMessage(const MyMessage &message) {
// We only expect one type of message from controller. But we better check anyway.
if (message.type==V_LIGHT) {
// Change relay state
digitalWrite(message.sensor-CHILD_ID_Relay+RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF);
// Store state in eeprom
gw.saveState(message.sensor, message.getBool());
// Write some debug info
Serial.print("Incoming change for sensor:");
Serial.print(message.sensor);
Serial.print(", New status: ");
Serial.println(message.getBool());
}
}
Please Log in or Create an account to join the conversation.
Please Log in or Create an account to join the conversation.