#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define PH_SENSOR_PIN A0
#define CALIB_BUTTON_PIN 2
#define RED_PIN 9
#define GREEN_PIN 10
#define BLUE_PIN 11
LiquidCrystal_I2C lcd(0x27, 16, 2);
bool isCalibrated = false;
bool blinking = false;
unsigned long lastBlinkTime = 0;
float v_offset = 0; // Será ajustado na calibração
void setup() {
pinMode(CALIB_BUTTON_PIN, INPUT_PULLUP);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("SENSOR DE PH");
setLED(255, 0, 0); // Vermelho piscando
}
void loop() {
if (digitalRead(CALIB_BUTTON_PIN) == LOW && !isCalibrated) {
calibrate();
}
if (!isCalibrated) {
handleBlinkingLED();
} else {
float volts = analogRead(PH_SENSOR_PIN) * (5.0 / 1023.0);
volts -= v_offset; // aplicar offset da calibração
// Clamp para garantir range válido
volts = constrain(volts, -0.414, 0.414);
float ph = 7 - (volts * (7.0 / 0.414)); // conversão pH
lcd.setCursor(0, 0);
lcd.print("pH: ");
lcd.print(ph, 2);
lcd.print(" ");
}
delay(200);
}
void calibrate() {
lcd.setCursor(0, 1);
lcd.print("Calibrando...");
blinking = true;
delay(2000);
float volts = analogRead(PH_SENSOR_PIN) * (5.0 / 1023.0);
v_offset = volts; // salvar como tensão do pH 7
isCalibrated = true;
blinking = false;
setLED(0, 255, 0); // LED verde
lcd.setCursor(0, 1);
lcd.print("Calibrado! ");
}
void handleBlinkingLED() {
if (millis() - lastBlinkTime > 500) {
static bool ledOn = false;
ledOn = !ledOn;
if (ledOn) {
setLED(255, 0, 0);
} else {
setLED(0, 0, 0);
}
lastBlinkTime = millis();
}
}
void setLED(uint8_t r, uint8_t g, uint8_t b) {
analogWrite(RED_PIN, r);
analogWrite(GREEN_PIN, g);
analogWrite(BLUE_PIN, b);
}