/* Analog2.C -> Data Collection / Monitor Written by Jeffrey J. Richardson September 7, 2002 Uses the MegaAVR-DEVelopment Board available from PRLLC with an ATmega163 controller operating at 6MHz. Second Analog to Digital program. This program will setup the ADC... Reads the value every 60 seconds and sends it out the serial port (CSV) */ #include #include #define XTAL 6000000L #define BAUD 9600 #define OCF2 0x80 void init_serial(void); void init_ports(void); void init_delay2(void); void init_ADC(void); unsigned char read_ADC(void); void main(void) { unsigned char temp, seconds; unsigned int time; init_ports(); // setup the ports init_serial(); // setup the serial port init_ADC(); // setup the Analog Converter init_delay2(); // setup the timer printf("Analog to Digital Converter 2.\n\r"); printf("Time, Temp\n"); seconds = 0; time = 0; while(1) // do forever... { if(seconds == 0) { temp = read_ADC(); PORTC = ~temp; // monitor the ADC input and display it on the LEDs printf("%i,%d\n", time, temp); } while( (TIFR & OCF2) == 0) // wait for second to be up... { } TIFR = (TIFR | OCF2); // clear flag for next time seconds++; // increment the seconds if(seconds > 59) { seconds = 0; time++; } } } 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 } void init_delay2(void) // variable 1 second based delay using Timer2 { // will flash the LED on PortB during operation!! ASSR = 0x08; // set for asynchronous clock TCCR2 = 0x0F; // set prescale for 1024 & clear counter on compare match TIFR = (TIFR | 0xC0); // clear any previous timer flags OCR2 = 32; // additional prescale for 1 second timer while(ASSR & 0x02); // wait for info to be transfered to OCR2 }