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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
| sbit Chip_Select at RC0_bit;
sbit Chip_Select_Direction at TRISC0_bit;
double AD_LSB,y_high, y_low , sk ;
#define NUM_SECTIONS 3
double coeff[NUM_SECTIONS*5] = { 0.9583, 0.04167 , 1.0, -1.808, 0.968 ,
0.0 , 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0 };
/* { 0.9583, 0.04167 , 1.0, -1.808, 0.968 ,
0.0 , 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0 }; */
double control_gain = 10.0*0.788 ; // gain is 10 times increased
double state[3] = { 0.0, 0.0,0.0 } ;
double*ptr_coeff, *ptr_state;
double input, output, yk, ADCres;
int section_count ;
void Initilalize_AD(void)
{ TRISA = 0x04; // SET CHAMNNEL 2 AN2/RA2
ANSELA.ANSA2 = 1 ; // AN2 is analog channel
TRISA.TRISA2 = 1 ;
ADCON2 =0X8A;
ADCON1.PVCFG0= 0; // VREF+ = VDD
ADCON1.NVCFG1 = 0 ; // VREF = VSS
ADCON0 = 0X09 ;
}
void Read_AD_Input(void)
{
PIR1.ADIF = 0; // A/D INT. NOT SET, i.e. not started a/d conversion
ADCON0.GO =1; // A/D CONVERSION BEGINS
while( !PIR1.ADIF );
y_high=ADRESH;
y_low=ADRESL;
yk=256.0*y_high + y_low;
yk=yk*AD_LSB;
}
void DAC(unsigned int value)
{
char temp;
Chip_Select = 0 ; // enable DAC
temp = (value>>8) & 0x0F ;
temp |= 0x30;
SPI1_Write(temp);
temp = value ; //send low byte
SPI1_Write(temp);
Chip_Select = 1 ; // disable DAC
}
void main() {
AD_LSB = 5.0/1024.0 ;
ANSELC = 0 ;
TRISC = 0;
Chip_Select = 1;
Chip_Select_Direction = 0 ; // CS IS OUTPUT
SPI1_Init();
Initilalize_AD();
while(1){
Read_AD_Input();
delay_us(1); // delay for using 2 channels
ADC_Init();
ADCres = ADC_Get_Sample(0);
sk = ADCres*5.0/1024.0;
input = sk - yk ;
ptr_coeff = coeff;
ptr_state = state;
for(section_count = 0; section_count < NUM_SECTIONS ; section_count++)
{
*( ptr_state+2) = *( ptr_state+1) ;
*( ptr_state+1) = * ptr_state ;
*ptr_state = input + *(ptr_coeff) *( *( ptr_state+1))
+ *(ptr_coeff+1) *( *( ptr_state+2)) ;
input = *(ptr_coeff+2) *( *( ptr_state++))
+ *(ptr_coeff+3) *( *( ptr_state++))
+ *(ptr_coeff+4) *( *( ptr_state++)) ;
ptr_coeff = ptr_coeff +5 ;
}
output = control_gain *input ;
//output = output*4095.0/5.0 ;
DAC(output) ;
/* Skiping the Timer Interrupt , instead Using delay
T0CON = 0XC0; // ENABLE TIMER0, 8 BIT TIMER MODE, PRESCALER 2
TMR0L = 246;
INTCON = 0xA0; // enable global and TMRO interrupt
for(; ;) // Wait for interrupt
{ */
delay_us (100);
}
} |