// This code was written by some shmo on the internet who don't know shit about anything.
// Use at your own risk.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Bounce2.h>
// Calibrate the A0 Analogue input
// Very important to do this! My AFR was off by 0.3 out the box.
float gain = 1;
float offset = 0;
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int buttonPin = 2;
const int analogPin = A0;
bool isReading = false;
float sumAFR = 0;
int count = 0;
unsigned long previousMillis = 0;
const int sampleInterval = 50; // 50ms interval for ~20Hz sampling
Bounce button = Bounce();
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("HELLO WORLD");
delay(1000);
pinMode(buttonPin, INPUT_PULLUP);
button.attach(buttonPin);
button.interval(5); // Debounce delay in milliseconds
}
void loop() {
button.update();
// Toggle reading state on button press
if (button.fell()) { // Detect button press event after debounce
isReading = !isReading;
if (!isReading) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Avg AFR: ");
lcd.setCursor(10, 0);
lcd.print(sumAFR / count); // Display final average
sumAFR = 0;
count = 0;
}
}
// Take samples and update average
if (isReading) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= sampleInterval) {
previousMillis = currentMillis;
float afrValue = (((analogRead(analogPin) * (10 / 1023.0))+10)*gain) + offset;
sumAFR += afrValue;
count++;
lcd.setCursor(0, 1);
lcd.print("CurrentAFR:");
lcd.setCursor(11, 1);
lcd.print(afrValue);
}
}
}