Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By LeXLuther422
#18411 I wanted to make a very simple (code wise) ESP8266 MQTT transmitter to use with my OpenHAB setup I have once a minute and I couldn't find much that where not over complicated so here is my code for others to use. I used The Arduino IDE. I'll update more as I have time. If anyone sees anything bad with the code please let me know as I am no expert in codeing.
Code: Select all/* Started with Basic MQTT example */

#include <ESP8266WiFi.h>      //ESP library from http://github.com/esp8266/Arduino
#include <PubSubClient.h>      // MQTT library from http://github.com/Imroy/pubsubclient
#include <DHT.h>      // DHT library from http://github.com/adafruit/DHT-sensor-library
                      // Written by ladyada, public domain

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
//DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for ESP8266:
DHT dht(DHTPIN, DHTTYPE, 20);



const char *ssid =   "********";      // cannot be longer than 32 characters!
const char *pass =   "********";      //
long previousMillis = 0;      // Timer loop from http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
long interval = 60000;        //
IPAddress server(192, 168, 2, 15);    // Update these with values suitable for your network.
PubSubClient client(server);

void setup(){
  // Setup console
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();
  dht.begin();
  WiFi.begin(ssid, pass);
  int retries = 0;
  while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) {
    retries++;
    delay(500);
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
  }
client.connect("clientName");
}

void loop(){
  client.loop();
  unsigned long currentMillis = millis();
    if(currentMillis - previousMillis > interval) {
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius
      //float t = dht.readTemperature();
      // Read temperature as Fahrenheit
      float f = dht.readTemperature(true);
        // Check if any reads failed and exit early (to try again).
        if (isnan(h) || isnan(f)) {
          Serial.println("Failed to read from DHT sensor!");
          return;
        }
      previousMillis = currentMillis;
      Serial.println("DTH sensor read and transmitted");
      client.publish("m_bed/temperature",String(f));
      client.publish("m_bed/humidity",String(h));
  }
}

Here is the stripped down just works version.
Code: Select all#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
DHT dht(2, DHT22, 20);
const char *ssid =   "********";
const char *pass =   "********";
long previousMillis = 0;
long interval = 60000;
IPAddress server(192, 168, 2, 15);
PubSubClient client(server);

void setup(){
  dht.begin();
  WiFi.begin(ssid, pass);
client.connect("clientName");
}

void loop(){
  client.loop();
  unsigned long currentMillis = millis();
    if(currentMillis - previousMillis > interval) {
      float h = dht.readHumidity();
      float f = dht.readTemperature(true);
        if (isnan(h) || isnan(f)) {
          return;
        }
      previousMillis = currentMillis;
      client.publish("m_bed/temperature",String(f));
      client.publish("m_bed/humidity",String(h));
  }
}

Here is what my test setup looks like I am currently designing a board to house everything.
20150524_183818.jpg

EDIT: add code with comments/2 add photo/3 add clientconnect
You do not have the required permissions to view the files attached to this post.
Last edited by LeXLuther422 on Mon Jun 29, 2015 2:49 pm, edited 2 times in total.
User avatar
By Pigs Fly
#18467 This is a really helpful simplification, thanks for taking the time to share it. If you don't mind, some questions related more toward your setup rather than the code:

Which module do you use?

How long has it run without locking up?

What signal lines do you have at fixed levels (direct wired or via resistor) or left floating?

Thanks again.
User avatar
By LeXLuther422
#18488 So far it has been running over a day with out locking up sending a message every minute. Last night I did notice something peculiar the AI-THINKER AP is still running and I need to figure out how to disable it.

I'm using ESP-03 modules and have it wired very simply. The DHT has a 100k pullup between 3.3v and data. Data is also wired to GPIO2 on the ESP-03. 3.3v is wired to ESP VCC, CH_PD and DHT VCC . GND is wired to ESP GND, GPIO15 and DHT GND.

Here is am image from benlo.com
Image
User avatar
By Pigs Fly
#18503 Interesting, thanks, I hope it continues without locking up. I've been using the -07 and -12 modules (maybe a dozen in use overall) and have found them to be unreliable in some cases, usually when using the DHT22 by itself or in combination with other sensors. When using only the DS18B20 I've yet to see one lock up, even when the code for the DHT22 is still present. In my case it happens anywhere from a few hours after power is applied to several days.

This is true whether I use Lua or Arduino, so I suspect it's some interaction with the DHT and the module.

Although I've tried different hookups, I usually have mine wired like yours, GPIO15 to common, CH_PD to Vin, GPIO0 floating or V+, Reset floating or V+, GPIO2 floating or V+. The DHT22 has been tried on several different pins with no change.

I know that's a bit off-topic, but since you're using a DHT22 and I've found a possible relationship with that and the lock-ups, I thought it worth asking.