2023-12-10 06:52 AM - edited 2023-12-10 06:58 AM
Hi all, I am new to stm32cube ide and this is my first project. I am currently working on stm32f103c8. I am taking the input from ADC1 pin PA0 which is connected to a potentiometer. I am controlling LEDs through a potentiometer and a button. The problem I am facing is that the value of the potentiometer is not being read. I have also shared the code below.
/* USER CODE BEGIN 0 */
uint32_t adcVal;
/* USER CODE END 0 */
while (1)
{
//HAL_ADC_Start_IT (&hadc1);
if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_1) == 0)
{
HAL_ADC_Start_IT(&hadc1);
if (adcVal > 2048)
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_3);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET);
}
else
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_2);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_SET);
}
HAL_Delay(200);
//HAL_ADC_Start_IT (&hadc1);
}
else
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_RESET);
}
/* USER CODE BEGIN 4 */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
adcVal = HAL_ADC_GetValue(&hadc1);
}
The problem I am facing is in the while loop part in the second if and else statement where I have given the commands to toggle respective LEDs. Only the else statement is being used. The value from hadc1 is not being compared.
if (adcVal > 2048)
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_3);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET);
}
This part does not seem to work. can someone please share as to where I am going wrong
2023-12-10 07:14 AM
Use polling and get the value as in the example here:
You can use interrupts, but then you need to wait for the operation to complete before using the value. Your current code doesn't wait at all.
2023-12-10 11:17 PM
Hi @TDK I did try as you suggested but the error still persists.
I have also shared the code with the modifications I made as you suggested through the link.
while (1)
{
HAL_ADC_Start(&hadc1);
if (HAL_ADC_PollForConversion(&hadc1,10) != HAL_TIMEOUT)
{
adc_val = HAL_ADC_GetValue(&hadc1);
if ((adc_val>0) && (adc_val <2048))
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_3);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET);
}
else
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_2);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_SET);
}
return adc_val;
}
else
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_3, GPIO_PIN_RESET);
}