1 // vim: set sw=8 ts=8 si et:
2 /********************************************
3 * UART interface without interrupt
6 **********************************************/
7 #include <avr/interrupt.h>
10 #include <avr/pgmspace.h>
12 #define F_CPU 8000000UL // 8 MHz
15 #define SENDSTACKSIZE 12
16 static volatile char ustack[SENDSTACKSIZE];
17 static volatile uint8_t stackpointer_end=0;
18 static uint8_t stackpointer_start=0;
22 unsigned int baud=51; // 9600 baud at 8MHz
24 UBRR0H=(unsigned char) (baud >>8);
25 UBRR0L=(unsigned char) (baud & 0xFF);
26 // enable tx/rx and no interrupt on tx/rx
27 UCSR0B = (1<<RXEN0) | (1<<TXEN0);
28 // format: asynchronous, 8data, no parity, 1stop bit
29 UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
31 UBRRH=(unsigned char) (baud >>8);
32 UBRRL=(unsigned char) (baud & 0xFF);
33 // enable tx/rx and no interrupt on tx/rx
34 UCSRB = (1<<RXEN) | (1<<TXEN);
35 // format: asynchronous, 8data, no parity, 1stop bit
36 UCSRC = (1<<URSEL)|(3<<UCSZ0);
40 // send one character to the rs232
41 void uart_sendchar(char c)
44 // wait for empty transmit buffer
45 while (!(UCSR0A & (1<<UDRE0)));
48 // wait for empty transmit buffer
49 while (!(UCSRA & (1<<UDRE)));
53 // send string to the rs232
54 void uart_sendstr(char *s)
62 void uart_sendstr_p(const char *progmem_s )
63 // print string from program memory on rs232
66 while ((c = pgm_read_byte(progmem_s++))) {
72 // call this function from interrupt to fill the
73 // ustack reveiver buffer. We need this big buffer
74 // to handle fast copy/paste of strings comming
76 void uart_poll_getchar_isr(void)
79 if(!(UCSR0A & (1<<RXC0))) return;
80 ustack[stackpointer_end]=UDR0;
82 if(!(UCSRA & (1<<RXC))) return;
83 ustack[stackpointer_end]=UDR;
85 stackpointer_end=(stackpointer_end+1) % SENDSTACKSIZE;
88 // get the characters out of the buffer which is filled by
89 // the above interrupt function
90 unsigned char uart_getchar_isr_noblock(char *returnval)
92 if (stackpointer_start!=stackpointer_end){
93 *returnval=ustack[stackpointer_start];
94 stackpointer_start=(stackpointer_start+1) % SENDSTACKSIZE;
101 // get a byte from rs232
102 // this function does a blocking read
103 char uart_getchar(void)
106 while(!(UCSR0A & (1<<RXC0)));
109 while(!(UCSRA & (1<<RXC)));
114 // get a byte from rs232
115 // this function does a non blocking read
116 // returns 1 if a character was read
117 unsigned char uart_getchar_noblock(char *returnval)
120 if(UCSR0A & (1<<RXC0)){
125 if(UCSRA & (1<<RXC)){
133 // read and discard any data in the receive buffer
134 void uart_flushRXbuf(void)
138 while(UCSR0A & (1<<RXC0)){
142 while(UCSRA & (1<<RXC)){