Arduino (no Shield) + ESP + MQTT = Chaos!

Hello guys,
I very very need your help.
Maybe I’m not in the right forum (arduino forum will be the right one) but I hope you can uderstand me, 'cause I’m sure some of you already afford the problem I’m going to expose you.

I wanna implement some very very easy sensors (PIR / DMT22 / Foto-resistence) on one of my arduinos board.
To implement an “internet antenna” for arduino I bought some ESP8266 (esp01 - version2 [the black one]) and not the WiFi shield.

I performed some tests by myself to check if ESP working correctly and indeed I’m able to connect my router/modem and send some AT command successfully.

Going further with the test I found a very big difficulty : MOST (almost all) ARDUINO <—> MQTT EXAMPLE CODES ON THE NET ARE BASED ON WIFI SHIELD OR ESP STAND ALONE WITH FLASHED LUA CODE ON IT [means to have a different approach and different libraries]!!!


I’m here to implore some-one with the same configuration of Arduino + Esp to share something (a working example or some of his know how) with me, please!!!
I try a lot of arduino’s library for ESP + MQTT cliente but i’m not able to find out the right ones for these project and the related examples.

Thanks a lot in advance!!!

1 Like


Why do you need the arduino, you could add directly your sensors to the ESP8266?

On ESP I’ve only 2 GPIO,
I wanna have several sensors on the same board (Like a phisical NODE of a NET), in my mind make more sence than have several ESP everyone with 1 sensor only!
Isn’t it ?

it is an ESP01?

Yes, esp01 - version2 [the black one]
Only difference from Blu-one should be the ROM space inside the memory.

in this case you are right, you need to have an arduino with some extra ports, the other possibilities is to go with an higher esp with more ports.

Regarding arduino/serial/esp01 connection I can’t help you.

If you are interested I have some example of esp8266 with mqtt and sensors directly connected

I have never tried to use an Arduino with an ESP so I can’t help you there. Personally I have taken to using NodeMCU’s for everything, even if I only need a single GPIO. For the negligible price difference, having the power supply taken care already is worth it in itself.

If you’re planning on battery powered nodes you may be disappointed with a wifi solution. Even if the nodes are sleeping a majority of the time, they do take a good amount of time to initiate a connection when they wake up. You may be better served by looking into something like,d.eWE.

If these are powered, then disregard.

I have choosen for similar approach some NodeMCU boards, costs about 3€ from China. There is the ESP8266 integrated, you have about 4 inputs and 4 outputs with some limitations.
I run them with Souliss. You can find examples on Github. These are working pretty ok with Openhab, except that I cannot get the analog input to be read in Openhab. On the Souliss Android app this is working.

Best Resoults I’ve got with these libraryes


Here you have my code … Fell free to try it and give me a little feedback please.
I wanna prepare you also the fitzing sketch but I’ve no so many time, sorry

Anycase you need:

Arduino Uno
WifiESP8266 model 01 (PIN 8 <–to-LLC-to–> TX ; PIN 9 <–to-LLC-to–> RX )
Logic Level Converter (LLC) 5 to 3.3v
Temperature Sensor (DT11 keyes in my case) (PIN 2)


  MQTT DHT22, when "temperature, c" is sent it returns the temperature in celcius
  when "humidity" is sent it returns the humidity as measured by the DHT22
  the signal pin is connected to a pull-ip resistor and GPIO 2

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
#include <DHT.h>

#define DHTTYPE DHT11
#define DHTPIN  2

// Update these with values suitable for your network.

char* ssid = "YOURSSID";
char* password = "YOURPASSWORD";
const char* mqtt_server = "YOURmqttSERVERip";
const char* clientID = "YOURCLIENTID";
const char* outTopic = "YOURCLIENTOUTTOPIC";
const char* inTopic = "YOURCLIENTINTOPIC";

int status = WL_IDLE_STATUS;   // the Wifi radio's status

// Initialize DHT sensor 
// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
// you 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.
// This is for the ESP8266 processor on ESP-01 
DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

float humidity, temp_c;  // Values read from sensor
// Generally, you should use "unsigned long" for variables that hold time
unsigned long previousMillis = 0;        // will store last temp was read
const long interval = 2000;              // interval at which to read sensor
WiFiEspClient espClient;
PubSubClient client(espClient);
char msg[50];

SoftwareSerial soft(8, 9);    // RX, TX

const int PIR_pin = 3;        
int Previous_Signal = LOW;

void setup() {
                              // initialize ESP module
  client.setServer(mqtt_server, 1883);
  dht.begin();           // initialize temperature sensor

  pinMode(PIR_pin, INPUT);


void loop() {
  int PIR_signal = digitalRead(PIR_pin);

  if (PIR_signal == HIGH && Previous_Signal == LOW)
    Previous_Signal = PIR_signal;
    Serial.println("Presence Revealed");
    client.publish(outTopic, "Presence");
  else if (PIR_signal == LOW && Previous_Signal == HIGH)
    Previous_Signal = PIR_signal;
  if (!client.connected()) {

void setup_wifi() {

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, password);

  // you're connected now, so print out the data
  Serial.println("WiFi connected");
  Serial.println("IP address: ");

void callback(char* topic, byte* payload, unsigned int length) {
  // Conver the incoming byte array to a string
  payload[length] = '\0'; // Null terminator used to terminate the char array
  String message = (char*)payload;

  Serial.print("Message arrived on topic: [");
  Serial.print("], ");

  if(message == "temperature"){
    Serial.print("Sending temperature:");
    dtostrf(temp_c , 2, 2, msg);
    client.publish(outTopic, msg);
  } else if (message == "humidity"){
    Serial.print("Sending humidity:");
    dtostrf(humidity , 2, 2, msg);
    client.publish(outTopic, msg);

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientID)) {
      // Once connected, publish an announcement...
      client.publish(outTopic, clientID);
      // ... and resubscribe
    } else {
      Serial.print("failed, rc=");
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying

void gettemperature() {
  // Wait at least 2 seconds seconds between measurements.
  // if the difference between the current time and last time you read
  // the sensor is bigger than the interval you set, read the sensor
  // Works better than delay for things happening elsewhere also
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) {
    // save the last time you read the sensor 
    previousMillis = currentMillis;   

    // Reading temperature for humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
    humidity = dht.readHumidity();          // Read humidity (percent)
    temp_c = dht.readTemperature();     // Read temperature as Celcius
    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(temp_c)) {
      Serial.println("Failed to read from DHT sensor!");

For now I work with MQTTFX to recognise the pub and sub, not already write down a role for OH2.