#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display width and height
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// OLED reset pin (if required)
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Fuel sensor pin
const int fuelSensorPin = A0;
// Resistance values (in ohms)
const float fullResistance = 20.0;
const float emptyResistance = 220.0;
// Voltage divider reference resistor value (in ohms)
const float referenceResistor = 1000.0; // Example: 1k ohm resistor
// Variables for averaging
const int numReadings = 60; // Number of readings for 1-minute average
float readings[numReadings];
int readIndex = 0;
float total = 0;
float average = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Initialize the OLED display
}
// Clear and display a welcome message
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Fuel Level Monitor");
display.display();
delay(2000);
// Initialize readings array
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
// Read the analog value from the sensor
int sensorValue = analogRead(fuelSensorPin);
// Convert the analog value to resistance
float voltage = sensorValue * (5.0 / 1023.0); // Assuming 5V reference
float resistance = (referenceResistor * (5.0 - voltage)) / voltage;
// Map the resistance to a fuel level percentage
float fuelLevel = map(resistance, fullResistance, emptyResistance, 100, 0);
fuelLevel = constrain(fuelLevel, 0, 100); // Ensure the value stays within 0-100%
// Update the readings array for averaging
total -= readings[readIndex]; // Subtract the oldest reading
readings[readIndex] = fuelLevel; // Store the new reading
total += readings[readIndex]; // Add the new reading to the total
readIndex = (readIndex + 1) % numReadings; // Advance to the next position
// Calculate the average
average = total / numReadings;
// Print the values to the Serial Monitor
Serial.print("Resistance (Ohms): ");
Serial.print(resistance);
Serial.print(" | Fuel Level (%): ");
Serial.print(fuelLevel);
Serial.print(" | Average Fuel Level (%): ");
Serial.println(average);
// Display the fuel level on the OLED
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Fuel Level Monitor");
display.setTextSize(2);
display.setCursor(0, 20);
display.print("Fuel: ");
display.print(average);
display.println("%");
display.display();
// Small delay for readability
delay(1000);
}