Many more changes, timed callbacks etc
[simavr] / tests / atmega88_uart_echo.c
1 /*
2         atmega88_uart_echo.c
3
4         This test case enables uart RX interupts, does a "printf" and then receive characters
5         via the interupt handler until it reaches a \r.
6
7         This tests the uart reception fifo system. It relies on the uart "irq" input and output
8         to be wired together (see simavr.c)
9  */
10
11 #include <avr/io.h>
12 #include <stdio.h>
13 #include <avr/interrupt.h>
14 #include <avr/eeprom.h>
15 #include <avr/sleep.h>
16
17 /*
18  * This demonstrate how to use the avr_mcu_section.h file
19  * The macro adds a section to the ELF file with useful
20  * information for the simulator
21  */
22 #include "avr_mcu_section.h"
23 AVR_MCU(F_CPU, "atmega88");
24
25
26 static int uart_putchar(char c, FILE *stream) {
27   if (c == '\n')
28     uart_putchar('\r', stream);
29   loop_until_bit_is_set(UCSR0A, UDRE0);
30   UDR0 = c;
31   return 0;
32 }
33
34 static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
35                                          _FDEV_SETUP_WRITE);
36
37 volatile uint8_t bindex = 0;
38 uint8_t buffer[80];
39 volatile uint8_t done = 0;
40
41 ISR(USART_RX_vect)
42 {
43         uint8_t b = UDR0;
44         buffer[bindex++] = b;
45         buffer[bindex] = 0;
46         if (b == '\n')
47                 done++;
48 }
49
50 int main()
51 {
52         stdout = &mystdout;
53
54         // enable receiver
55         UCSR0B |= (1 << RXCIE0) | (1 << RXEN0) | (1 << TXEN0);
56
57         sei();
58         printf("Hey there, this should be received back\n");
59
60         while (!done)
61                 sleep_cpu();
62
63         cli();
64         printf("Received: %s", buffer);
65
66         // this quits the simulator, since interupts are off
67         // this is a "feature" that allows running tests cases and exit
68         sleep_cpu();
69 }