0.6.1 Improved display code
[digitaldcpower] / uart.c
1 // vim: set sw=8 ts=8 si et: 
2 /********************************************
3 * UART interface without interrupt
4 * Author: Guido Socher
5 * Copyright: GPL
6 **********************************************/
7 #include <avr/interrupt.h>
8 #include <string.h>
9 #include <avr/io.h>
10 #include "uart.h"
11 #define F_CPU 8000000UL  // 8 MHz
12
13 void uart_init(void) 
14 {
15         unsigned int baud=51;   // 9600 baud at 8MHz
16 #ifdef VAR_88CHIP
17         UBRR0H=(unsigned char) (baud >>8);
18         UBRR0L=(unsigned char) (baud & 0xFF);
19         // enable tx/rx and no interrupt on tx/rx 
20         UCSR0B =  (1<<RXEN0) | (1<<TXEN0);
21         // format: asynchronous, 8data, no parity, 1stop bit 
22         UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
23 #else
24         UBRRH=(unsigned char) (baud >>8);
25         UBRRL=(unsigned char) (baud & 0xFF);
26         // enable tx/rx and no interrupt on tx/rx 
27         UCSRB =  (1<<RXEN) | (1<<TXEN);
28         // format: asynchronous, 8data, no parity, 1stop bit 
29         UCSRC = (1<<URSEL)|(3<<UCSZ0);
30 #endif
31 }
32
33 // send one character to the rs232 
34 void uart_sendchar(char c) 
35 {
36 #ifdef VAR_88CHIP
37         // wait for empty transmit buffer 
38         while (!(UCSR0A & (1<<UDRE0)));
39         UDR0=c;
40 #else
41         // wait for empty transmit buffer 
42         while (!(UCSRA & (1<<UDRE)));
43         UDR=c;
44 #endif
45 }
46 // send string to the rs232 
47 void uart_sendstr(char *s) 
48 {
49         while (*s){
50                 uart_sendchar(*s);
51                 s++;
52         }
53 }
54
55 void uart_sendstr_p(const prog_char *progmem_s)
56 // print string from program memory on rs232 
57 {
58         char c;
59         while ((c = pgm_read_byte(progmem_s++))) {
60                 uart_sendchar(c);
61         }
62
63 }
64
65 // get a byte from rs232
66 // this function does a blocking read 
67 char uart_getchar(void)  
68 {
69 #ifdef VAR_88CHIP
70         while(!(UCSR0A & (1<<RXC0)));
71         return(UDR0);
72 #else
73         while(!(UCSRA & (1<<RXC)));
74         return(UDR);
75 #endif
76 }
77
78 // get a byte from rs232
79 // this function does a non blocking read 
80 // returns 1 if a character was read
81 unsigned char uart_getchar_noblock(char *returnval)  
82 {
83 #ifdef VAR_88CHIP
84         if(UCSR0A & (1<<RXC0)){
85                 *returnval=UDR0;
86                 return(1);
87         }
88 #else
89         if(UCSRA & (1<<RXC)){
90                 *returnval=UDR;
91                 return(1);
92         }
93 #endif
94         return(0);
95 }
96
97 // read and discard any data in the receive buffer 
98 void uart_flushRXbuf(void)  
99 {
100         unsigned char tmp;
101 #ifdef VAR_88CHIP
102         while(UCSR0A & (1<<RXC0)){
103                 tmp=UDR0;
104         }
105 #else
106         while(UCSRA & (1<<RXC)){
107                 tmp=UDR;
108         }
109 #endif
110 }
111