Najad
Published © GPL3+

Plant Monitoring - Flutter & Websockets

In this project we are going to use the Seeed Studios‘ XIAO ESP32C dev board to read moisture data and send it to our app via WebSocket

BeginnerWork in progress1,087

Things used in this project

Software apps and online services

ESP32 IoT Plant Monitor

Story

Read more

Schematics

iot_plant_monitor_xiao_circuit_eSGLZ38fD4.jpg

Code

XIAOplantMonitoring

Arduino
// IoT Plant Monitor
// by diyusthad.com

#include <WiFi.h>
#include <WebSocketsServer.h>

int sensorPin = A0;
int moistureSensorValue = 0;

const char* ssid = "YOUR WiFi SSID";
const char* password = "WiFi PASSWORD"; 

WebSocketsServer webSocket = WebSocketsServer(80);

// Called when receiving message from WebSocket client
void onWebSocketEvent(uint8_t num,
                      WStype_t type,
                      uint8_t * payload,
                      size_t length) {


  switch (type) {

    // Client has disconnected
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", num);
      break;

    // New client has connected
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connection from ", num);
        Serial.println(ip.toString());
      }

    // Send data back to client
    case WStype_TEXT:
      Serial.printf("[%u] Text: %s\n", num, payload);
      readSensor(num);
      break;

    // For everything else: do nothing
    case WStype_BIN:
    case WStype_ERROR:
    case WStype_FRAGMENT_TEXT_START:
    case WStype_FRAGMENT_BIN_START:
    case WStype_FRAGMENT:
    case WStype_FRAGMENT_FIN:
    default:
      break;
  }
}

void setup() {

  // Start Serial port
  Serial.begin(115200);

  // Connect to access point
  Serial.println("Connecting");
  WiFi.begin(ssid, password);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
  }

  // Print IP address
  Serial.println("Connected!");
  Serial.print("My IP address: ");
  Serial.println(WiFi.localIP());

  // Start WebSocket server and assign callback
  webSocket.begin();
  webSocket.onEvent(onWebSocketEvent);

}

void readSensor(int num) {

  moistureSensorValue = analogRead(sensorPin); //Read analog data from the sensor
  int mapvalue = map(moistureSensorValue, 1100, 2700, 0, 100); // map the value
  String mapMoistureSensorValue = String(mapvalue); // convert the value to string

  // convert the string to JSON formate
  // I have used dummy values for temperature, humidity and pH
  String json = "{\"water_level\":";
  json += mapMoistureSensorValue;
  json += ",\"temperature\":0.5,\"humidity\":0.7,\"ph\":0.2}";

  webSocket.sendTXT(num, json); //send data to client

}

void loop()
{
  webSocket.loop();
}

Credits

Najad
30 projects • 99 followers
Just crazy stuff​
Contact

Comments

Please log in or sign up to comment.