ey5
Published © MPL-2.0

Automatic gate control for agricalture purpose

Water is a scarce commodity for rural agriculture. The inability to account for water utilization at the farm block level is the key hindran

AdvancedFull instructions provided285
Automatic gate control for agricalture purpose

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Relay (generic)
×1
Geared DC Motor, 24 V
Geared DC Motor, 24 V
×1

Software apps and online services

Arduino IDE
Arduino IDE
Visual Studio 2017
Microsoft Visual Studio 2017

Story

Read more

Schematics

circiut digram

Code

automaic gate control

C/C++
/** LIBRARIES**/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include "HX710B.h"
#include "FS.h"
#include "SD.h"
#include <SPI.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
/** LIBRARIES**/

/**SD CARD**/
uint64_t uS_TO_S_FACTOR = 1000000; 
uint64_t TIME_TO_SLEEP = 300;
#define SD_CS 5
RTC_DATA_ATTR int sensor_data = 0;
String Data;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
String Date;
String day;
String Time;
/** SD CARD**/

/** WEBSOCKET INITALIZATION**/
WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
WebSocketsClient webSocket3;
/** WEBSOCKET INITALIZATION**/ 

/**  PIN DECLARATION FOR PRESSURE AND ULTRASONIC RESPECTIVE**/
const int DOUT = 22;   //sensor data pin
const int SCLK  = 24;   //sensor clock pin
float pressure;
float fixed_pressure=549.7;
HX710B pressure_sensor; 

static int sensorVal = 0;

/**  PIN DECLARATION FOR PRESSURE AND ULTRASONIC RESPECTIVE**/
const int trigPin = 5;
const int echoPin = 18;
long duration;
float distanceMm;
#define SOUND_SPEED 0.034
int inputHeight=10;
int heightTolorance=1;
int fixedHeight=46;
//int openingHeight;
//int userOpeningdifference;

/** calculation to control the motor**/
int openingHeight=fixedHeight-distanceMm;
int userOpeningdifference=inputHeight-openingHeight;
 /** calculation to control the motor**/
/**  PIN DECLARATION FOR PRESSURE AND ULTRASONIC RESPECTIVE**/

/** FOR PRESSURE **/
//float pressure;
float inputpressure=10;
float pressureTolorance=1;
float fixedpressure=46;

/** calculation to control the motor**/
int openingpressure=fixedpressure-pressure;
int userOpeningDifferencep=inputHeight-openingpressure;
/** FOR RELAY**/
#define CW 14 //CW is defined as pin #7//
#define CCW 15 //CCW is defined as pin #8//

//for limit switch
int Lswitch = 2; 

// CHANGE THIS TO ADD YOUR WIFI USERNAME/PASSWORD
const char * WIFI_SSID = "TP-Link_27ED";
const char * WIFI_PASS = "19202122";
 
//Initialize the JSON data we send to our websocket server
const int capacity = JSON_OBJECT_SIZE(3);
StaticJsonDocument<capacity> doc;
StaticJsonDocument<1024> rx_doc;

 /** FOR DEVICE TEMPERATURE READING**/
#define USE_SERIAL Serial
 
 #ifdef __cplusplus

extern "C" {

#endif

uint8_t temprature_sens_read();

#ifdef __cplusplus

}

#endif

uint8_t temprature_sens_read();
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length)
{
 
  switch(type)
  {
  case WStype_DISCONNECTED:
    USE_SERIAL.printf("[WSc] Disconnected!\n");
    break;
  case WStype_CONNECTED:
    USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
    break;
  case WStype_TEXT:
    USE_SERIAL.printf("[WSc] get text: %s\n", payload);
    // deserializeJson(rx_doc,payload);
    // // String height = rx_doc["height"];
    // USE_SERIAL.println(rx_doc["height"]);
    break;
  case WStype_BIN:
    USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
    break;
  case WStype_ERROR:
//   case WStype_FRAGMENT_TEXT_START:
  case WStype_FRAGMENT_BIN_START:
  case WStype_FRAGMENT:
  case WStype_FRAGMENT_FIN:
  case WStype_PING:
  case WStype_PONG:
    break;
  }
}
/** FOR DEVICE TEMPERATURE READING**/ 

void setup()
{
  //Set the baud rate
  USE_SERIAL.begin(115200);
  USE_SERIAL.printf("Begin websocket client program....");
 /** FOR WIFI CONNECTION **/
  USE_SERIAL.println();
 WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
/** FOR WIFI CONNECTION **/
  
  Serial.println(WiFi.localIP());
//   for (uint8_t t = 4; t > 0; t--)
//   {
//     USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
//     USE_SERIAL.flush();
//     delay(1000);
//   }
 
//   WiFiMulti.addAP(WIFI_SSID, WIFI_PASS);
 
  // WiFi.disconnect();
  USE_SERIAL.printf("Connecting");
//   while (WiFiMulti.run() != WL_CONNECTED)
//   {
//     USE_SERIAL.printf(".");
//     delay(100);
//   }
  USE_SERIAL.printf("Connected!");
 
  // server address, port and URL
  webSocket.begin("192.168.0.141", 8085, "/sendSensorData");
  webSocket3.begin("192.168.0.141", 8085, "/request");
 
  // event handler
  webSocket.onEvent(webSocketEvent);
 webSocket3.onEvent(webSocketEvent);
  // use HTTP Basic Authorization this is optional remove if not needed
  // webSocket.setAuthorization("user", "Password");
 
  // try ever 5000 again if connection has failed
  webSocket.setReconnectInterval(5000);
  webSocket3.setReconnectInterval(10000);

 
  // // Set the resolution values
  // analogReadResolution(RESOLUTION);
  pinMode(Lswitch, INPUT); 

  /**SD CARD**/
   timeClient.begin();
  timeClient.setTimeOffset(18000);
   
  if(!SD.begin()) {
    Serial.println("Card Mount Failed");
    return;
  }
  uint8_t cardType = SD.cardType();
  if(cardType == CARD_NONE) {
    Serial.println("No SD card attached");
    return;
  }
  Serial.println("Initializing SD card...");
  if (!SD.begin()) {
    Serial.println("SD card initialization failed!");
    return;    
  }

  File file = SD.open("/sensor_readings.txt");
  if(!file) {
    Serial.println("File does not exist");
    Serial.println("Creating file...");
    writeFile(SD, "/temperature_readings.txt", "Reading Number, Date, Hour, Temperature \r\n");
  }
  else {
    Serial.println("File exists");  
  }
  file.close();

  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
/**  sensors.begin(); 
  obtainReadings();
  obtain_Date_Time();
  data_logging();**/
 Serial.println("Sensor data logged successfully! Going to sleep");
  esp_deep_sleep_start(); 
    pressure_sensor.begin(DOUT, SCLK);
}

void presssurereading()
{
  if (pressure_sensor.is_ready())
{
    Serial.print("mmh20: ");
    pressure=(pressure_sensor.pascal()-fixed_pressure)*2.469;
    Serial.println(pressure); 
} 
}

void lmitswitch()
{
  if(digitalRead(Lswitch) == LOW) 
  {
    digitalWrite(CW,LOW); //Motor runs clockwise
  }
  
  else if(digitalRead(Lswitch) == HIGH) 
  {
   digitalWrite(CW,HIGH); //Motor runs clockwise/ 
  }
}

void readDistanceValue()
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input

digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

   // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance
  distanceMm = (duration * SOUND_SPEED/2)*10;
  
  // Prints the distance in the Serial Monitor
  Serial.print("Distance (Mm): ");
  USE_SERIAL.println(distanceMm);
   // Check if value read is different then send a websocket message to the server
 if (distanceMm != sensorVal)
  {
    sensorVal = distanceMm;
 //send JSON message in this format {"value": 100}
    doc["Distance"] = distanceMm;
 // Declare a buffer to hold the result
    
    char output[50];
 serializeJson(doc, output);
 
    // send message to server when Connected
    webSocket.sendTXT(output);
  }
 // sleep for some time before next read
  delay(100);
}

void readPressureValue()
{
 
 pressure_sensor.begin(DOUT, SCLK);

 if (pressure_sensor.is_ready())
{
    Serial.print("mmh20: ");
    pressure=(pressure_sensor.pascal()-fixed_pressure)*2.469;
    Serial.println(pressure); 
} 
  // Check if value read is different then send a websocket message to the server
  if (pressure != sensorVal)
  {
    sensorVal = pressure;
 
    //send JSON message in this format {"value": 100}
    doc["pressure"] = pressure;
    
 
    // Declare a buffer to hold the result
    char output[50];
 
    serializeJson(doc, output);
 
    // send message to server when Connected
    webSocket.sendTXT(output);
  }
 
  // sleep for some time before next read
  delay(100);
}

void readDeviceTempValue()
{
 
Serial.print("Temperature: ");
float TempDevice=(temprature_sens_read() - 32) / 1.8;
Serial.print(TempDevice);
Serial.println(" C");
delay(1000);
  // Check if value read is different then send a websocket message to the server
  if (TempDevice != sensorVal)
  {
    sensorVal = TempDevice;
 
    //send JSON message in this format {"value": 100}
    doc["TempDevice"] = TempDevice;
   // Declare a buffer to hold the result
    char output[50];
 
    serializeJson(doc, output);
 
    // send message to server when Connected
    webSocket.sendTXT(output);
  }
 
  // sleep for some time before next read
  delay(100);
}
// This will go into loop
void clockwiserotation()
{
  if(openingHeight>inputHeight)
{
  digitalWrite(CW,HIGH); //Motor runs clockwise/
}
}
void counterclockwiserotation()
{
  if(openingHeight>inputHeight)
{
  digitalWrite(CCW, HIGH);
}
}
void motorstop()
{
  if(userOpeningdifference<heightTolorance)
{
  digitalWrite(CW, LOW); //Motor stops//
}
}
void obtain_Date_Time() {
  while(!timeClient.update()) {
    timeClient.forceUpdate();
  }
  Date = timeClient.getFormattedTime();
  Serial.println(Date);
  
  int split = Date.indexOf("T");
  day = Date.substring(0, split);
  Serial.println(day);
  Time = Date.substring(split+1, Date.length()-1);
  Serial.println(Time);
}

void data_logging() {
  Data = String(sensor_data) + "," + String(day) + "," + String(Time) + "," + 
                String(distanceMm) + "\r\n";
  Serial.print("Save data: ");
  Serial.println(Data);
  appendFile(SD, "/temperature_readings.txt", Data.c_str());
}

void writeFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Writing file: %s\n", path);

  File file = fs.open(path, FILE_WRITE);
  if(!file) {
    Serial.println("Failed to open file for writing");
    return;
  }
  if(file.print(message)) {
    Serial.println("File written");
  } else {
    Serial.println("Write failed");
  }
  file.close();
}

void appendFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Appending to file: %s\n", path);

  File file = fs.open(path, FILE_APPEND);
  if(!file) {
    Serial.println("Failed to open file for appending");
    return;
  }
  if(file.print(message)) {
    Serial.println("Message appended");
  } else {
    Serial.println("Append failed");
  }
  file.close();
}
void loop()
{
  readDistanceValue();
  presssurereading();
  readPressureValue();
  readDeviceTempValue();
  clockwiserotation();
  counterclockwiserotation();
  motorstop();
  lmitswitch();
//  obtainReadings();
 obtain_Date_Time();
 data_logging();
 sensor_data++;
  webSocket.loop();
  webSocket3.loop();
}

Credits

ey5
3 projects • 0 followers

Comments