#include<avr/io.h>
#include<avr/interrupt.h>
#include<stdlib.h>
[COLOR="#FF0000"]#include<avr/power.h>[/COLOR]
#define DATABUFSIZE 42
#define NUMBER_OFSET 34
char demoBuff[DATABUFSIZE] = {'M','o','r','e',' ','o','o','m','f',' ','t','o',' ','y','o','u','r',' ','a','m','p','s',',',' ','p','i','c','o','P','o','w','e','r','!',0,0,0,0, 0,'\r','\n'};
uint16_t iteration=1;
void init_adc()
{
ADMUX = (1<<MUX3); //Set mux to internal temp sens.
ADCSRA = (1<<ADEN); //ADC enable
}
void init_timer2()
{
TCCR2B = (1<<CS20) | (1<<CS22); //Clock prescaler set to 5, overflow each sec
TIMSK2 = (1<<TOIE2); //Enable timer2 overflow interrupt
ASSR = (1<<AS2); //Enable async operation
}
void init_uart()
{
UCSR0A = (1<<U2X0); // Enable U2Xn to get a baud rate with less error margin
UCSR0B = (1<<TXEN0); // Transmitter enable
UCSR0C = (1<<UCSZ00) | (1<<UCSZ01); // Asynchronous USART | No parity | 1 stopbit | CH size 8-bit
UBRR0 = 0x0C; // 19200 Baudrate@8Mhz
}
void enable_pullups()
{
PORTB = 0xFF; // Enables internal pull-ups on the IO pins, direction bits are by default set to 0 (input)
PORTC = 0xFF; // The UART tx pin will still work
PORTD = 0xFF;
}
void enable_prr()
{
[COLOR="#FF0000"] power_spi_disable();
power_timer0_disable();
power_timer1_disable();
power_twi_disable();[/COLOR]
}
void cal_clock()
{
OSCCAL = 0x66; // Calibrate oscillator to 8MHz
}
int main()
{
int count=0;
cal_clock();
clock_prescale_set(clock_div_4); // Prescale systemclock to 2 MHz
enable_pullups();
enable_prr();
init_uart();
init_timer2();
init_adc();
while(1)
{
ADMUX |= (1<<REFS1) | (1<<REFS0); // Enable internal 1.1V ref.
ADCSRA |= (1<< ADSC); // Start conversion
while(!(ADCSRA & (1<<ADIF))); // Wait for ready flag
ADMUX &= (1<<MUX3); // Disable internal 1.1V ref.
utoa(iteration, &demoBuff[NUMBER_OFSET], 10); // Generate desimal number string from itt
__asm__ volatile ( // Simulate 1000 cycles of processing
"ldi r24, 25" "\n\t" // Load 25 into register 24
"1: sbiw r24,1" "\n\t" // Subtract 1 for each iteration
"brne 1b" // Branch if not equal (Z = 0), the loop takes 4 cycles
);
for(count=0;count<DATABUFSIZE;++count)
{
while(!(UCSR0A & (1<<UDRE0))); // Wait for the last byte to be shifted out of the data register in the UART module
UDR0 = demoBuff[count];
}
while(!(TIFR2 & (1<<TOV2))); // Wait for the timer to count a second
TIFR2 = (1<<TOV2); // Reset timer/counter 2 interrupt flag
iteration++; // Increase the itterator counter
}
return 0;
}