rendered paste body#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#define USART_BAUDRATE 4800
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
void icp_init(void);
void usart_init(void);
void usart_transmit(unsigned char);
unsigned char usart_receive(void);
volatile unsigned char sync;
volatile unsigned char end;
volatile unsigned int start_pulse;
volatile unsigned int end_pulse;
int main(void)
{
DDRD = 0xFE;
usart_init();
icp_init();
while (1) {
if (sync == 2) {
usart_transmit(0xFF);
} else if (sync == 1) {
usart_transmit(end_pulse>>3);
}
sync = 0;
}
}
ISR(TIMER1_CAPT_vect) {
if (end == 0) {
start_pulse = ICR1;
end = 1;
} else {
end_pulse = ICR1 - start_pulse;
end = 0;
if (end_pulse > 2100) {
sync = 2;
} else if (end_pulse > 900) {
sync = 1;
}
}
}
void icp_init(void) {
// set ICP pin as input
DDRB &= ~(1<<PB0);
// timer clock = system clock, rising edge trigger
TCCR1B = 0xC1;
// clear ICF1 clear pending interrupts
TIFR1 = 1<<ICF1;
// enable timer1 captuer event interrupt
TIMSK1 = 1<<ICIE1;
// set local var for start of pulse
end = 0;
// enable global interrupts
sei();
}
void usart_init(void) {
// set baud rate
UBRR0H = (unsigned char) (BAUD_PRESCALE>>8);
UBRR0L = (unsigned char) BAUD_PRESCALE;
// enable receiver and transmitter
UCSR0B = (1<<RXEN0) | (1<<TXEN0);
}
void usart_transmit(unsigned char data) {
// wait for empty transmit buffer
while ( !(UCSR0A & (1<<UDRE0)) );
// put data into buffer, sends the data automatically
UDR0 = data;
}
unsigned char usart_receive(void) {
// wait for data to be received
while ( !(UCSR0A & (1<<RXC0)) );
// get and return received data from buffer
return UDR0;
}