#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SoftwareSerial.h>
#define OLED_RESET -1
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define sensorPin A0
#define RE 8
#define DE 7
const byte nitro[] = {0x01, 0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c};
const byte phos[] = {0x01, 0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc};
const byte pota[] = {0x01, 0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0};
byte values[11];
SoftwareSerial mod(2, 3);
void setup() {
Serial.begin(9600);
mod.begin(9600);
pinMode(RE, OUTPUT);
pinMode(DE, OUTPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialize with the I2C addr 0x3C (128x64)
display.clearDisplay();
display.setCursor(25, 15);
display.setTextSize(1);
display.setTextColor(WHITE);
display.println("NPK Sensor");
display.setCursor(25, 35);
display.setTextSize(1);
display.print("Initializing...");
display.display();
delay(3000);
}
void loop() {
int soilMoistureValue = analogRead(sensorPin);
int soilMoisturePercent = map(soilMoistureValue, 0, 1023, 0, 100);
byte nitrogenValue = readSensor(nitro);
byte phosphorusValue = readSensor(phos);
byte potassiumValue = readSensor(pota);
Serial.print("Nitrogen: ");
Serial.print(nitrogenValue);
Serial.println(" mg/kg");
Serial.print("Phosphorus: ");
Serial.print(phosphorusValue);
Serial.println(" mg/kg");
Serial.print("Potassium: ");
Serial.print(potassiumValue);
Serial.println(" mg/kg");
delay(2000);
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Embedded Systems Lab");
display.println("Araf Sourov Mahid");
display.print("Soil Moisture: ");
display.print(soilMoisturePercent);
display.println("%");
display.setTextSize(2);
display.setCursor(0, 20);
display.print("N: ");
display.print(nitrogenValue);
display.setTextSize(1);
display.print(" mg/kg");
display.setTextSize(2);
display.setCursor(0, 40);
display.print("P: ");
display.print(phosphorusValue);
display.setTextSize(1);
display.print(" mg/kg");
display.setTextSize(2);
display.setCursor(0, 60);
display.print("K: ");
display.print(potassiumValue);
display.setTextSize(1);
display.print(" mg/kg");
display.display();
}
byte readSensor(const byte *command) {
digitalWrite(DE, HIGH);
digitalWrite(RE, HIGH);
delay(10);
byte returnValue = 0;
if (mod.write(command, 8) == 8) {
digitalWrite(DE, LOW);
digitalWrite(RE, LOW);
for (byte i = 0; i < 7; i++) {
values[i] = mod.read();
Serial.print(values[i], HEX);
}
Serial.println();
returnValue = values[4];
}
return returnValue;
}