0
votes

I am new user of STM32(L476RG).I've done some work with Arduino so far. Now,I want to read ADC Value and transmit this value with UART. I setup hardware part and initial software configuration part. I want to know, this part of code in while loop is correct?

if (HAL_ADC_PollForConversion(&hadc1, 1000000) == HAL_OK)
{
    ADCValue = HAL_ADC_GetValue(&hadc1);
    sprintf(str, "%d", ADCValue);
    HAL_UART_Transmit(&huart2,ADCValue,1,100);
}
2

2 Answers

1
votes

Assuming that you callHAL_ADC_Start(&hadc1) before entering the while loop. Basically it is OK to call you code in a while loop, but I have some remarks.

Make sure that ADCValue variable is uint32_t or at least uin16_t as the return value of HAL_ADC_GetValue is uint32_t. If the ADC's resolution is above 8 bit then 1 byte won't be enough to store the result.

HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout);

The HAL_UART_Transmit expects an uint8_t* as a second parameter, given your code you pass a simple variable. You should use the & operator before ADCValue and cast it to uint8_t*. Also it only sends 1 byte in your code, based on the third parameter. If ADCValue is uint32_t then you should modify this parameter to 4. Also note that you send raw byte value and not ASCII. All in all:

uint32_t ADCValue;

if (HAL_ADC_PollForConversion(&hadc1, 1000000) == HAL_OK)
{
    ADCValue = HAL_ADC_GetValue(&hadc1);
    sprintf(str, "%d", ADCValue);
    HAL_UART_Transmit(&huart2, (uint8_t*)(&ADCValue), 4, 100);
}

(&ADCValue) returns the address of ADCValue which is an uint32_t* so it should be casted to uint8_t* when passing to HAL_UART_Transmit. And as an uint32_t is 4 byte, third param should be 4.

If you want to send the str you should calculate its correct length before sending as well.

By the way here is an ADC example from this STM32 HAL ADC Tutorial.

uint32_t g_ADCValue;    
int g_MeasurementNumber;


int main(void)
{
    HAL_Init();
    SystemClock_Config();
    ConfigureADC();

    HAL_ADC_Start(&g_AdcHandle);
    for (;;)
    {
        if (HAL_ADC_PollForConversion(&g_AdcHandle, 1000000) == HAL_OK)
        {
            g_ADCValue = HAL_ADC_GetValue(&g_AdcHandle);
            g_MeasurementNumber++;
        }
    }
}
-1
votes

What I did as the simplest working solution was to force an ADC reset:

HAL_StatusTypeDef stat = HAL_ADC_PollForConversion(&hadc1, 900);

if (stat != HAL_OK)  {
    HAL_ADC_Stop(&hadc1);
    HAL_ADC_Start(&hadc1);
}

This should be executed earlier than just before GetValue, I had improper action then.

P.S. Sorry for poor visibility

Slightly more elegant would be stopping after GetValue function, yet I left this code as properly working.