diff --git a/firmware/Makefile b/firmware/Makefile index 4679682..cc12eaa 100644 --- a/firmware/Makefile +++ b/firmware/Makefile @@ -119,9 +119,10 @@ CSRC = $(ALLCSRC) cfg/board.c # C++ sources that can be compiled in ARM or THUMB mode depending on the global # setting. CPPSRC = $(ALLCPPSRC) \ - pwm.cpp \ + analog_input.cpp \ can.cpp \ can_helper.cpp \ + pwm.cpp \ main.cpp # List ASM source files here. diff --git a/firmware/analog_input.cpp b/firmware/analog_input.cpp new file mode 100644 index 0000000..803e075 --- /dev/null +++ b/firmware/analog_input.cpp @@ -0,0 +1,41 @@ +#include "analog_input.h" + +#include "hal.h" + +#define ADC_OVERSAMPLE 8 + +static adcsample_t adcBuffer[3 * ADC_OVERSAMPLE]; + +ADCConversionGroup convGroup = +{ + false, 3, nullptr, nullptr, + 0, // CFGR1 + ADC_TR(0, 0), // TR + ADC_SMPR_SMP_28P5, // SMPR + ADC_CHSELR_CHSEL0 | ADC_CHSELR_CHSEL1 | ADC_CHSELR_CHSEL2 +}; + +static float AverageSamples(adcsample_t* buffer, size_t idx) +{ + uint32_t sum = 0; + + for (size_t i = 0; i < ADC_OVERSAMPLE; i++) + { + sum += buffer[idx]; + idx += ADC_OVERSAMPLE; + } + + return (float)sum / ADC_OVERSAMPLE; +} + +AnalogResult AnalogSample() +{ + adcConvert(&ADCD1, &convGroup, adcBuffer, ADC_OVERSAMPLE); + + return + { + .NernstVoltage = AverageSamples(adcBuffer, 0), + .VirtualGroundVoltage = AverageSamples(adcBuffer, 1), + .PumpCurrentVoltage = AverageSamples(adcBuffer, 2), + }; +} diff --git a/firmware/analog_input.h b/firmware/analog_input.h new file mode 100644 index 0000000..7f25e61 --- /dev/null +++ b/firmware/analog_input.h @@ -0,0 +1,10 @@ +#pragma once + +struct AnalogResult +{ + float NernstVoltage; + float VirtualGroundVoltage; + float PumpCurrentVoltage; +}; + +AnalogResult AnalogSample(); diff --git a/firmware/main.cpp b/firmware/main.cpp index 7184207..806e80e 100644 --- a/firmware/main.cpp +++ b/firmware/main.cpp @@ -1,6 +1,7 @@ #include "ch.h" #include "hal.h" +#include "analog_input.h" #include "can.h" #include "pwm.h" @@ -14,7 +15,7 @@ Pwm pumpDac(PWMD3, 1, 48000000, 1024); /* * Application entry point. */ -int main(void) { +int main() { halInit(); chSysInit(); @@ -27,6 +28,8 @@ int main(void) { pumpDac.SetDuty(0.4f); while (true) { + auto result = AnalogSample(); + // dummy data SendCanData(0.5f, 300); chThdSleepMilliseconds(10);