#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
int sensorPin = A0; // Analog input pin for the potentiometer (hydration sensor)
int ledPin = 13; // Digital output pin for the built-in LED
int readings[10]; // Array to store the last 10 hydration readings
int currentIndex = 0; // Current index in the readings array
int total = 0; // Running total of hydration readings
int average = 0; // Calculated average hydration level
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
// Initialize OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
// Initialize readings array
for (int i = 0; i < 10; i++) {
readings[i] = 0;
}
}
void loop() {
int sensorValue = analogRead(sensorPin); // Read the simulated hydration level from the potentiometer
// Map the sensor value to a hydration level (0-100%)
int hydrationLevel = map(sensorValue, 0, 1023, 0, 100);
// Subtract the last reading from the total
total = total - readings[currentIndex];
// Add the current reading to the total
readings[currentIndex] = hydrationLevel;
total = total + readings[currentIndex];
// Advance to the next position in the array
currentIndex = currentIndex + 1;
// If we're at the end of the array, wrap around to the beginning
if (currentIndex >= 10) {
currentIndex = 0;
}
// Calculate the average
average = total / 10;
// Print the hydration level and average to the serial monitor
Serial.print("Hydration Level: ");
Serial.println(hydrationLevel);
Serial.print("Average Hydration: ");
Serial.println(average);
// Display the hydration level and average on the OLED
display.clearDisplay();
display.setTextSize(1); // Display text size
display.setTextColor(SSD1306_WHITE); // Display text color
display.setCursor(0,10); // Display text starting position
display.print("Hydration: ");
display.print(hydrationLevel);
display.print("%");
display.setCursor(0, 30);
display.print("Average: ");
display.print(average);
display.print("%");
// If hydration level is below the average, indicate on the display and turn on the LED
if (hydrationLevel < average) {
display.setCursor(0, 50);
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.print("Hydration Low!");
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
display.setCursor(0, 50);
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.print("Hydration Normal");
digitalWrite(ledPin, LOW); // Turn off the LED
}
display.display(); // Show the display
delay(1000); // Delay for 1 second before next reading
}