#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin not used (I2C interface)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define READ_INTERVAL 500 // Interval between sensor readings in milliseconds
#define NUM_READINGS 100 // Number of readings to store for a 10-second average (100 readings at 100ms intervals)
int readings[NUM_READINGS]; // Array to store sensor readings
int readIndex = 0; // Index of the current reading
long total = 0; // Sum of the readings
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud
// SSD1306 display initialization
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Initialize readings array with 0s
for (int i = 0; i < NUM_READINGS; i++) {
readings[i] = 0;
}
// Clear the buffer
display.clearDisplay();
// Display initial message
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Sensor Reading:");
display.display();
delay(2000); // Pause for 2 seconds
}
void loop() {
// Read the resistance from the potentiometer (simulating sensor)
int sensorValue = analogRead(A0); // Read analog input from pin A0
// Update the rolling sum and replace the oldest reading
total = total - readings[readIndex]; // Subtract the oldest reading from the total
readings[readIndex] = sensorValue; // Store the new reading
total = total + readings[readIndex]; // Add the new reading to the total
// Advance to the next position in the readings array
readIndex = (readIndex + 1) % NUM_READINGS;
// Calculate the average value over the last 10 seconds
float average = total / (float)NUM_READINGS;
// Map the sensor value (range 0 to 1023) to percentage (0% to 100%)
float percentage = map(sensorValue, 0, 1023, 0, 100);
float avgPercentage = map(average, 0, 1023, 0, 100);
// Clear the previous content
display.clearDisplay();
// Print sensor resistance and percentage on OLED display
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 10);
display.print("Resistance:");
display.setCursor(0, 20);
display.print(sensorValue);
display.setCursor(0, 30);
display.print("Percentage:");
display.setCursor(0, 40);
display.print(percentage);
display.print("%");
display.setCursor(0, 50);
display.print("Avg (10 sec):");
display.setCursor(0, 60);
display.print(avgPercentage);
display.print("%");
// Display the content
display.display();
// Delay to match the read interval
delay(READ_INTERVAL);
}