Microcontroller › AVR › ADC › I found this code: #include
April 19, 2013 at 4:50 am
#9519
Participant
I found this code:
#include <avr/io.h> // include I/O definitions (port names, pin names, etc)
#include “global.h” // include our global settings
//
//
Defines
Defines
#define BV(bit) (1<<(bit)) // Byte Value => converts bit into a byte value. One at bit location.
#define cbi(reg, bit) reg &= ~(BV(bit)) // Clears the corresponding bit in register reg
#define sbi(reg, bit) reg |= (BV(bit)) // Sets the corresponding bit in register reg
//
//
Function Prototypes
Function Prototypes
void adc_init(void); // Will set up the registers for A/D conversion
//
Begin Code
Begin Code
int main(void)
{
unsigned short adc_result; // Just a variable to hold the result
adc_init(); // Call the init function
DDRF = 0x00; // configure a2d port (PORTF) as input so we can receive analog signals
PORTF = 0x00; // make sure pull-up resistors are turned off (else we’ll just read 0xCFF)
while(1)
{
sbi(ADCSRA,ADSC); // start a conversion by writing a one to the ADSC bit (bit 6)
while(ADCSRA & 0b01000000); // wait for conversion to complete (bit 6 will change to 0)
adc_result = ((ADCL) | ((ADCH)<<
); // 10-bit conversion for channel 0 (PF0)

}
return 0;
} // end main()
//
void adc_init(void)
{
sbi(ADCSRA,ADEN); // enables ADC by setting bit 7 (ADEN) in the ADCSRA
cbi(ADCSRA,ADFR); // single sample conversion by clearing bit 5 (ADFR) in the ADCSRA
ADCSRA = ((ADCSRA & 0b11111000) | 0b00000110); // selects div by 64 clock prescaler
ADMUX = ((ADMUX & 0b00111111) | 0b01000000); // selects AVCC as Vref
cbi(ADMUX,ADLAR); // selects right adjust of ADC result
ADMUX &= 0b11100000; // selects single-ended conversion on PF0
}