#include <DallasTemperature.h>
#include <OneWire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
const int PH_PIN = 32,
TEMP_PIN = 22;
#define ncom 3 // number of commands
char commar[ncom] = {0x1, 0x3, 0x5}; // Actual commands
const char* respar[ncom] = {"Phosphorous value is: ", "Potassium value is: ", "Nitrogen value is: "};
uint8_t rtValue[ncom]; // Store the return values from the custom chip in here
float phVal = 0, tempVal = 0;
int readVal = 0;
OneWire oneWire(TEMP_PIN); // creates the OneWire object using a specific pin
DallasTemperature sensor(&oneWire);
// OLED display setup
#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, -1);
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Infinite loop if display initialization fails
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
Serial2.begin(15200, SERIAL_8N1, 16, 17); // Initialize the custom chip communication line
pinMode(PH_PIN, INPUT);
sensor.begin();
}
void loop() {
// Read and display pH value
readVal = analogRead(PH_PIN);
phVal = ((float) readVal / 4095.0) * 14;
Serial.print("Current PH: ");
Serial.println(phVal);
// Read and display temperature value
sensor.requestTemperatures();
tempVal = sensor.getTempCByIndex(0);
if (tempVal == -127) {
Serial.println("Temperature Sensor Not Found.");
delay(1000);
return;
}
Serial.print("Temperature: ");
Serial.print(tempVal);
Serial.println("ºC");
// Display values on OLED
displayValues(phVal, tempVal);
delay(1000);
// Read and display NPK values
readNPKSensor();
}
void readNPKSensor() {
for (uint8_t i = 0; i < ncom; i++) {
Serial2.print((char)commar[i]); // Send the command stored in ncom array through serial2
if (Serial2.available()) {
rtValue[i] = Serial2.read();
Serial2.flush();
Serial.print(respar[i]);
Serial.println(rtValue[i]);
}
}
// Display NPK values on OLED
displayNPKValues(rtValue[0], rtValue[1], rtValue[2]);
}
void displayValues(float pH, float temperature) {
display.clearDisplay();
display.setCursor(0, 0);
display.print("Current PH: ");
display.println(pH);
display.setCursor(0, 10);
display.print("Temperature: ");
display.print(temperature);
display.println(" C");
display.display();
}
void displayNPKValues(uint8_t nitrogen, uint8_t phosphorous, uint8_t potassium) {
display.setCursor(0, 30);
display.print("N: ");
display.print(nitrogen);
display.setCursor(0, 40);
display.print("P: ");
display.print(phosphorous);
display.setCursor(0, 50);
display.print("K: ");
display.print(potassium);
display.display();
}