STM8S---Timer generates PWM (TIM2)

Publisher:cyzceeLatest update time:2018-04-13 Source: eefocusKeywords:STM8S Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

1 Description

  • Use STM8S internal clock (HSI);

  • PWM mode 2;

  • The duty cycle is 50% and the frequency is 2Hz (convenient for testing LED lights);

  • PD2 port is connected to an external LED light, and PD2 port outputs PWM wave;

  • System clock initialization is very important: CLK_CKDIVR |= 0x08;

2 Code


/*

TIM2_CH3 PWM

PD2 output

*/

#include


void CLK_init(void)

{

    CLK_ICKR |= 0X01; //Enable internal high-speed clock HSI

    CLK_CKDIVR |= 0x08; //16M internal RC is divided by 2 and the system clock is 8M

    while(!(CLK_ICKR&0x02)); //HSI is ready 

    CLK_SWR=0xe1; //HSI is the main clock source 

}


void Init_Tim2(void)

{

    TIM2_CCMR3 |= 0X70; //Set the output comparison mode of timer 2 three channels (PD2)

    TIM2_CCMR3 |= 0X04; //Output compare 3 preload enable


    TIM2_CCER2 |= 0x03; //Channel 3 is enabled, low level is valid, and it is configured as output


    //Initialize the clock divider to 1, that is, the clock frequency of the counter is Fmaster=8M/64=0.125MHZ

    TIM2_PSCR = 0X06;   

    // Initialize the auto-load register to determine the frequency of the PWM square wave, Fpwm=0.125M/62500=2HZ

    TIM2_ARRH = 62500/256;

    TIM2_ARRL = 62500%256;

    // Initialize the comparison register to determine the duty cycle of the PWM square wave: 5000/10000 = 50%

    TIM2_CCR3H = 31250/256;

    TIM2_CCR3L = 31250%256;



    // Start counting; update interrupt disable

    TIM2_CR1 |= 0x81;

    //TIM2_IER |= 0x00;        

}


void Init_GPIO(void)

{

    /*Set to push-pull output, PD2 is connected to LED light*/

    PD_DDR |= 0X04; //Set PD2 port to output mode

    PD_CR1 |= 0X04; //Set PD2 port to push-pull output mode

    PD_CR2 &= 0XFD;


    PA_DDR |= 0X08; //Set PA3 port to output mode

    PA_CR1 |= 0X08; //Set PA3 port to push-pull output mode

    PA_CR2 |= 0XF7;

}


void main(void)

{

    CLK_init();

    Init_GPIO();

    Init_Tim2();

    while (1);

}


Keywords:STM8S Reference address:STM8S---Timer generates PWM (TIM2)

Previous article:STM8S---Independent button IO port setting and press event problem
Next article:STM8S---IO multiplexing configuration (STVP mode)

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号