Skip to content

Instantly share code, notes, and snippets.

@benwwchen
Created November 8, 2016 17:11
Show Gist options
  • Save benwwchen/82b7967b20b8261cf6b0aa35f46c152b to your computer and use it in GitHub Desktop.
Save benwwchen/82b7967b20b8261cf6b0aa35f46c152b to your computer and use it in GitHub Desktop.
NodeMCU Arduino Wi-Fi LED Strip and DHT Sensor
#include <ESP8266WiFi.h>
#include <MQTTClient.h>
#include <Adafruit_NeoPixel.h>
#include <DHT.h>
#define STRIP_PIN 4
#define DHT_TYPE DHT11 // DHT11 or DHT22
#define DHT_PIN 2
// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, STRIP_PIN, NEO_GRB + NEO_KHZ800);
const char* ssid = "IoT";
const char* password = "123456";
const char* lightTopic = "homekit/light"; // the name of your fixture, and the base channel to listen to
const char* sensorTopic = "homekit/sensor";
const char* server = "192.168.1.1"; // your MQTT server host
String clientName = "dormNodeMCU";
/**************************************************************/
/* NO NEED TO CHANGE BENEATH THIS LINE */
WiFiClient wifiClient;
MQTTClient client;
/* DHT */
unsigned long prevTimeReadSensor;
DHT dht(DHT_PIN, DHT_TYPE,11);
float h, t;
long interval = 30000; //(ms) - 30 seconds between reports
unsigned long resetPeriod = 86400000; // 1 day - this is the period after which we restart the CPU, to deal with odd memory leak errors
void DHTLoop() {
if(prevTimeReadSensor + interval < millis()){
prevTimeReadSensor = millis();
Serial.println("checking again");
h = dht.readHumidity();
t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
}
else if(!client.connected()){
Serial.println("Connection to broker lost; retrying");
}
else{
Serial.println(t);
Serial.println(h);
Serial.println(String(t,0));
Serial.println(String(h,0));
client.publish(sensorTopic + (String)"/temperature", String(t,0));
client.publish(sensorTopic + (String)"/humidity", String(h,0));
Serial.println("published environmental data");
}
}
// reset after a day to avoid memory leaks
if(millis()>resetPeriod){
ESP.restart();
}
}
/* Light */
int hue = 0;
float brightness = 0.0;
float saturation = 0.0;
int currentHue = 0;
float currentBrightness = 0.0;
float currentSaturation = 0.0;
unsigned long prevTimeFade = 0;
const int fadeInterval = 10; // interval between every step
bool isFading = true;
bool isForward = true; // whether the hue fades forward
uint32_t HSVColor(float h, float s, float v);
void fadeToTargetColor() {
uint16_t i;
if(prevTimeFade + fadeInterval < millis()) {
prevTimeFade = millis();
if (currentSaturation != saturation || currentBrightness != brightness || currentHue != hue) {
if (currentSaturation != saturation) currentSaturation += currentSaturation<saturation? 1:-1;
if (currentBrightness != brightness) currentBrightness += currentBrightness<brightness? 1:-1;
if (currentHue != hue) {
if (isForward) {
if (++currentHue > 360) currentHue = 0;
} else if (--currentHue < 0) currentHue = 360;
}
// set and show
for (i = 0; i < strip.numPixels(); i ++) strip.setPixelColor(i, HSVColor(currentHue, currentSaturation/100, currentBrightness/100));
strip.show();
} else isFading = false; // complete fading
}
}
void setup() {
Serial.begin(115200);
client.begin(server,wifiClient);
Serial.println("Booting");
// WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
if (client.connect((char*) clientName.c_str())) {
client.publish("outTopic",(String)"hello world, I'm "+lightTopic);
client.subscribe(lightTopic+(String)"/#");
}
}
if (client.connected()) {
client.loop();
if (isFading) fadeToTargetColor();
DHTLoop();
}
}
}
// Convert Hue/Saturation/Brightness values to a packed 32-bit RBG color.
// hue must be a float value between 0 and 360
// saturation must be a float value between 0 and 1
// brightness must be a float value between 0 and 1
uint32_t HSVColor(float h, float s, float v) {
h = constrain(h, 0, 359);
s = constrain(s, 0, 1);
v = constrain(v, 0, 1);
int i, b, p, q, t;
float f;
h /= 60.0; // sector 0 to 5
i = floor( h );
f = h - i; // factorial part of h
b = v * 255;
p = v * ( 1 - s ) * 255;
q = v * ( 1 - s * f ) * 255;
t = v * ( 1 - s * ( 1 - f ) ) * 255;
switch( i ) {
case 0:
return strip.Color(b, t, p);
case 1:
return strip.Color(q, b, p);
case 2:
return strip.Color(p, b, t);
case 3:
return strip.Color(p, q, b);
case 4:
return strip.Color(t, p, b);
default:
return strip.Color(b, p, q);
}
}
void currentValues(){
Serial.println("");
Serial.println("Current State");
Serial.print("Hue (0-360):");
Serial.println(hue);
Serial.print("Saturation (0-100 in, 0-1):");
Serial.println(saturation);
Serial.print("Brightness (0-100):");
Serial.println(brightness);
Serial.println("");
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
currentValues();
// handle message arrived
Serial.print(topic);
Serial.print(" => ");
if (topic == lightTopic) {
Serial.println(payload);
if(payload== "on"){
brightness = 100.0;
} else {
brightness = 0.0;
}
} else if (topic == lightTopic + (String)"/brightness") {
// Brightness up to 100
Serial.println(payload);
brightness = payload.toFloat();
} else if (topic == lightTopic + (String)"/hue") {
// Hue value 0-360
Serial.println(payload);
hue = payload.toInt();
} else if (topic == lightTopic + (String)"/saturation") {
// Saturation value at 0-100
Serial.println(payload);
saturation = payload.toFloat();
}
// start fading if topic is the light
if (String(topic).startsWith(lightTopic)) {
isFading = true;
isForward = hue > currentHue && hue - currentHue < 180 || currentHue > hue && currentHue - hue > 180;
}
currentValues();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment