144 lines
2.7 KiB
C
144 lines
2.7 KiB
C
/*
|
|
* TIM_InputCapture.c
|
|
*
|
|
* Created on: Jun 30, 2020
|
|
* Author: matth
|
|
*/
|
|
|
|
#include "TIM_InputCapture.h"
|
|
|
|
static TIM_InputCapture_t *root = NULL;
|
|
|
|
int TIM_InputCapture_open(TIM_InputCapture_t *e, TIM_HandleTypeDef *tim, HAL_TIM_ActiveChannel channel,uint32_t Channel)
|
|
{
|
|
e->channel = channel;
|
|
e->tim = tim;
|
|
e->next_ptr = NULL;
|
|
|
|
e->cnt = 0;
|
|
e->pps = 0;
|
|
|
|
if (root)
|
|
{
|
|
TIM_InputCapture_t *last = root;
|
|
while (last->next_ptr)
|
|
{
|
|
last = last->next_ptr;
|
|
}
|
|
last->next_ptr = e;
|
|
}
|
|
else
|
|
{
|
|
root = e;
|
|
}
|
|
|
|
if (HAL_TIM_IC_Start_IT(tim, Channel) != HAL_OK)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
|
|
{
|
|
uint32_t cur_tick;
|
|
uint32_t ch;
|
|
if (root)
|
|
{
|
|
TIM_InputCapture_t *cur = root;
|
|
while (cur)
|
|
{
|
|
if (cur->tim == htim && cur->channel == htim->Channel)
|
|
{
|
|
cur->cnt++;
|
|
switch (htim->Channel)
|
|
{
|
|
case HAL_TIM_ACTIVE_CHANNEL_1:
|
|
ch = TIM_CHANNEL_1;
|
|
break;
|
|
case HAL_TIM_ACTIVE_CHANNEL_2:
|
|
ch = TIM_CHANNEL_2;
|
|
break;
|
|
case HAL_TIM_ACTIVE_CHANNEL_3:
|
|
ch = TIM_CHANNEL_3;
|
|
break;
|
|
case HAL_TIM_ACTIVE_CHANNEL_4:
|
|
ch = TIM_CHANNEL_4;
|
|
break;
|
|
default:
|
|
return;
|
|
}
|
|
cur_tick = HAL_TIM_ReadCapturedValue(htim, ch);
|
|
cur->delta_tick = cur_tick - cur->last_tick;
|
|
if (cur->delta_tick < 0)
|
|
{
|
|
cur->delta_tick = 0xffff + cur->delta_tick;
|
|
}
|
|
if (cur->delta_tick > 1)
|
|
{
|
|
cur->pps_acc1 = 1000000/cur->delta_tick;
|
|
}
|
|
else
|
|
{
|
|
cur->pps_acc1 = 0;
|
|
}
|
|
cur->pps_acc = (4*cur->pps_acc+cur->pps_acc1)/5;
|
|
cur->last_tick = cur_tick;
|
|
break;
|
|
}
|
|
cur = cur->next_ptr;
|
|
}
|
|
}
|
|
/*
|
|
if (Is_First_Captured==0) // is the first value captured ?
|
|
{
|
|
IC_Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); // capture the first value
|
|
Is_First_Captured =1; // set the first value captured as true
|
|
}
|
|
else if (Is_First_Captured) // if the first is captured
|
|
{
|
|
IC_Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); // capture second value
|
|
|
|
if (IC_Value2 > IC_Value1)
|
|
{
|
|
Difference = IC_Value2-IC_Value1; // calculate the difference
|
|
}
|
|
|
|
else if (IC_Value2 < IC_Value1)
|
|
{
|
|
Difference = ((0xffff-IC_Value1)+IC_Value2) +1;
|
|
}
|
|
|
|
else
|
|
{
|
|
Error_Handler();
|
|
}
|
|
|
|
Frequency = HAL_RCC_GetPCLK1Freq()/Difference; // calculate frequency
|
|
Is_First_Captured = 0; // reset the first captured
|
|
}
|
|
*/
|
|
|
|
}
|
|
|
|
void TIM_InputCapture_stats(void)
|
|
{
|
|
if (root)
|
|
{
|
|
TIM_InputCapture_t *cur = root;
|
|
while (cur)
|
|
{
|
|
cur->pps = cur->cnt;
|
|
if (cur->cnt < 1)
|
|
{
|
|
cur->delta_tick = 0u;
|
|
cur->pps_acc1 = 0;
|
|
cur->pps_acc = 0;
|
|
}
|
|
cur->cnt = 0;
|
|
cur = cur->next_ptr;
|
|
}
|
|
}
|
|
}
|