#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Relay class to control the relay
class Relay {
private:
int pin;
public:
// Constructor to initialize relay pin
Relay(int relayPin) {
pin = relayPin;
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW); // Initialize relay as OFF
}
// Method to turn relay ON
void turnOn() {
digitalWrite(pin, HIGH);
Serial.println("Relay is ON");
}
// Method to turn relay OFF
void turnOff() {
digitalWrite(pin, LOW);
Serial.println("Relay is OFF");
}
};
// BreathRate class to calculate breaths per minute based on relay state changes
class BreathRate {
private:
int breathCount;
unsigned long startTime;
LiquidCrystal_I2C& lcd; // Reference to the LCD object
public:
// Constructor to initialize variables and LCD reference
BreathRate(LiquidCrystal_I2C& lcdRef)
: lcd(lcdRef), breathCount(0), startTime(0) {}
// Method to start the timer for 60 seconds
void startCounting() {
startTime = millis(); // Record the start time
breathCount = 0; // Reset the breath count
Serial.println("Breath counting started...");
}
// Method to update breath count when relay is toggled
void countBreath() {
breathCount++; // Increase breath count with each relay ON
}
// Method to check and display breaths per minute after 60 seconds
void displayBreathRate() {
// Check if [*] seconds have passed
if (millis() - startTime >= 15000) {
// Display breaths per minute on LCD
lcd.setCursor(0, 1);
lcd.print("Breaths: ");
lcd.print(breathCount);
Serial.print("Breaths per 15 seconds: ");
Serial.println(breathCount);
// Restart breath counting for another 60 seconds
startCounting();
}
}
};
Relay relay1(7); // Initialize relay on pin 7
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize LCD (I2C: Address 0x27, Pins: SDA, SCL)
BreathRate breathCounter(lcd); // Initialize breath rate with LCD reference
void setup() {
Serial.begin(9600);
// Setup LCD
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Breaths per Min:");
// Start breath counting
breathCounter.startCounting();
}
void loop() {
// Example: Turn relay ON and count as a breath, then OFF after delay
relay1.turnOn();
breathCounter.countBreath(); // Count each relay ON as a breath
delay(1000); // Simulate 1-second delay for relay ON
relay1.turnOff();
delay(1000); // Simulate 1-second delay for relay OFF
// Check and display breaths per minute
breathCounter.displayBreathRate();
}