-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPWM.cpp
More file actions
98 lines (71 loc) · 2.51 KB
/
Copy pathPWM.cpp
File metadata and controls
98 lines (71 loc) · 2.51 KB
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
89
90
91
92
93
94
95
96
97
98
#include "PWM.h"
void initPWM(){
// PWM frequency calculation for FAST PWM mode on page 148 of datasheet
// frequency of PWM = (F_clk)/((Prescaler)* (1 +TOP))
// frequency of PWM = 16Mhz
// Prescaler = 1
// TOP value = 03ff = 1023
// PWM frequency from calculation = 15.625 kHz
//-----FOR TIMER 3-----//
// set Fast PWM 10-bit mode, non-inverting
// Use Timer 3
// initalize pin as output
DDRE |= (1 << DDE3); //pin 5 for timer 3
// Fast PWM 10-bit mode from Table 17-2
TCCR3A |= (1 << WGM31) | (1 << WGM30);
TCCR3B |= (1 << WGM32);
TCCR3B &= ~(1 << WGM33);
// Noninverting, from Table 17-4
TCCR3A |= (1 << COM3A1);
TCCR3A &= ~(1 << COM3A0);
// Clock Prescaler set to 1 from Table 17-6
TCCR3B |= (1 << CS30);
TCCR3B &= ~((1 << CS31) | (1 << CS32));
//-----FOR TIMER 4-----//
// set Fast PWM 10-bit mode, non-inverting
// Use Timer 4
// initalize pin as output
DDRH |= (1 << DDH3); //pin 6 for timer 4
// Fast PWM 10-bit mode from Table 17-2
TCCR4A |= (1 << WGM41) | (1 << WGM40);
TCCR4B |= (1 << WGM42);
TCCR4B &= ~(1 << WGM43);
// Noninverting, from Table 17-4
TCCR4A |= (1 << COM4A1);
TCCR4A &= ~(1 << COM4A0);
// Clock Prescaler set to 1 from Table 17-6
TCCR4B |= (1 << CS40);
TCCR4B &= ~((1 << CS41) | (1 << CS42));
}
//Set motor speed and direction with count registers using information obtained by ADC
void SetMOTORspeed(int ADCValue) {
// the last thing is to set the duty cycle.
// duty cycle is set by dividing output compare OCR4A value by 1 + TOP value
// the top value is (1 + 0x3FF) = 1024
// calculate OCR4A value => OCR4A = duty cycle(fractional number) * (1 + TOP)
// we want a duty cycle varies based on voltage variable result
// OCR1A = 0.60 * 1024
double result = 0.0;
//convert result into a voltage for this to not change
result = ADCValue*(5.0/1024.0);
if(result < 2.3){
// set duty cycle
// Tpulse/Tperiod = OCRnx/TOP
// duty cycle varies based on voltage variable result
// 0x3FF/4
unsigned int jeff = 1024 - (result / 2.5 )* 1024;
OCR4A = 0;
OCR3A = jeff;
}else if (result > 2.7){
// set duty cycle
// Tpulse/Tperiod = OCRnx/TOP
// duty cycle of 25%
// 0x3FF/4
unsigned int jeff2 = ((result/2.5) * 0x400) ;
OCR3A = 0;
OCR4A = jeff2;
} else{
OCR3A = 0;
OCR4A = 0;
}
}