/* Analog1.C Written by Jeffrey J. Richardson September 7, 2002 Uses the MegaAVR-DEVelopment Board available from PRLLC with an ATmega163 controller operating at 6MHz. First Analog to Digital program. This program will setup the ADC... Read the value and Display it on Port C (forever) */ #include #include #define XTAL 6000000L #define BAUD 9600 void init_serial(void); void init_ports(void); void init_ADC(void); unsigned char read_ADC(void); void main(void) { init_ports(); // setup the ports init_serial(); // setup the serial port init_ADC(); // setup the Analog Converter printf("Analog to Digital Converter.\n\r"); while(1) // do forever... { PORTC = ~read_ADC(); // monitor the ADC input and display it on the LEDs } } unsigned char read_ADC(void) { unsigned char value; ADCSR = ADCSR | 0x40; // start a conversion while( (ADCSR & 0x10) == 0 ); // wait for conversion to be completed value = ADCH; // get the upper 8-bits ADCSR = ADCSR | 0x10; // clear the flag return value; } void init_serial(void) { unsigned int UBR; // 16 bit variable to hold serial port calculations UBR = XTAL / 16 / BAUD - 1; // calculate the load values UBRR = (unsigned char)(UBR & 0xFF); // load the lower 8 bits UBRRHI = (unsigned char)(UBR >> 8); // load the upper bits UCSRB = 0x18; // enable transmit and receive } void init_ports(void) { DDRC = 0xFF; // setup PortC for output PORTC = 0x00; } void init_ADC(void) { ADMUX = 0x00; // start by selecting channel 0 ADMUX = ADMUX | 0x40; // select the voltage reference ADMUX = ADMUX | 0x20; // set for Left Justified ADCSR = 0x07; // select the ADC clock frequency ADCSR = ADCSR | 0x80; // enable the ADC }