我做了这个简单的例子,当启用复位触发计数器时,计数脉冲输入 TI1 和复位脉冲输入 TI2 给出随机数!
功能是这样的:
/* Select the TIM_SMCR_TS_1 signal as Input trigger for the TIM */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= TIM_SMCR_TS_1;
Use the TIM_SMCR_TS_1 to reset the TIM counter each edge detection */
htim->Instance->SMCR &= ~TIM_SMCR_SMS;
htim->Instance->SMCR |= TIM_SLAVEMODE_RESET;
代码:
#include "mbed.h"
#include "stm32f4xx.h"
#include "stm32f4xx_hal_tim_ex.h"
//direction to PA_9 -- step pulse to PA_8
uint16_t count1;
void pulsecount(void)
{
TIM_HandleTypeDef timer;
TIM_IC_InitTypeDef ICconfiginit;
TIM_ClockConfigTypeDef counter;
TIM_SlaveConfigTypeDef SlaveModeselect;
GPIO_InitTypeDef GPIO_InitStruct;
__TIM1_CLK_ENABLE();
__GPIOA_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
timer.Instance = TIM1;
timer.Init.Period = 0xffff;
timer.Init.Prescaler = 0;
timer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
timer.Init.CounterMode = TIM_COUNTERMODE_UP;
ICconfiginit.ICFilter = 0x0f;
ICconfiginit.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
ICconfiginit.ICPrescaler = TIM_ICPSC_DIV1;
ICconfiginit.ICSelection = TIM_ICSELECTION_DIRECTTI;
counter.ClockSource = TIM_CLOCKSOURCE_TI1;
counter.ClockFilter = 0x0f;
SlaveModeselect.SlaveMode = TIM_SLAVEMODE_RESET;
SlaveModeselect.InputTrigger = TIM_TS_TI2FP2;
HAL_TIM_IC_Init(&timer);
HAL_TIM_IC_ConfigChannel(&timer, &ICconfiginit, TIM_CHANNEL_1);
HAL_TIM_ConfigClockSource(&timer, &counter);
HAL_TIM_SlaveConfigSynchronization(&timer, &SlaveModeselect); ///<<< not reset
HAL_TIM_IC_Start(&timer, TIM_CHANNEL_1);
TIM1->EGR = 1; // Generate an update event
TIM1->CR1 = 1; // Enable the counter
}
int main()
{
pulsecount();
while (1) {
count1=TIM1->CNT;
printf("%d\r\n", count1);
wait(1.0);
};
}