I would like to ask about a voltage sensor using a voltage divider. I have a circuit as shown below, and I want to measure the voltage entering my circuit using the code below. However, I am uncertain because I am still a beginner and I need your guidance. What is lacking in this code, and am I doing something wrong? By the way, I also found this code from a reference, so I am confused when VREF is given as 3.3V. Is this the voltage from the MCU, or the voltage that I should provide (VCC), or what?
#include "main.h"
uint32_t adc_value = 0;
float voltage = 0.0;
#define R1 10000
#define R2 10000
#define VREF 3.3
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_ADC1_Init();
MX_TIM2_Init();
MX_USART1_UART_Init();
HAL_ADC_Start(&hadc1);
while (1)
{
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);
adc_value = HAL_ADC_GetValue(&hadc1);
voltage = (float)adc_value * VREF / 4095.0 * (R1 + R2) / R2;
char voltage_str[10];
sprintf(voltage_str, "%.2f V\n", voltage);
HAL_UART_Transmit(&huart1, (uint8_t *)voltage_str, strlen(voltage_str), HAL_MAX_DELAY);
HAL_Delay(1000);
}
}
I have tried, but I am unsure. I am using STM32CubeMX and Keil.
I want to read the voltage that goes into … but it seems that the size of the resistor I chose is incorrect because I am using the STM32F4 MCU. Now, what I doubt is whether the code is correct? I am quite confused; is there anyone who can explain the logic of how the circuit works?
You need to sign in to view this answers