tests: Update them so they work...
[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 // tell simavr to listen to commands written in this (unused) register
25 AVR_MCU_SIMAVR_COMMAND(&GPIOR0);
26
27 static int uart_putchar(char c, FILE *stream) {
28   if (c == '\r')
29     uart_putchar('\r', stream);
30   loop_until_bit_is_set(UCSR0A, UDRE0);
31   UDR0 = c;
32   return 0;
33 }
34
35 static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
36                                          _FDEV_SETUP_WRITE);
37
38 volatile uint8_t bindex = 0;
39 uint8_t buffer[80];
40 volatile uint8_t done = 0;
41
42 ISR(USART_RX_vect)
43 {
44         uint8_t b = UDR0;
45         buffer[bindex++] = b;
46         buffer[bindex] = 0;
47         if (b == '\n')
48                 done++;
49 }
50
51 int main()
52 {
53         // this tell simavr to put the UART in loopback mode
54         GPIOR0 = SIMAVR_CMD_UART_LOOPBACK;
55
56         stdout = &mystdout;
57
58         // enable receiver
59         UCSR0B |= (1 << RXCIE0) | (1 << RXEN0) | (1 << TXEN0);
60
61         sei();
62         printf("Hey there, this should be received back\n");
63
64         while (!done)
65                 sleep_cpu();
66
67         cli();
68         printf("Received: %s", buffer);
69
70         // this quits the simulator, since interupts are off
71         // this is a "feature" that allows running tests cases and exit
72         sleep_cpu();
73 }