#include "stm32f4xx.h"
void TIM4_PWM_config(void);
int main(void){
	TIM4_PWM_config();
	while(1){
	}
}
/***************************************************/
void TIM4_PWM_config(void){
	GPIO_InitTypeDef          GPIO_InitStruct;
	TIM_OCInitTypeDef         TIM_OCInitStruct;
	TIM_TimeBaseInitTypeDef   TIM_TimeBaseInitStruct;
	uint16_t TIM4_counter_clock = 10000; // 10 kHz
	uint16_t TIM4_Period = (TIM4_counter_clock/1) - 1;
	
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_12;
	GPIO_Init(GPIOD, &GPIO_InitStruct);
	GPIO_PinAFConfig(GPIOD, GPIO_PinSource12, GPIO_AF_TIM4);

	TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStruct.TIM_Prescaler = ( (SystemCoreClock/2)/TIM4_counter_clock ) - 1; // TIM4->PSC = 8399 // Get TIM4_counter_clock to 10 kHz on STM32F407
	TIM_TimeBaseInitStruct.TIM_Period = TIM4_Period;                                       // TIM4->ARR = 9999 // 1 Hz for 10 kHz prescaled
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStruct);
	
	TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_Pulse = ((TIM4_Period + 1) * 0.5) - 1; // TIM4->CCR1 = 4999
	TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC1Init(TIM4, &TIM_OCInitStruct);
	
	TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);
	
	TIM_Cmd(TIM4, ENABLE);
}