FastPWM library, modified by benkatz
Dependents: WangBoard_MotorScience
Fork of FastPWM3 by
FastPWM_KSDK.cpp
00001 #if defined(TARGET_KPSDK_MCUS) 00002 00003 #include "FastPWM.h" 00004 #include "fsl_clock_manager.h" 00005 00006 00007 #define PWM_CNV (*(((fastpwm_struct*)fast_obj)->CnV)) 00008 #define PWM_MOD (*(((fastpwm_struct*)fast_obj)->MOD)) 00009 #define PWM_SC (*(((fastpwm_struct*)fast_obj)->SC)) 00010 00011 typedef struct { 00012 __IO uint32_t *CnV; 00013 __IO uint32_t *MOD; 00014 __IO uint32_t *SC; 00015 } fastpwm_struct; 00016 00017 static uint32_t pwm_prescaler; 00018 00019 void FastPWM::initFastPWM( void ) { 00020 fast_obj = new fastpwm_struct; 00021 bits = 16; 00022 00023 uint32_t pwm_base_clock; 00024 CLOCK_SYS_GetFreq(kBusClock, &pwm_base_clock); 00025 pwm_prescaler = SystemCoreClock / pwm_base_clock; 00026 00027 uint32_t ftms[] = FTM_BASE_ADDRS; 00028 unsigned int ch_n = (_pwm.pwm_name & 0xFF); 00029 FTM_Type *ftm = (FTM_Type *)ftms[_pwm.pwm_name >> TPM_SHIFT]; 00030 00031 ((fastpwm_struct*)fast_obj)->CnV = &ftm->CONTROLS[ch_n].CnV; 00032 ((fastpwm_struct*)fast_obj)->MOD = &ftm->MOD; 00033 ((fastpwm_struct*)fast_obj)->SC = &ftm->SC; 00034 } 00035 00036 void FastPWM::pulsewidth_ticks( uint32_t ticks ) { 00037 PWM_CNV = ticks; 00038 } 00039 00040 void FastPWM::period_ticks( uint32_t ticks ) { 00041 PWM_MOD = ticks - 1; 00042 } 00043 00044 uint32_t FastPWM::getPeriod( void ) { 00045 return PWM_MOD + 1; 00046 } 00047 00048 uint32_t FastPWM::setPrescaler(uint32_t reqScale) { 00049 00050 uint32_t prescalers[] = {1, 2, 4, 8, 16, 32, 64, 128}; 00051 00052 for (int i = 0; i<8; i++) 00053 prescalers[i] = prescalers[i] * pwm_prescaler; 00054 00055 //If prescaler is 0, return current one 00056 if (reqScale == 0) 00057 return (prescalers[(PWM_SC) & 0x07]); 00058 00059 uint32_t retval = 0; 00060 char bin; 00061 00062 for (bin = 0; bin<8; bin++) { 00063 retval = prescalers[bin]; 00064 if (retval >= reqScale) 00065 break; 00066 } 00067 if (bin == 8) 00068 bin = 7; 00069 00070 //Clear lower 5 bits, write new value: 00071 char clockbits = PWM_SC & (3<<3); 00072 00073 //For some reason clearing them takes some effort 00074 while ((PWM_SC & 0x1F) != 0) 00075 PWM_SC &= ~0x1F; 00076 00077 00078 PWM_SC = bin + clockbits; 00079 00080 return retval; 00081 } 00082 #endif
Generated on Sat Jul 16 2022 12:48:38 by 1.7.2