;Compiler : CodevisionAVR V2.04.4a
;CHIP : AVR ATMega16 @4Mhz
;Prog. Exp : ADC UART example..
-------
*/
#include <mega16.h>
// Standard Input/Output functions
#include <delay.h> //library fungsi delay
#include <stdio.h> //I/O funtion
#define ADC_VREF_TYPE 0x40 //AVCC reference
// Global variables
const long int osilator=4000000;
unsigned long int UBRR;
//function prototype
void sett_regs(void);
void SetBaudrate( unsigned long int baud_rate );
// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input){
ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
// Delay needed for the stabilization of the ADC input voltage
delay_us(10);
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}
//Main routine buat super loop
void main(void){
sett_regs();
SetBaudrate(9600);
for(;;){
#asm("nop")
//utilize printf function from stdio.h. sometimes will needs CRLF to monitor the data in terminal software
//CRLF has the function to make a new line with every packet sent
//printf("Data ADC = %d%c%c", read_adc(0),13,10); //printf dengan carriage return and linefeed (13,10) CRLF
//printf("Data ADC = %d\r\n", read_adc(0)); //printf dengan carriage return and linefeed (13,10) CRLF
printf("Data ADC = %d", read_adc(0)); //printf tanpa carriage return and linefeed (13,10) CRLF
//carriage return dan linefeed terpisah :)
putchar(13); //carriage return
putchar(10); //linefeed
delay_ms(500); //delay for packet, time interval
}
}
// Setting register
void sett_regs(void){
//Define I/O
DDRA = 0x00;PORTA = 0x00;
DDRB = 0x00;PORTB = 0x00;
DDRC = 0x00;PORTC = 0x00;
DDRD = 0xF0;PORTD = 0xF0;
// ADC initialization
// ADC Clock frequency: 31,250 kHz
// ADC Voltage Reference: AVCC pin
// ADC Auto Trigger Source: Free Running
ADMUX=ADC_VREF_TYPE & 0xff;
ADCSRA=0xA7;
SFIOR&=0x1F;
}
void SetBaudrate( unsigned long int baud_rate ){
UBRR = (osilator/(16*baud_rate))-1;
UBRRL = UBRR;
UBRRH = UBRR>>8;
UCSRA = 0x00;
UCSRB = 0x18;
UCSRC = 0x86;
}