2020-02-08 12:47 AM
I am using stm32f103c8t6 and performing ADC sampling of voltage input 50 Hz from the mains. I have all hardware and PCB prepared. I am achieving 60 samples/cycle using DMA mode in ADC conversion. Now I would like to know the RMS calculation algorithm to be performed on it. Like exactly how to use timers with the ADC in order to get the full /half cycle rms. my sampling time is 252ms. I tried using one TIM3 as a time base generator and kept ADC . I am new to this coding in C. Please help me out as i am stuck in my ongoing project.
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
TIM_HandleTypeDef htim3;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM3_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
double val;
double vsqu;
double vsum;
float vrms;
int timer_value;
uint32_t adc_val;
uint32_t buffer;
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
for (int i=0; i<80; i++)
{
adc_val=buffer;
val = adc_val * (3.3/4096);
vsqu = pow (val,2);
vsum = vsum + vsqu;
}
vrms = sqrt((vsum/80));
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC1_Init();
MX_TIM3_Init();
/* USER CODE BEGIN 2 */
HAL_ADC_Start_DMA(&hadc1,&buffer,1);
HAL_TIM_Base_Start(&htim3);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
int timer_value = __HAL_TIM_GET_COUNTER(&htim3);
if (timer_value == 80)
{
vsum = 0;
timer_value = 0;
}
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL8;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV8;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV8;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief ADC1 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Common config
*/
hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc1.Init.ContinuousConvMode = ENABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
/**
* @brief TIM3 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM3_Init(void)
{
/* USER CODE BEGIN TIM3_Init 0 */
/* USER CODE END TIM3_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM3_Init 1 */
/* USER CODE END TIM3_Init 1 */
htim3.Instance = TIM3;
htim3.Init.Prescaler = 8000-1;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 80-1;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_ENABLE;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM3_Init 2 */
/* USER CODE END TIM3_Init 2 */
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2020-02-09 09:25 AM
Can you state what exactly the issue is with the above code?
Usually, when one needs a precise sampling rate, say 3000 Hz (50*60?), timer triggered ADC is used. There are other posts here discussing this in more detail. Next, I would not recommend using DMA until you really need it. Use HAL_ADC_Start_IT and you get an interrupt after each measurement. In the interrupt handler HAL_ADC_ConvCpltCallback, keep accumulating the sampled values fore the desired time span. At the end of each time span, trigger the desired action to output the result etc..
2020-02-09 09:43 PM
So you are suggesting using Interrupt Service routine. But i guess it will increase latency in the code. But let me check if it works! The issue is can you suggest me how to calculate RMS in the aboce code for 60 samples together. Like how to proceed with the calculation.
2020-02-09 09:44 PM
So you are suggesting using Interrupt Service routine. But i guess it will increase latency in the code. But let me check if it works! The issue is can you suggest me how to calculate RMS in the aboce code for 60 samples together. Like how to proceed with the calculation
2020-02-09 10:22 PM
You might consider a zero crossing detection to determine one full period of mains.
> I am using stm32f103c8t6 and performing ADC sampling of voltage input 50 Hz from the mains. I have all hardware and PCB prepared. I am achieving 60 samples/cycle using DMA mode in ADC conversion.
I would rather have choosen a multiple of 50, e.g. 100Hz.
However, with a proper ZX detection, you device works with 60Hz mains as well, and is more robust against EMI and phase shifts (dirty industrial and marine nets).
For RMS algorithms, just use you favorite search engine for example code and(or a tutorial. Those are not MCU/STM32 specific.
2020-02-10 01:00 AM
Thanks for your response. I am new to this coding part of project and hence knowing what is RMS and its algorithm i cant figure out how to deploy it in the code. Need help in that.
Also I am working on 50Hz Supply only. I am having 60 samples for every cycle in 1sec. so overall i am having 3000 smples per second.
2020-02-10 01:52 AM
In theory - assuming a clean mains - you could take any sequence of 60 samples (one complete period, ingoring any phase shift) and calculate the RMS value.
That is rarely the case, however. Heavy inductive loads and transients (switching of large reactive loads) will disturb the net.
When the simple relation U(RMS) = U(peak)/ sqrt(2) is no longer valid, just use theiterative method: sqrt (1/N * x(n)^2) for [1..n].
Technically, I would keep a ring buffer for two mains periods for doing the calculation.
For unloading the core, one could setup DMA for a 60 sample period, and copy the results to the ringbuffer upon the DMA Transfer Complete interrupt.
The calculation should be done in the main routine (meaning, not in interrupt context).
And, I would avoid using float variables on a M3 core. A scaled integer calculation will be at least as precise.
2020-02-10 05:11 AM
okay! some of the things i can understand but other i cant...like it will be much easier if you quote with an example or just edit in my code. Thanks for your response !
2020-02-10 05:30 AM
I don't speak the Cube/HAL gobbledygook.
But to achieve a 60Hz sampling rate, your ADC needs to be triggered every 20ms/60 = 333us. The timer should trigger at that period. Use a timer directly to trigger the ADC. Only a few timer modules are supported as ADC trigger, check the reference manual. CubeMX might reflect that fact ...
For DMA, I would setup a channel to transfer a full period, meaning 60 samples a 2 bytes, 120 words. Configuring a DMA TC interrupt, you get noticed when a sample of one period is ready. Don't process it in-place, DMA begins to overwrite it in the background.
Check a ref manual again, only a few DMA channels/tream combbinations are supported for specific peripherals. Again, CubeMX might reflect this fact.
> hadc1.Init.ContinuousConvMode = ENABLE;
> hadc1.Init.DiscontinuousConvMode = DISABLE;
> hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
> hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
> hadc1.Init.NbrOfConversion = 1;
This is not a good idea. ADC sampling time should reflect the hardware requirements (input impedance).
With continuous conversion + sampling time, you are very limited. As said above, use a timer as trigger directly.
2020-02-14 03:29 AM
Thanks for the help guys! I got my code running.