Skip to content

Instantly share code, notes, and snippets.

@fxprime
Created April 21, 2025 06:38
Show Gist options
  • Save fxprime/b35457704279766ea647ccb8b1c84b4a to your computer and use it in GitHub Desktop.
Save fxprime/b35457704279766ea647ccb8b1c84b4a to your computer and use it in GitHub Desktop.
MEMO PROJECT (DROWSINESS DETECTOR DEVICE)
#ifndef __BATTERY_H__
#define __BATTERY_H__
#include <Arduino.h>
// ADC Configuration
#define BATTERY_PIN 34 // GPIO34 = ADC1_CH6
#define VOLTAGE_DIVIDER_RATIO 2.0 // 47kΩ / (47kΩ + 47kΩ) = 0.5 (so 1/0.5 = 2.0)
#define ADC_SAMPLES 20 // Must be odd number for true median
#define VOLTAGE_OFFSET 0.2463 // Offset for calibration
float read_battery_voltage() {
// Array to store multiple readings
int raw_values[ADC_SAMPLES] = {0};
// Take multiple samples
for (int i = 0; i < ADC_SAMPLES; i++) {
raw_values[i] = analogRead(BATTERY_PIN);
delay(1); // Small delay between readings
}
// Simple insertion sort for median
for (int i = 1; i < ADC_SAMPLES; i++) {
int temp = raw_values[i];
int j = i - 1;
while (j >= 0 && raw_values[j] > temp) {
raw_values[j+1] = raw_values[j];
j--;
}
raw_values[j+1] = temp;
}
// Get median value
int median_raw = raw_values[ADC_SAMPLES / 2];
// Convert to voltage (ESP32 ADC reference is 3.3V with 12-bit resolution = 4096)
float voltage = (median_raw * 3.3f) / 4095.0f;
// Apply voltage divider factor
voltage *= VOLTAGE_DIVIDER_RATIO;
// Optional: Apply calibration formula if you have one
voltage = voltage * 1.00005 + VOLTAGE_OFFSET; // Example calibration formula
if(voltage <VOLTAGE_OFFSET*1.1) {
voltage = 0;
}
return voltage;
}
void init_adc() {
// Configure ADC
analogReadResolution(12); // 12-bit resolution
analogSetPinAttenuation(BATTERY_PIN, ADC_11db); // For input up to 3.3V
}
#endif // __BATTERY_H__
#include <Arduino.h>
#include "battery.h"
#define VIBRATION_PIN 14 // GPIO14 for vibration motor control
void setup() {
Serial.begin(115200);
init_adc();
pinMode(VIBRATION_PIN, OUTPUT); // Set vibration pin as output
}
void loop() {
float voltage = read_battery_voltage();
static unsigned long last_print = 0;
if (millis() - last_print > 1000) { // Print every second
last_print = millis();
Serial.printf("Battery Voltage: %.2f V\n", voltage);
}
digitalWrite(VIBRATION_PIN, (millis() %3000<200 ? HIGH : LOW));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment