| 1 |
/* This wrapper file initializes stdio to UART connection and |
| 2 |
* receives the list of command line arguments. |
| 3 |
*/ |
| 4 |
#include <stdint.h> |
| 5 |
#include <stdio.h> |
| 6 |
#include <stdlib.h> |
| 7 |
#include <avr/io.h> |
| 8 |
#include <avr/interrupt.h> |
| 9 |
#include <avr/sleep.h> |
| 10 |
|
| 11 |
#undef main |
| 12 |
extern int app_main(int argc, const char **argv); |
| 13 |
|
| 14 |
struct { |
| 15 |
uint8_t argc; |
| 16 |
char args[3][16]; |
| 17 |
} g_args; |
| 18 |
|
| 19 |
int uart_putchar(char c, FILE *stream) |
| 20 |
{ |
| 21 |
loop_until_bit_is_set(UCSR0A, UDRE0); |
| 22 |
UDR0 = c; |
| 23 |
return 0; |
| 24 |
} |
| 25 |
|
| 26 |
int uart_getchar(FILE *stream) |
| 27 |
{ |
| 28 |
while (bit_is_clear(UCSR0A, RXC0) && bit_is_clear(UCSR0A, FE0)); |
| 29 |
if (UCSR0A & _BV(FE0)) return _FDEV_EOF; /* Break = EOF */ |
| 30 |
return UDR0; |
| 31 |
} |
| 32 |
|
| 33 |
FILE uart_str = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW); |
| 34 |
static char g_malloc_heap[8192]; |
| 35 |
extern uint32_t __bss_end; |
| 36 |
|
| 37 |
void abort(void) |
| 38 |
{ |
| 39 |
if (__bss_end != 0xDEADBEEF) |
| 40 |
{ |
| 41 |
fprintf(stderr, "possible stack overflow\n"); |
| 42 |
} |
| 43 |
|
| 44 |
fprintf(stderr, "abort() called\n"); |
| 45 |
DDRB = 3; |
| 46 |
PORTB = 1; |
| 47 |
cli(); |
| 48 |
while (1) sleep_mode(); |
| 49 |
} |
| 50 |
|
| 51 |
int main(void) |
| 52 |
{ |
| 53 |
const char *argv[4] = {"main", g_args.args[0], g_args.args[1], g_args.args[2]}; |
| 54 |
int status; |
| 55 |
|
| 56 |
UBRR0 = (8000000 / (16UL * 9600)) - 1; /* 9600 bps with default 8 MHz clock */ |
| 57 |
UCSR0B = _BV(TXEN0) | _BV(RXEN0); |
| 58 |
|
| 59 |
__malloc_heap_start = g_malloc_heap; |
| 60 |
__malloc_heap_end = g_malloc_heap + sizeof(g_malloc_heap); |
| 61 |
|
| 62 |
__bss_end = 0xDEADBEEF; |
| 63 |
|
| 64 |
stdout = stdin = stderr = &uart_str; |
| 65 |
|
| 66 |
fread((char*)&g_args, 1, sizeof(g_args), stdin); |
| 67 |
|
| 68 |
status = app_main(g_args.argc + 1, argv); |
| 69 |
|
| 70 |
if (__bss_end != 0xDEADBEEF) |
| 71 |
{ |
| 72 |
status = 255; |
| 73 |
fprintf(stderr, "possible stack overflow\n"); |
| 74 |
} |
| 75 |
|
| 76 |
DDRB = 3; |
| 77 |
if (status) |
| 78 |
{ |
| 79 |
fprintf(stderr, "Error exit: %d\n", status); |
| 80 |
PORTB = 1; // PB0 indicates error |
| 81 |
} |
| 82 |
else |
| 83 |
{ |
| 84 |
PORTB = 2; // PB1 indicates success |
| 85 |
} |
| 86 |
|
| 87 |
cli(); |
| 88 |
sleep_mode(); |
| 89 |
return status; |
| 90 |
} |
| 91 |
|