Mohamed Nour Bouraoui
Published

Watero

With Watero smart irrigation system, your plants will be healthy and flourish all year round. You'll never have to worry again!

IntermediateFull instructions provided286
Watero

Things used in this project

Hardware components

ESP32
Espressif ESP32
×1
Wio Terminal
Seeed Studio Wio Terminal
×1
Grove - I2C High Accuracy Temp&Humi Sensor (SHT35)
Seeed Studio Grove - I2C High Accuracy Temp&Humi Sensor (SHT35)
×1
water pumps
×1
Growth led
×1

Software apps and online services

Arduino IoT Cloud
Arduino IoT Cloud

Story

Read more

Code

Wio Terminal code

Arduino
#include"Free_Fonts.h"
#include <TFT_eSPI.h>        // Hardware-specific library
#include "seeed_rpcUnified.h"
#include "rtl_wifi/wifi_unified.h"
#include "DNSServer.h"
#include "WebServer.h"
 

#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "usernqme"
#define AIO_KEY         "Enter_Adafruit_IO_Key"

const char *ssid = "ssid";
const char *password = "pass";
TFT_eSPI tft = TFT_eSPI();   // Invoke library
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
float temp,moist,hum;
String sts_1,sts_2;
Adafruit_MQTT_Subscribe hum = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/hum");
Adafruit_MQTT_Subscribe moist = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/moist");
Adafruit_MQTT_Subscribe tem = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/temp");

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

esp_err_t wifi_event_callback(void *ctx, system_event_t *event)
{
    Serial.printf("[WiFi-event] event: %d\n\r", event->event_id);
    
    switch (event->event_id)
    {
    case SYSTEM_EVENT_WIFI_READY:
        Serial.printf("WiFi interface ready\n\r");
        break;
    case SYSTEM_EVENT_SCAN_DONE:
        Serial.printf("Completed scan for access points\n\r");
        break;
    case SYSTEM_EVENT_STA_START:
        Serial.printf("WiFi client started\n\r");
        break;
    case SYSTEM_EVENT_STA_STOP:
        Serial.printf("WiFi clients stopped\n\r");
        break;
    case SYSTEM_EVENT_STA_CONNECTED:
        Serial.printf("Connected to access point\n\r");
        break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
        Serial.printf("Disconnected from WiFi access point\n\r");
        break;
    case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:
        Serial.printf("Authentication mode of access point has changed\n\r");
        break;
    case SYSTEM_EVENT_STA_GOT_IP:
        Serial.printf("Obtained IP address: \n\r");
        break;
    case SYSTEM_EVENT_STA_LOST_IP:
        Serial.printf("Lost IP address and IP address is reset to 0\n\r");
        break;
    case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
        Serial.printf("WiFi Protected Setup (WPS): succeeded in enrollee mode\n\r");
        break;
    case SYSTEM_EVENT_STA_WPS_ER_FAILED:
        Serial.printf("WiFi Protected Setup (WPS): failed in enrollee mode\n\r");
        break;
    case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
        Serial.printf("WiFi Protected Setup (WPS): timeout in enrollee mode\n\r");
        break;
    case SYSTEM_EVENT_STA_WPS_ER_PIN:
        Serial.printf("WiFi Protected Setup (WPS): pin code in enrollee mode\n\r");
        break;
    case SYSTEM_EVENT_AP_START:
        Serial.printf("WiFi access point started\n\r");
        break;
    case SYSTEM_EVENT_AP_STOP:
        Serial.printf("WiFi access point  stopped\n\r");
        break;
    case SYSTEM_EVENT_AP_STACONNECTED:
        Serial.printf("Client connected\n\r");
        break;
    case SYSTEM_EVENT_AP_STADISCONNECTED:
        Serial.printf("Client disconnected\n\r");
        break;
    case SYSTEM_EVENT_AP_STAIPASSIGNED:
        Serial.printf("Assigned IP address to client\n\r");
        break;
    case SYSTEM_EVENT_AP_PROBEREQRECVED:
        Serial.printf("Received probe request\n\r");
        break;
    case SYSTEM_EVENT_GOT_IP6:
        Serial.printf("IPv6 is preferred\n\r");
        break;
    case SYSTEM_EVENT_ETH_START:
        Serial.printf("Ethernet started\n\r");
        break;
    case SYSTEM_EVENT_ETH_STOP:
        Serial.printf("Ethernet stopped\n\r");
        break;
    case SYSTEM_EVENT_ETH_CONNECTED:
        Serial.printf("Ethernet connected\n\r");
        break;
    case SYSTEM_EVENT_ETH_DISCONNECTED:
        Serial.printf("Ethernet disconnected\n\r");
        break;
    case SYSTEM_EVENT_ETH_GOT_IP:
        Serial.printf("Obtained IP address\n\r");
        break;
    default:
        break;
    }

    return ESP_OK;
}


void setup() {
   system_event_callback_reg(wifi_event_callback);
    tcpip_adapter_init();
  tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
  wifi_off();
    vTaskDelay(20);
  if (wifi_on(RTW_MODE_STA) < 0){
    printf("\n\rERROR: Wifi on STA failed!");
  }
  int ret = rpc_wifi_connect(ssid, password, RTW_SECURITY_WPA2_AES_PSK, -1, NULL);
  if(ret == RTW_ERROR)
  {
    printf("Error!!\n\r");
  }else
  {
    tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
  }
    tft.begin();  
    tft.setRotation(3);// Initialise the display
    tft.fillScreen(TFT_WHITE); // Black screen fill
     mqtt.subscribe(&temp);
  mqtt.subscribe(&moist);
  mqtt.subscribe(&hum);
}

void loop() {

     static wlan_fast_reconnect_profile_t wifi_info = {0};
 if(wifi_get_reconnect_data(&wifi_info)!=0)
  {
    Serial.printf("SSID: %s\n\r", wifi_info.psk_essid);
    Serial.println("Cnx_OK");
  }
   MQTT_connect();
   Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    // Check if its the onoff button feed
    if (subscription == &temp) {
    int16_t  t=(int16_t *)temp.lastread)    
    }
    
    if (subscription == &moist) {
    int16_t  m=(int16_t *)moist.lastread) 
    }
     if (subscription == &hum) {
    int16_t  h=(int16_t *)hum.lastread) 
    }
  }
  tft.setTextColor(TFT_BLACK, TFT_WHITE);
  tft.setFreeFont(&FreeSansBoldOblique12pt7b);
    //select Free, Sans, Bold, Oblique, 12pt.
  tft.drawString("Temp",00,00);
  tft.drawString("Humi",130,00);
  tft.drawString("Moist",252,00);
  tft.drawString("Pump",230,110);
  tft.drawString("UVLed",48,110);
    //  tft.setCursor(120, 200, 4);
      tft.setTextColor(TFT_GREEN, TFT_WHITE);
     tft.drawString("Watero",100,200,1);
   // delay(500);
   tft.setTextColor(TFT_BLUE, TFT_BLACK);
  
tft.drawNumber(t, 00, 30,7);
tft.drawNumber(h, 130,30,7);
tft.drawNumber(m, 250, 30,7);
String sts_1="ON";
String sts_2="OFF";
  tft.drawString(sts_1,230,150);
  tft.drawString(sts_2,48,150); 
  if(! mqtt.ping()) {
    mqtt.disconnect();
  }
}
void MQTT_connect()
{
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT ");

  uint8_t retries = 3;

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds");
    mqtt.disconnect();

Esp32 Code

Arduino
#include <WiFi.h>
#include "WiFiClientSecure.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <SensirionI2CSht4x.h>
#include <Wire.h>
/************************* WiFi Access Point *********************************/

#define WLAN_SSID "WLAN_SSID"
#define WLAN_PASS "WIFI_PASSWORD"

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"

// Using port 8883 for MQTTS
#define AIO_SERVERPORT  8883

// Adafruit IO Account Configuration
// (to obtain these values, visit https://io.adafruit.com and click on Active Key)
#define AIO_USERNAME "YOUR_ADAFRUIT_IO_USERNAME"
#define AIO_KEY      "YOUR_ADAFRUIT_IO_KEY"

/************ Global State (you don't need to change this!) ******************/

// WiFiFlientSecure for SSL/TLS support
WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

// io.adafruit.com root CA
const char* adafruitio_root_ca = \
    "-----BEGIN CERTIFICATE-----\n" \
    "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \
    "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \
    "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \
    "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \
    "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \
    "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \
    "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \
    "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \
    "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \
    "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \
    "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \
    "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \
    "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \
    "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \
    "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \
    "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \
    "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \
    "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \
    "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \
    "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \
    "-----END CERTIFICATE-----\n";

/****************************** Feeds ***************************************/

// Setup a feed called 'test' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>


/*************************** Sketch Code ************************************/
SensirionI2CSht4x sht4x;
void setup() {
  Serial.begin(115200);
  delay(10);
pinMode(4,OUTPUT);
  pinMode(13,OUTPUT);
  //I2C SHT40 temp&Hum sensor init
 Wire.begin();
 
    uint16_t error;
    char errorMessage[256];
 
    sht4x.begin(Wire);
 
    uint32_t serialNumber;
    error = sht4x.serialNumber(serialNumber);
    if (error) {
        Serial.print("Error trying to execute serialNumber(): ");
        errorToString(error, errorMessage, 256);
        Serial.println(errorMessage);
    } else {
        Serial.print("Serial Number: ");
        Serial.println(serialNumber);
    }
    //end SHT40 init 

  
  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  delay(1000);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  delay(2000);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());

  // Set Adafruit IO's root CA
  client.setCACert(adafruitio_root_ca);
}

uint32_t x=0;

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  moistref =analogRead(34);
  Serial.println(moistref);
  // SHT40
   uint16_t error;
    char errorMessage[256];

    delay(1000);

    float temperature;
    float humidity;
    error = sht4x.measureHighPrecision(temperature, humidity);
    if (error) {
        Serial.print("Error trying to execute measureHighPrecision(): ");
        errorToString(error, errorMessage, 256);
        Serial.println(errorMessage);
    } else {
        Serial.print("Temperature:");
        Serial.print(temperature);
        temp=temperature;
        Serial.print("\t");
        Serial.print("Humidity:");
        Serial.println(humidity);
        hum=humidity;
    }
Adafruit_MQTT_Publish hum = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/hum");
Adafruit_MQTT_Publish moistref = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/moist");
Adafruit_MQTT_Publish temp = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temp");
  MQTT_connect();

  // Now we can publish stuff!
  Serial.print(F("\nSending val "));
  Serial.print(x);
  Serial.print(F(" to test feed..."));
  if (! test.publish(x++)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

  // wait a couple seconds to avoid rate limit
  delay(2000);

}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }

  Serial.println("MQTT Connected!");
}

Credits

Mohamed Nour Bouraoui

Mohamed Nour Bouraoui

1 project • 1 follower

Comments