Arduino: modular structure

This commit is contained in:
Mikkeli Matlock
2026-01-25 19:05:17 +09:00
parent f51b165503
commit 6d043b7439
3 changed files with 50 additions and 24 deletions

View File

@@ -1,35 +1,19 @@
// Vehicle Voltage Monitor // Smart Serow - Main
// Reads 12V-14.4V battery via voltage divider on A0 // Motorcycle telemetry hub
// Outputs to Serial for PC monitoring
// Pin definitions #include "voltage.h"
const int PIN_VBAT = A0; // Vehicle voltage input (via divider)
// Voltage divider constants
// Divider: 100k upper (to Vin), 47k lower (to GND)
// Vout = Vin * (47k / (100k + 47k)) = Vin * 0.3197
// So Vin = Vout / 0.3197
// At 12V: ADC sees 3.84V | At 14.4V: ADC sees 4.60V
const float DIVIDER_RATIO = 47.0 / (100.0 + 47.0); // ~0.3197
const float ADC_REF = 5.0;
const int ADC_MAX = 1023;
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT); pinMode(LED_BUILTIN, OUTPUT);
voltage_init();
} }
void loop() { void loop() {
// Read and calculate voltage // Report battery voltage
int rawAdc = analogRead(PIN_VBAT); Serial.print("V_bat: ");
float vDivider = (rawAdc / (float)ADC_MAX) * ADC_REF; Serial.print(voltage_read(), 2);
float vBattery = vDivider / DIVIDER_RATIO;
// Output to serial
Serial.print("ADC: ");
Serial.print(rawAdc);
Serial.print(" | V_bat: ");
Serial.print(vBattery, 2);
Serial.println("V"); Serial.println("V");
// Heartbeat blink // Heartbeat blink

27
arduino/main/voltage.cpp Normal file
View File

@@ -0,0 +1,27 @@
#include "voltage.h"
// Pin definitions
static const int PIN_VBAT = A0;
// Voltage divider constants
// Divider: 100k upper (to Vin), 47k lower (to GND)
// Vout = Vin * (47k / (100k + 47k)) = Vin * 0.3197
// At 12V: ADC sees 3.84V | At 14.4V: ADC sees 4.60V
static const float DIVIDER_RATIO = 47.0 / (100.0 + 47.0); // ~0.3197
static const float ADC_REF = 5.0;
static const int ADC_MAX = 1023;
void voltage_init() {
// analogRead doesn't need explicit pinMode, but here for future config
// e.g., could switch to internal 1.1V reference for different range
}
int voltage_read_raw() {
return analogRead(PIN_VBAT);
}
float voltage_read() {
int raw = voltage_read_raw();
float vDivider = (raw / (float)ADC_MAX) * ADC_REF;
return vDivider / DIVIDER_RATIO;
}

15
arduino/main/voltage.h Normal file
View File

@@ -0,0 +1,15 @@
#ifndef VOLTAGE_H
#define VOLTAGE_H
#include <Arduino.h>
// Initialize voltage monitoring (call in setup)
void voltage_init();
// Read battery voltage, returns volts (e.g., 12.5)
float voltage_read();
// Read raw ADC value (0-1023)
int voltage_read_raw();
#endif