diff --git a/application.c b/application.c index 17e7489..5f02c62 100644 --- a/application.c +++ b/application.c @@ -11,6 +11,7 @@ #include // string utilities #include // date/time utilities #include // utilities to check chars +#include // rounding utilities /* STM32 (including CM3) libraries */ #include // Cortex M3 utilities @@ -51,6 +52,10 @@ static volatile bool second_flag = false; /**< flag set when a second passed */ /** number of seconds since boot */ static uint32_t boot_time = 0; +#define TARGET_CHANNEL 1 /**< PA1/ADC1_IN1 used to measure target voltage */ +#define SIGNAL_CHANNEL 2 /**< PA2/ADC1_IN2 used to measure signal voltage */ +const uint8_t channels[] = {ADC_CHANNEL17, ADC_CHANNEL(TARGET_CHANNEL), ADC_CHANNEL(SIGNAL_CHANNEL)}; /**< voltages to convert (channel 17 = internal voltage reference) */ + size_t putc(char c) { size_t length = 0; // number of characters printed @@ -69,9 +74,29 @@ size_t putc(char c) return length; // return number of characters printed } -#define TARGET_CHANNEL 1 /**< PA1/ADC1_IN1 used to measure target voltage */ -#define SIGNAL_CHANNEL 2 /**< PA2/ADC1_IN2 used to measure signal voltage */ -const uint8_t channels[] = {ADC_CHANNEL17, ADC_CHANNEL(TARGET_CHANNEL), ADC_CHANNEL(SIGNAL_CHANNEL)}; /**< voltages to convert (channel 17 = internal voltage reference) */ +/** print voltage with fixed precision + * @param[in] voltage voltage to print + * @param[in] precision number of digits after comma to print + * @note %f is used to force scientific notation + */ +static void print_voltage(double voltage, uint8_t precision) +{ + uint32_t multiplier = 1; + for (uint8_t i = 0; i < precision; i++) { + multiplier *= 10; + } + double to_print = round(voltage * multiplier); + printf("%d.", (int32_t)to_print / multiplier); + char decimal[32]; + snprintf(decimal, LENGTH(decimal), "%u", abs(to_print) % multiplier); + if (strlen(decimal) > precision) { + decimal[precision] = 0; + } + for (uint8_t i = strlen(decimal); i < precision; i++) { + putc('0'); + } + puts(decimal); +} /** measure target and signal voltages * @return voltages of channels @@ -129,8 +154,16 @@ static void command_voltages(void* argument) (void)argument; // we won't use the argument float* voltages = measure_voltages(); // measure voltages puts("voltages:\n"); - printf("- target: %.02f V\n", (uint32_t)(voltages[1] * 100) / 100.0); - printf("- signal: %.02f V\n", (uint32_t)(voltages[2] * 100) / 100.0); + puts("- target: "); + print_voltage(voltages[1], 2); + puts(" V\n"); + if (voltages[2] >= 3.25) { + puts("- signal: >= 3.30 V\n"); + } else { + puts("- signal: "); + print_voltage(voltages[2], 2); + puts(" V\n"); + } } /** display available commands