Embeded programing and Networking

To make my DI-FARM system functional and reliable, I integrated multiple sensors and enabled network communication. Here’s how I went about it:

Libraries I Used

  • #include <OneWire.h> – For communication with the DS18B20 temperature sensor.
  • #include <DallasTemperature.h> – To read accurate temperature values.
  • #include <Wire.h> – Required for I2C communication with MPU6050.
  • #include <MPU6050_light.h> – A lightweight library to interact with MPU6050.
  • #include <TinyGPSPlus.h> – For parsing data from the GPS module.
  • #include <WiFi.h> – To enable Wi-Fi connectivity on the ESP32 C3 board.
  • #include <HTTPClient.h> – To send sensor data to the Node.js backend.

DS18B20 Temperature Sensor

I used the DS18B20 to track the cow’s body temperature. It’s waterproof and ideal for livestock monitoring.

const int DS18B20_PIN = 10;
OneWire oneWire(DS18B20_PIN);
DallasTemperature sensors(&oneWire);

sensors.begin();
sensors.requestTemperatures();
float tempC = sensors.getTempCByIndex(0);

MPU6050 Accelerometer

This sensor helps me detect whether the cow is moving, lying down, or standing. It's crucial for monitoring health and behavior.

Wire.begin(6, 7);
mpu.begin();
mpu.calcOffsets(true, true);
mpu.update();

float accX = mpu.getAccX();
float accY = mpu.getAccY();
float accZ = mpu.getAccZ();

GPS Module

Using GPS, I can track the location, altitude, and speed of my cow in real-time, which is important for both safety and logistics.

gpsSerial.begin(9600, SERIAL_8N1, 4, 5);
while (gpsSerial.available() > 0) {
  gps.encode(gpsSerial.read());
}

gps.location.lat();
gps.location.lng();
gps.altitude.meters();

Wi-Fi Connection & Sending Data

After collecting data from all sensors, I send it to my Node.js server using Wi-Fi and HTTP POST requests.

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
}

HTTPClient http;
http.begin(nodeServer);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
http.end();

Code Snippets from setup() and loop()

Here's an overview of how I structured the setup and loop functions to initialize and run the system:

void setup() {
  Serial.begin(115200);
  sensors.begin();
  gpsSerial.begin(9600, SERIAL_8N1, 4, 5);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
  Wire.begin(6, 7);
  mpu.begin();
  mpu.calcOffsets(true, true);
}

void loop() {
  while (gpsSerial.available() > 0) {
    gps.encode(gpsSerial.read());
  }
  mpu.update();

  if (millis() - prevMillis >= interval) {
    prevMillis = millis();
    readSensorsAndSend();
  }
}
System Overview