Potmeter FastPWM.h

Dependencies:   mbed

Committer:
vd
Date:
Tue Sep 19 16:52:01 2017 +0000
Revision:
0:16be67f4d9ac
Potmeter FastPWM.h

Who changed what in which revision?

UserRevisionLine numberNew contents of line
vd 0:16be67f4d9ac 1 #if defined(TARGET_KLXX) || defined(TARGET_K20D50M)
vd 0:16be67f4d9ac 2
vd 0:16be67f4d9ac 3 #include "FastPWM.h"
vd 0:16be67f4d9ac 4
vd 0:16be67f4d9ac 5 void FastPWM::initFastPWM( void ) {
vd 0:16be67f4d9ac 6 bits = 16;
vd 0:16be67f4d9ac 7 }
vd 0:16be67f4d9ac 8
vd 0:16be67f4d9ac 9 void FastPWM::pulsewidth_ticks( uint32_t ticks ) {
vd 0:16be67f4d9ac 10 *(_pwm.CnV) = ticks;
vd 0:16be67f4d9ac 11 }
vd 0:16be67f4d9ac 12
vd 0:16be67f4d9ac 13 void FastPWM::period_ticks( uint32_t ticks ) {
vd 0:16be67f4d9ac 14 *(_pwm.MOD) = ticks - 1;
vd 0:16be67f4d9ac 15 }
vd 0:16be67f4d9ac 16
vd 0:16be67f4d9ac 17 uint32_t FastPWM::getPeriod( void ) {
vd 0:16be67f4d9ac 18 return *(_pwm.MOD) + 1;
vd 0:16be67f4d9ac 19 }
vd 0:16be67f4d9ac 20
vd 0:16be67f4d9ac 21 uint32_t FastPWM::setPrescaler(uint32_t reqScale) {
vd 0:16be67f4d9ac 22
vd 0:16be67f4d9ac 23 //Yes this is ugly, yes I should feel bad about it
vd 0:16be67f4d9ac 24 volatile uint32_t *TPM_SC = _pwm.MOD - 2;
vd 0:16be67f4d9ac 25
vd 0:16be67f4d9ac 26 const char prescalers[] = {1, 2, 4, 8, 16, 32, 64, 128};
vd 0:16be67f4d9ac 27
vd 0:16be67f4d9ac 28 //If prescaler is 0, return current one
vd 0:16be67f4d9ac 29 if (reqScale == 0)
vd 0:16be67f4d9ac 30 return (prescalers[(*TPM_SC) & 0x07]);
vd 0:16be67f4d9ac 31
vd 0:16be67f4d9ac 32 uint32_t retval = 0;
vd 0:16be67f4d9ac 33 char bin;
vd 0:16be67f4d9ac 34
vd 0:16be67f4d9ac 35 for (bin = 0; bin<8; bin++) {
vd 0:16be67f4d9ac 36 retval = prescalers[bin];
vd 0:16be67f4d9ac 37 if (retval >= reqScale)
vd 0:16be67f4d9ac 38 break;
vd 0:16be67f4d9ac 39 }
vd 0:16be67f4d9ac 40 if (bin == 8)
vd 0:16be67f4d9ac 41 bin = 7;
vd 0:16be67f4d9ac 42
vd 0:16be67f4d9ac 43 //Clear lower 5 bits, write new value:
vd 0:16be67f4d9ac 44 char clockbits = *TPM_SC & (3<<3);
vd 0:16be67f4d9ac 45
vd 0:16be67f4d9ac 46 //For some reason clearing them takes some effort
vd 0:16be67f4d9ac 47 while ((*TPM_SC & 0x1F) != 0)
vd 0:16be67f4d9ac 48 *TPM_SC &= ~0x1F;
vd 0:16be67f4d9ac 49
vd 0:16be67f4d9ac 50
vd 0:16be67f4d9ac 51 *TPM_SC = bin + clockbits;
vd 0:16be67f4d9ac 52
vd 0:16be67f4d9ac 53 return retval;
vd 0:16be67f4d9ac 54 }
vd 0:16be67f4d9ac 55 #endif