From 130d2a7f77f6b2ed61e0c22d2adbb352d785504d Mon Sep 17 00:00:00 2001 From: Ronald Schaten Date: Sun, 20 Mar 2016 15:18:12 +0100 Subject: [PATCH] support Witty Wifi module, set rgb led via MQTT --- things.ino | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/things.ino b/things.ino index 69aa5b1..5d1e856 100644 --- a/things.ino +++ b/things.ino @@ -21,6 +21,12 @@ extern "C" { #define CONFIGPIN D3 // config-button is connected to this pin +#define RGBRED D8 // red led channel on witty module +#define RGBGRN D6 // green led channel on witty module +#define RGBBLU D7 // blue led channel on witty module + +#define LDRPIN A0 // analog LDR input on witty module + // define default values here, overwritten by values from config.json char mqtt_server[40]; char mqtt_port[6] = "1883"; @@ -129,22 +135,21 @@ void read_sensor() { // callback for MQTT, gets called if we receive a message void mqtt_callback(char* topic, byte* payload, unsigned int length) { + char inData[length+1]; + for(int i = 0; i < length; i++) { + inData[i] = (char)payload[i]; + } + inData[length] = 0; Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); - for (int i = 0; i < length; i++) { - Serial.print((char)payload[i]); - } - Serial.println(); + Serial.println(inData); - // switch on the LED if an 1 was received as first character - if ((char)payload[0] == '1') { - Serial.println("setting LED to low"); - digitalWrite(BUILTIN_LED, LOW); // turn the LED on - } else { - Serial.println("setting LED to high"); - digitalWrite(BUILTIN_LED, HIGH); // turn the LED off - } + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.parseObject(inData); + analogWrite(RGBRED, json["red"]); + analogWrite(RGBGRN, json["green"]); + analogWrite(RGBBLU, json["blue"]); } // make sure we're connected to MQTT broker @@ -158,7 +163,7 @@ void mqtt_reconnect() { // once connected, publish an announcement... mqtt_client.publish(topic("online"), "1", true); // ... and resubscribe: - mqtt_client.subscribe("inTopic"); + mqtt_client.subscribe("setrgb"); } else { Serial.print("failed, rc="); Serial.print(mqtt_client.state()); @@ -188,7 +193,12 @@ void setup() { pinMode(BUILTIN_LED, OUTPUT); // set led pin as output ticker.attach(0.5, toggle_led); // toggle led slowly during initialization + pinMode(RGBRED, OUTPUT); + pinMode(RGBGRN, OUTPUT); + pinMode(RGBBLU, OUTPUT); + pinMode(CONFIGPIN, INPUT); // flash-button on nodemcu + pinMode(LDRPIN, INPUT); // clean FS, for testing //SPIFFS.format();