-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAtmega32_ADC.c
142 lines (135 loc) · 2.26 KB
/
Atmega32_ADC.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
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
142
/*
* AVRGCC4.c
*
* Created: 03-07-2020 14:47:17
* Author: user
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
int calculateADC();
void setupADC(int x);
void setPin(char port,int pin,int state);
void digitalWrite(char port,int pin,int state);
void setupADC(int x){
ADCSRA |= (1<<ADEN)|(1<<ADATE)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); //free running, 128 PRESCALAR
ADMUX |= (1<<REFS0); //ADC0,LEFT JUSTIFIED,REF 5V
switch (x)
{
case 0:
ADMUX=0x40;
break;
case 1:
ADMUX=0x41;
break;
case 2:
ADMUX=0x42;
break;
case 3:
ADMUX=0x43;
break;
case 4:
ADMUX=0x44;
break;
case 5:
ADMUX=0x45;
break;
case 6:
ADMUX=0x46;
break;
case 7:
ADMUX=0x47;
break;
default:
ADMUX=0x40;
}
ADCSRA |= 1<<ADSC; //START CONVERSION
sei();
// while(ADCSRA & (1<<ADSC)); //Wait for A/D Conversion to complete;
}
int calculateADC(){
int ADCval = ADCL;
ADCval = (ADCH << 8) + ADCval; // ADCH is read so ADC can be updated again
return ADCval;
}
ISR(ADC_vect){
if(calculateADC() > 700){
digitalWrite('B',7,1);
_delay_ms(1000);
digitalWrite('B',7,0);
}
}
void setPin(char port,int pin,int state) //port=A,B,C,D. pin 0-7. state 0 or 1.
{
switch(port){
case 'A':
if(state==1)
DDRA |= (1<<pin);
else
DDRA &= ~(1<<pin);
break;
case 'B':
if(state==1)
DDRB |= (1<<pin);
else
DDRB &= ~(1<<pin);
break;
case 'C':
if(state==1)
DDRC |= (1<<pin);
else
DDRC &= ~(1<<pin);
break;
case 'D':
if(state==1)
DDRD |= (1<<pin);
else
DDRD &= ~(1<<pin);
break;
default:
DDRB=0xFF;
PORTB=0xFF;
}
}
void digitalWrite(char port,int pin,int state) //port=A,B,C,D. pin 0-7. state 0 or 1.
{
switch(port){
case 'A':
if(state)
PORTA |= (1<<pin);
else
PORTA &= ~(1<<pin);
break;
case 'B':
if(state)
PORTB |= (1<<pin);
else
PORTB &= ~(1<<pin);
break;
case 'C':
if(state)
PORTC |= (1<<pin);
else
PORTC &= ~(1<<pin);
break;
case 'D':
if(state)
PORTD |= (1<<pin);
else
PORTD &= ~(1<<pin);
break;
default:
DDRB=0xFF;
PORTB=0xFF;
}
}
int main(void)
{
setPin('B',7,1);
setupADC(0);
while(1)
{
digitalWrite('B',7,0);
}
}