cancel
Showing results for 
Search instead for 
Did you mean: 

STM32F103C8T6 PWM Generation

Falco Femoralis
Associate II

How to generate PWM so that the LED lights up for 5 seconds? Now, my LED is just blinking. I watched a lot of tutorials, but I don't know where I'm wrong. I need help...

My code:

#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_tim.h"
 
#define Period 0xffff
#define Pulse 0
 
int main()
{
	    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
 
		//PB1
		GPIO_InitTypeDef pwmGPIO;
		pwmGPIO.GPIO_Pin = GPIO_Pin_1;
		pwmGPIO.GPIO_Mode = GPIO_Mode_AF_PP;
		pwmGPIO.GPIO_Speed = GPIO_Speed_50MHz;
		GPIO_Init(GPIOB, &pwmGPIO);
 
		// TIM3, channel 4
		TIM_TimeBaseInitTypeDef pwm;
		TIM_OCInitTypeDef pwmOC;
 
		pwm.TIM_Period = Period;
		pwm.TIM_Prescaler = (SystemCoreClock / 4800000) - 1;
		pwm.TIM_ClockDivision = 0;
		pwm.TIM_CounterMode = TIM_CounterMode_Up;
		TIM_TimeBaseInit(TIM3, &pwm);
 
		pwmOC.TIM_OCMode = TIM_OCMode_PWM1;
		pwmOC.TIM_OutputState = TIM_OutputState_Enable;
		pwmOC.TIM_Pulse = Pulse;
		pwmOC.TIM_OCPolarity = TIM_OCPolarity_High;
 
		TIM_OC4Init(TIM3, &pwmOC);
		TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
		TIM_ARRPreloadConfig(TIM3, ENABLE);
		TIM_Cmd(TIM3, ENABLE);
 
  while(1)
  {
	  for(int i=0;i<5000;i++){
		  TIM_SetCompare4(TIM3, i);
	  }
  }
}

1 ACCEPTED SOLUTION

Accepted Solutions
Falco Femoralis
Associate II

I found out what is wrong, Unfortunately my controller not working properly :( tested on another one, working well

View solution in original post

4 REPLIES 4

> for(int i=0;i<5000;i++){

> TIM_SetCompare4(TIM3, i);

> }

What is this supposed to do? Mind, the PWM period is something like 1/72 seconds, and this loop writes the compare register like half a million times during that time.

For starter, you want something more like:

while(1) {

TIM_SetCompare4(TIM3, 0 * Period / 4);

Delay1Second();

TIM_SetCompare4(TIM3, 1 * Period / 4);

Delay1Second();

TIM_SetCompare4(TIM3, 2 * Period / 4);

Delay1Second();

TIM_SetCompare4(TIM3, 3 * Period / 4);

Delay1Second();

TIM_SetCompare4(TIM3, 4 * Period / 4);

Delay1Second();

}

JW

It didn't help, the LED is still blinking :(

Falco Femoralis
Associate II

I found out what is wrong, Unfortunately my controller not working properly :( tested on another one, working well

Thanks for coming back with the solution.

Please select your post as Best so that the thread is marked as solved.

JW