// The Arduino standard library provides fundamental definitions and functions that make working with Arduino easier.
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Constants
const int IR_PIN = 2; // Pin connected to the IR sensor
const int OLED_RESET_PIN = 4; // Pin connected to the OLED reset
const int OLED_ADDRESS = 0x3C; // I2C address of the OLED display
// Variables
volatile unsigned long pulseCount = 0; // Number of pulses from the IR sensor
unsigned long lastPulseTime = 0; // Time of the last pulse from the IR sensor
unsigned long lastUpdateTime = 0; // Time of the last update to the OLED display
float speed = 0.0; // Speed in km/h
float rpm = 0.0; // Revolutions per minute
float batteryPercentage = 0.0; // Battery percentage for lithium-ion battery
// Objects
Adafruit_SSD1306 display(OLED_RESET_PIN);
/*
* Interrupt service routine for the IR sensor.
* Increments the pulse count and updates the last pulse time.
*/
void irSensorISR() {
pulseCount++;
lastPulseTime = micros();
}
/*
* Initializes the OLED display.
*/
void initializeDisplay() {
display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDRESS);
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Speed: 0.00 km/h");
display.setCursor(0, 10);
display.println("RPM: 0.00");
display.setCursor(0, 40);
display.println("Battery: 0.00%");
display.display();
}
/*
* Updates the speed, RPM, and battery percentage based on the pulse count and time.
*/
void updateData() {
unsigned long currentTime = micros();
unsigned long elapsedTime = currentTime - lastUpdateTime;
// Calculate speed in km/h
speed = (pulseCount * 2.25) / (elapsedTime / 1000000.0) * 3.6;
// Calculate RPM
rpm = (pulseCount * 60.0) / (elapsedTime / 1000000.0);
// Calculate battery percentage (dummy calculation)
batteryPercentage = analogRead(A0) * 100.0 / 1023.0;
// Reset pulse count and update time
pulseCount = 0;
lastUpdateTime = currentTime;
}
/*
* Updates the OLED display with the current speed, RPM, and battery percentage.
*/
void updateDisplay() {
display.clearDisplay();
display.setCursor(0, 0);
display.print("Speed: ");
display.print(speed, 2);
display.println(" km/h");
display.setCursor(0, 10);
display.print("RPM: ");
display.print(rpm, 2);
display.println();
display.setCursor(0, 40);
display.print("Battery: ");
display.print(batteryPercentage, 2);
display.println("%");
display.display();
}
void setup() {
Serial.begin(9600);
// Configure IR sensor pin as input
pinMode(IR_PIN, INPUT);
// Attach interrupt to the IR sensor pin
attachInterrupt(digitalPinToInterrupt(IR_PIN), irSensorISR, FALLING);
// Initialize OLED display
initializeDisplay();
// Set initial update time
lastUpdateTime = micros();
}
void loop() {
// Update data
updateData();
// Update display every 1 second
if (millis() - lastUpdateTime >= 1000) {
updateDisplay();
}
}