cancel
Showing results for 
Search instead for 
Did you mean: 

How to read ADC on B-L475E board

JMerr.1
Associate II

I simply want to read A0 analog pin through terminal on Truestudio however after weeks of trying I need help. My step-by-step guide on what I have done is below:

In STM32CubeMX I initialised all peripherals.

I set PA0 as ADC1_IN5. I initialised ADC1_IN5 as single ended.

I set PA10 as GPIO_Output.

I enable USART2 as asynchronous.

I export to truestudio.

The code I add is as follows:

#include <string.h>

#include <stdio.h>

 /* USER CODE BEGIN 1 */

uint16_t raw;

char msg[10];

 /* USER CODE END 1 */

 while (1)

 {

  /* USER CODE END WHILE */

 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);

 HAL_ADC_Start(&hadc1);

 HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);

 raw = HAL_ADC_GetValue(&hadc1);

 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);

 sprintf(msg, "%hu\r\n", raw);

 HAL_UART_Transmit(&huart2, (uint8_t*)msg, strlen(msg), HAL_MAX_DELAY);

  /* USER CODE BEGIN 3 */

 HAL_Delay(1);

  /* USER CODE BEGIN 3 */

 }

There are no error messages with this code. However, nothing prints on the terminal. Any explanations would be greatly appreciated 🙂 I am new to TrueStudio.

Have a nice day!

2 REPLIES 2
Mohamed Aymen HZAMI
ST Employee

Hello,

Try to add this function to your code :

#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
 
 
 
/***********************************************************************/
 
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the terminale and Loop until the end of transmission */
  HAL_UART_Transmit(&UARTHandle, (uint8_t *)&ch, 1, 0xFFFF); 
 
  return ch;
}

Best Regards,

Mohamed Aymen.

Hello Mohamed,

Thank you very much for the response.

I have not used the 'fputc' function before and I have just watched some videos to try and understand.

I am not sure how to use this method to read the analog pin continuously? It seems as though it saves the data to a file (though this will be useful in future). How do I replace the character with A0 and loop continuously?

kind regards,

Jacob