50 lines
1.6 KiB
C
50 lines
1.6 KiB
C
|
#pragma once
|
||
|
|
||
|
#include "derivative.h"
|
||
|
|
||
|
#define PWMCLK 163828 // 20.97 MHz / 128
|
||
|
|
||
|
/*
|
||
|
@brief Timer / PWM Initialization
|
||
|
@param TPM (TPM0, TPM1, TPM2)
|
||
|
@param cha channel
|
||
|
*/
|
||
|
static inline void tpm_init(TPM_Type* TPM, uint8_t cha) {
|
||
|
SIM->SOPT2 |= SIM_SOPT2_TPMSRC(1); // MCGFLLCLK clock or MCGPLLCLK/2
|
||
|
SIM->SOPT2 &= ~SIM_SOPT2_PLLFLLSEL_MASK; // MCGFLLCLK clock
|
||
|
|
||
|
/*
|
||
|
CNT: Current Counter Value, 16 bits
|
||
|
MOD: Modulo Value, 16 bits -> Frequency
|
||
|
SC: Status and Control
|
||
|
CnSC: Channel (n) Status and Control
|
||
|
CnV: Channel (n) Value, 16 bits -> duty cycle
|
||
|
*/
|
||
|
if (TPM == TPM0) {
|
||
|
SIM->SCGC6 |= SIM_SCGC6_TPM0_MASK;
|
||
|
} else if (TPM == TPM1) {
|
||
|
SIM->SCGC6 |= SIM_SCGC6_TPM1_MASK;
|
||
|
} else if (TPM == TPM2) {
|
||
|
SIM->SCGC6 |= SIM_SCGC6_TPM2_MASK;
|
||
|
}
|
||
|
TPM->CNT = 0x0;
|
||
|
TPM->MOD = 0x0;
|
||
|
TPM->SC |= TPM_SC_CMOD(1) // LPTPM counter increments on every LPTPM counter clock
|
||
|
| TPM_SC_PS(7); // Prescaler Factor, Divide by 128
|
||
|
TPM->CONTROLS[cha].CnSC |= TPM_CnSC_ELSB(1) | TPM_CnSC_ELSA(0) // High-true pulses
|
||
|
| TPM_CnSC_MSB(1) | TPM_CnSC_MSA(0); // Edge-aligned PWM
|
||
|
TPM->CONTROLS[cha].CnV = 0x0;
|
||
|
}
|
||
|
|
||
|
/*
|
||
|
@brief Set the frequency and duty cycle of the PWM
|
||
|
@param TPM (TPM0, TPM1, TPM2)
|
||
|
@param mod modulo value -> frequency
|
||
|
@param val threshold value, when the count exceeds the threshold output toggles -> duty cycle
|
||
|
@param cha channel
|
||
|
*/
|
||
|
static inline void tpm_set(TPM_Type* TPM, uint16_t mod, uint16_t val, uint8_t cha) {
|
||
|
TPM->MOD = mod;
|
||
|
TPM->CONTROLS[cha].CnV = val;
|
||
|
}
|