Timer除了可以作为一个基本的定时器之外,也可以作为一个PWM输出模块。
硬件:TG STK, 利用PD7 即 TIMER1, CC1, #4来输出一个PWM波形。
软件例程如下:
#include "efm32.h"
#include "efm32_cmu.h"
#include "efm32_emu.h"
#include "efm32_gpio.h"
#include "efm32_prs.h"
#include "efm32_system.h"
#include "efm32_timer.h"
#include "efm32_chip.h"
/* Define TOP value */
#define TOP 1000 //TOP值设置PWM的周期
#define HIGHPULSE 800 //HIGHPULSE设置占空比
/**************************************************************************//**
* @brief Main function
* Main is called from __iar_program_start, see assembly startup file
*****************************************************************************/
int main(void)
{
/* Initialize chip */
CHIP_Init();
/* Enable clock for GPIO module */
CMU_ClockEnable(cmuClock_GPIO, true);
/* Enable clock for TIMER0 module */
CMU_ClockEnable(cmuClock_TIMER1, true);
/* Set CC1 location 4 pin (PD7) as output */
GPIO_PinModeSet(gpioPortD, 7, gpioModePushPull, 0);
/* Select CC channel parameters */
TIMER_InitCC_TypeDef timerCCInit =
{
.eventCtrl = timerEventEveryEdge,
.edge = timerEdgeBoth,
.prsSel = timerPRSSELCh0,
.cufoa = timerOutputActionNone,
.cofoa = timerOutputActionNone,
.cmoa = timerOutputActionToggle,
.mode = timerCCModePWM,
.filter = false,
.prsInput = false,
.coist = false,
.outInvert = false,
};
/* Configure CC channel 1 */
TIMER_InitCC(TIMER1, 1, &timerCCInit);
/* Route CC1 to location 4 (PD7) and enable pin */
TIMER1->ROUTE |= (TIMER_ROUTE_CC1PEN | TIMER_ROUTE_LOCATION_LOC4);
/* Set Top Value */
TIMER_TopSet(TIMER1, TOP);
TIMER_CompareBufSet(TIMER1, 1, HIGHPULSE);
/* Select timer parameters */
TIMER_Init_TypeDef timerInit =
{
.enable = true,
.debugRun = true,
.prescale = timerPrescale64,
.clkSel = timerClkSelHFPerClk,
.fallAction = timerInputActionNone,
.riseAction = timerInputActionNone,
.mode = timerModeUp,
.dmaClrAct = false,
.quadModeX4 = false,
.oneShot = false,
.sync = false,
};
/* Configure timer */
TIMER_Init(TIMER1, &timerInit);
while(1)
{
}
}