added UART methods

This commit is contained in:
King Kévin 2013-10-12 18:19:39 +02:00
parent 1c72c2bce0
commit f3b8b2d8e9
5 changed files with 64 additions and 3 deletions

View File

@ -19,7 +19,7 @@ PROGRAMMER=usbtiny
#AVRDUDE=avrdude -p $(DEVICE) -P $(PORT) -c $(PROGRAMMER)
FLASHER=avrdude -p $(DEVICE) -c $(PROGRAMMER)
# source files to compile
SRC = main.c
SRC = main.c uart.c
# object files.
OBJ = $(SRC:.c=.o)
# listing files.
@ -36,6 +36,9 @@ verify:
exit 1; \
fi
reset:
$(FLASHER)
read-fuse:
$(FLASHER) -U lfuse:r:lfuse.raw:r -U hfuse:r:hfuse.raw:r -U efuse:r:efuse.raw:r

View File

@ -5,12 +5,15 @@
#include <avr/io.h> /* AVR device-specific IO definitions */
#include <util/delay.h> /* Convenience functions for busy-wait delay loops */
#define LED PD6 /* LED port */
#include "main.h"
#include "uart.h"
static void ioinit(void)
{
DDRD = (1<<LED); /* set LED pin as output */
uart_init(); /* initialize UART */
stdout = &uart_output;
stdin = &uart_input;
}
int main(void)
@ -19,6 +22,8 @@ int main(void)
uint8_t i;
puts("Hello world!");
/* blink LED */
for (i = 0; i < 100; i++) {
PIND |= (1<<LED); /* toggle LED */

3
src/main.h Normal file
View File

@ -0,0 +1,3 @@
#define LED PD6 /* LED port */
static void ioinit(void);

40
src/uart.c Normal file
View File

@ -0,0 +1,40 @@
#include <stdint.h> /* Standard Integer Types */
#include <stdio.h> /* Standard IO facilities */
#include <stdlib.h> /* General utilities */
#include <avr/io.h> /* AVR device-specific IO definitions */
#include "uart.h"
#include <util/setbaud.h> /* Helper macros for baud rate calculations */
FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);
FILE uart_input = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);
FILE uart_io = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
/* configure serial port */
void uart_init(void)
{
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0C = (1<<UCSZ01) | (1<<UCSZ00); /* 8N1-bit data */
UCSR0B = (1<<RXEN0) | (1<<TXEN0); /* enable RX and TX */
}
void uart_putchar(char c, FILE *stream)
{
if (c == '\n') {
uart_putchar('\r', stream);
}
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = c;
}
char uart_getchar(FILE *stream)
{
loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
return UDR0;
}

10
src/uart.h Normal file
View File

@ -0,0 +1,10 @@
#define BAUD 115200 /* serial baudrate */
FILE uart_output;
FILE uart_input;
FILE uart_io;
void uart_init(void);
void uart_putchar(char c, FILE *stream);
char uart_getchar(FILE *stream);