-
Notifications
You must be signed in to change notification settings - Fork 0
/
pwm.c
88 lines (66 loc) · 1.38 KB
/
pwm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*! \file pwm.c
\brief PWM Functions
PWM Functions
*/
#include "pic.h"
#include "pwm.h"
#include "timer.h"
#include "interrupts.h"
#include <p18F2525.h>
unsigned char PWM_CCP2CON;
unsigned char PWM_PR2;
unsigned char PWM_T2CON;
unsigned char PWM_CCPR2L;
unsigned char PWM_CCP2CON;
void PWM_Start(void)
{
CCPR2L = PWM_CCPR2L;
}
void PWM_Stop(void)
{
CCPR2L = 0;
}
char PWM_Configure(char Channel, unsigned long Frequency, char Duty)
{
char Prescale = 1;
unsigned long t,s;
unsigned char u;
TRISBbits.RB3 = 0;
do
{
// (OSC / (Freq * Prescale)) - 1 = PR2
t = CLOCK_HZ / Frequency;
t = t / 4;
t = t / Prescale;
t = t - 1;
if(t < 256)
break;
Prescale = Prescale * 4;
if(Prescale > 16) // We couldn't find a working parameters
return 1;
} while (1==1);
PWM_PR2 = t;
if(Prescale == 1)
PWM_T2CON = 0b00000000;
if(Prescale == 4)
PWM_T2CON = 0b00000001;
if(Prescale == 16)
PWM_T2CON = 0b00000011;
// Duty * OSC / (Frequency * Prescale*100) = CCPR
t = PWM_PR2;
t++;
t = t * 4;
t = t * Duty;
t = t / 100;
s = t >> 2;
PWM_CCPR2L = s;
PWM_CCP2CON = 0b00001100;
PORTBbits.RB3 = 0;
TMR2=0;
CCP2CON = PWM_CCP2CON;
PR2 = PWM_PR2;
T2CON = PWM_T2CON;
CCPR2L = 0;
T2CONbits.TMR2ON = 1;
return 0;
}