avrinput/avr_tests/usart_test.c

72 lines
1.1 KiB
C
Raw Normal View History

2019-04-10 09:52:35 +00:00
#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>
//#define USART_U2X_EN
#define F_CPU 20000000UL
#include <util/delay.h>
#define USART_BAUD 2400
#define UBRR_VALUE_DS 520
#ifndef USART_U2X_EN
#define UBRR_VALUE (F_CPU/16/USART_BAUD-1)
#else
#define UBRR_VALUE (F_CPU/8/USART_BAUD-1)
#endif
#if !(UBRR_VALUE == UBRR_VALUE_DS)
#warning "Calculated UBRR value differs from the value given in the datasheet: "
#define UBRR_VALUE UBRR_VALUE_DS
#endif
int cnt;
void
usart_init(void)
{
UBRR0H = (unsigned char)(UBRR_VALUE >> 8);
UBRR0L = (unsigned char)UBRR_VALUE;
#ifdef USART_U2X_EN
UCSR0A |= _BV(U2X0);
#endif
UCSR0B = _BV(TXEN0) | _BV(TXCIE0);
UCSR0C = _BV(UCSZ00) | _BV(UCSZ01);
//UCSR0C = _BV(UCSZ00) | _BV(UCSZ01);
cnt = 0;
sei();
}
ISR(USART_TX_vect)
{
if(!cnt)
{
UDR0 = '\n';
cnt++;
}
else
{
cnt = (cnt + 1) % 10;
UDR0 = '0' + cnt;
}
}
int main(void)
{
DDRC |= _BV(PC5);
usart_init();
while(!(UCSR0A & _BV(UDRE0)));
UDR0 = '0';
while(1)
{
PORTC ^= _BV(PC5);
_delay_ms(500);
PORTC ^= _BV(PC5);
_delay_ms(1000);
PORTC ^= _BV(PC5);
_delay_ms(500);
}
return 0;
}