Harun YenisanMehmet Emin Uğur
Published © MIT

Automated Pest Control System in Agriculture Fields

Automated Pest Control System in Agriculture Fields

IntermediateWork in progress24 hours52
Automated Pest Control System in Agriculture Fields

Things used in this project

Hardware components

RAKwireless RAK4631
×1
RAKwireless RAK19003
×1
RAKwireless RAK12033
×1
RAKwireless Solar Panel
×1
RAKwireless RAK7268V2
×1
RAKwireless RAK13009
×1

Software apps and online services

Arduino IDE
Arduino IDE
The Things Industries TheThingsNetwork

Hand tools and fabrication machines

Multitool, Screwdriver
Multitool, Screwdriver

Story

Read more

Code

Automated Pest Control System in Agriculture Fields

Arduino
#include <LoRaWan-RAK4631.h> // LoRaWAN library for RAK4631
#include <SPI.h>
#include <Wire.h>

// For RAK12033 Motion Sensor (assuming PIR sensor)
#define MOTION_SENSOR_PIN WB_IO4 // GPIO pin connected to RAK12033
#define RELAY_PEST_CONTROL_PIN WB_IO3 // Relay pin controlling the pest control device (e.g., repellent, trap)

// LoRaWAN Join Settings
// You must obtain these values from your TheThingsNetwork (TTN) console.
String node_device_eui = "AC1F09FFFE0xxxx"; // <<< CHANGE THIS
String node_app_eui = "70B3D57ED000xxxx";   // <<< CHANGE THIS
String node_app_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // <<< CHANGE THIS

// LoRaWAN Application Port
#define LORAWAN_APP_PORT 1

// Data Transmission Interval and Sensor Cooldown Durations
#define SEND_INTERVAL_SEC 30 // Send status or last motion info every 30 seconds
#define MOTION_COOLDOWN_MS 5000 // Cooldown period for the sensor after motion detection (5 seconds)

// Timer Variables
long lastSendTime = 0;      // Last data transmission time (millis())
long lastMotionTime = 0;    // Last motion detection time (millis())
bool pestControlActive = false; // Tracks whether the pest control device is active

void setup() {
  // Set internal LED as OUTPUT and turn it off initially
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW); 
  
  // Start serial communication (for debug messages)
  Serial.begin(115200);
  while (!Serial); // Wait for serial port to be ready
  Serial.println("Automated Pest Control System Starting...");

  // Set motion sensor pin as INPUT
  pinMode(MOTION_SENSOR_PIN, INPUT);
  // Set relay pin as OUTPUT and keep it off initially
  pinMode(RELAY_PEST_CONTROL_PIN, OUTPUT);
  digitalWrite(RELAY_PEST_CONTROL_PIN, LOW); 

  // Initialize and configure LoRaWAN module
  api.lorawan.setMcuStatus(true);         // Set MCU status
  api.lorawan.setDeviceClass(CLASS_A);    // Set device class
  api.lorawan.setRegion(EU868);           // Set LoRaWAN region
  api.lorawan.setDevEui(node_device_eui); // Set Device EUI
  api.lorawan.setAppEui(node_app_eui);   // Set Application EUI
  api.lorawan.setAppKey(node_app_key);   // Set Application Key
  api.lorawan.setConfirm(true);          // Use confirmed messages?
  api.lorawan.setAdaptiveDr(true);       // Use Adaptive Data Rate (ADR)?
  
  Serial.println("Attempting to join LoRaWAN network...");
  api.lorawan.join(); // Start LoRaWAN network join process

  // Initialize timer
  lastSendTime = millis();
}

void loop() {
  // Read current state of motion sensor
  int motionState = digitalRead(MOTION_SENSOR_PIN);

  // If motion is detected AND cooldown period has passed
  if (motionState == HIGH && (millis() - lastMotionTime > MOTION_COOLDOWN_MS)) {
    Serial.println("Motion Detected! Notifying Node-RED for Pest Control System.");
    sendMotionDetectedPayload(); // Send motion detected via LoRaWAN
    lastMotionTime = millis(); // Reset timer to start cooldown period
  }

  // Check LoRaWAN network connection status
  if (api.lorawan.queryNetworkStatus() == LORAWAN_JOINED) {
    // Check if it's time for periodic data transmission
    if (millis() - lastSendTime > (SEND_INTERVAL_SEC * 1000)) {
      // Optional: We can also periodically send general device status or last motion info.
      // For example, a 'heartbeat' message even if no continuous motion.
      // sendDeviceStatus(); 
      lastSendTime = millis(); // Reset timer
    }
  } else {
    // If not connected to LoRaWAN network, try to join again...
    Serial.println("Not connected to LoRaWAN network, trying to join again...");
    api.lorawan.join(); 
    delay(10000); // Wait 10 seconds before retrying
  }
}

// Function to send a LoRaWAN payload indicating motion detection
void sendMotionDetectedPayload() {
  uint8_t payload[1]; // 1-byte payload
  payload[0] = 1;     // Send 1 to indicate motion detected (true)

  Serial.println("Sending LoRaWAN 'Motion Detected' data...");
  // Send payload to LoRaWAN network. Use LORAWAN_APP_PORT and send as confirmed message (true).
  api.lorawan.send(sizeof(payload), payload, LORAWAN_APP_PORT, true);
}

// Callback function to be called when a LoRaWAN downlink message is received
// Processes commands from Node-RED or via TTN (e.g., turn pest control on/off)
void OnRxData(lorawan_AppData_t* appData) {
  Serial.printf("LoRaWAN Downlink message received, Port: %d, Length: %d\n", appData->Port, appData->BuffSize);
  
  // Print received payload to serial monitor
  Serial.print("Payload (hex): ");
  for (int i = 0; i < appData->BuffSize; i++) {
    Serial.printf("%02X ", appData->Buffer[i]);
  }
  Serial.println();

  // Convert payload to String and interpret as command
  String command = "";
  for (int i = 0; i < appData->BuffSize; i++) {
    command += (char)appData->Buffer[i];
  }
  Serial.print("Received Command: ");
  Serial.println(command);

  // Control relay based on incoming commands (pest control device)
  if (command == "PEST_ON") {
    digitalWrite(RELAY_PEST_CONTROL_PIN, HIGH); // Turn on relay
    pestControlActive = true;
    Serial.println("PEST CONTROL SYSTEM TURNED ON!");
  } else if (command == "PEST_OFF") {
    digitalWrite(RELAY_PEST_CONTROL_PIN, LOW);  // Turn off relay
    pestControlActive = false;
    Serial.println("PEST CONTROL SYSTEM TURNED OFF!");
  } else {
    Serial.println("Unknown command.");
  }
}

// Mandatory callback function definitions for LoRaWAN library
void lorawan_rx_handler(lorawan_AppData_t* appData) {
  OnRxData(appData); // Call OnRxData function when data is received
}

void lorawan_has_joined_handler(void) {
  Serial.println("Successfully joined LoRaWAN network!");
  digitalWrite(LED_BUILTIN, HIGH); // Turn on internal LED after joining network
}

void lorawan_join_failed_handler(void) {
  Serial.println("LoRaWAN network join failed. Retrying...");
  digitalWrite(LED_BUILTIN, LOW); // Turn off internal LED if join fails
}

void lorawan_tx_handler(void) {
  Serial.println("LoRaWAN Tx Done!"); // Inform when data transmission is complete
}

Credits

Harun Yenisan
8 projects • 7 followers
Electronic engineer, working as an IT teacher at the Ministry of National Education.
Mehmet Emin Uğur
9 projects • 9 followers
Computer engineer, working as an IT teacher at the Ministry of National Education.

Comments