Debian Codegraph @

kpy/mh-soft-uart.c

raw symbols SCIP
1 /*
2 mh-soft-uart.c : Soft Serial Communication functions for Atmega32 on MicroHOPE
3 Tx on PD3
4 Rx on PD2 (uses INT0)
5
6 Author : Ajith Kumar, Inter-University Accelerator Centre, New Delhi
7 Licence : GNU General Public License version 3 or above
8 Date : 5-Feb-2014
9 */
10
11 #include <avr/io.h>
12 #include <avr/interrupt.h>
13
14 #define RXBIT PD3
15 #define TXBIT PD4
16
17 //delay between bits for a given baudrate, valid only for 8MHz clock
18 void bit_delay (uint16_t baudrate)
19 {
20 volatile uint16_t x;
21 switch(baudrate) {
22 case 38400: // this is only to mark the first middle point
23 x=9;
24 while (x--);
25 break;
26 case 19200:
27 x=22;
28 while (x--);
29 break;
30 case 9600: // 104 usecs per bit
31 x=54;
32 while (x--);
33 break;
34 case 4800:
35 x=105;
36 while (x--);
37 break;
38 case 2400:
39 x=215;
40 while (x--);
41 break;
42 default:
43 break;
44 }
45 }
46
47 #define UBSIZE 128
48 uint16_t baudrate = 9600;
49 uint8_t uart_buf[UBSIZE]; // Rx buffer
50 volatile uint8_t ubrd, ubwrt, ubcount; // read/write indices and count
51
52 ISR (INT1_vect) // interrupt triggered on a falling edge on PD3
53 {
54 uint8_t bit, val = 0;
55
56 if(ubcount == UBSIZE) return; // Rx buffer is full
57
58 bit_delay(baudrate*2); // wait till the middle of the start bit
59 if ( (PIND >> RXBIT) & 1) return; // False trigger
60
61 for(bit =0; bit <= 7; ++bit)
62 {
63 bit_delay(baudrate);
64 if (PIND & (1 << RXBIT)) val |= (1 << bit);
65 }
66 bit_delay(baudrate);
67 if (PIND & (1 << RXBIT)) // stop bit high ?
68 {
69 if (ubwrt == UBSIZE) ubwrt = 0;
70 if(ubcount++ < UBSIZE)
71 uart_buf[ubwrt++] = val;
72 }
73 }
74
75 void disable_uart(uint16_t baud) // Only 2400, 4800, 9600 and 19200 are allowed
76 {
77 DDRD &= ~(1 << TXBIT); // Transmit pin as input
78 GICR &= ~(1<<INT1); // Disable INT1
79 cli(); //disable interrupt globally
80 }
81
82 void enable_uart(uint16_t baud) // Only 2400, 4800, 9600 and 19200 are allowed
83 {
84 baudrate = baud;
85 ubrd = ubwrt = ubcount =0;
86 DDRD |= (1 << TXBIT); // Transmit pin as output
87 PORTD |= (1 << TXBIT); // and set it HIGH
88
89 PORTD |= (1 << RXBIT); // Enable pullup on PD3 (INT1 pin) receive pin
90 MCUCR |= (1<<ISC11); // Falling edge on INT1
91 GICR |= (1<<INT1); // Enable INT1
92 sei(); //enable interrupt globally
93 }
94
95 uint8_t uart_read() // Should be called only if ubcount > 0
96 {
97 if (!ubcount) return 0;
98 --ubcount;
99 if (ubrd == UBSIZE) ubrd = 0;
100 return uart_buf[ubrd++];
101 }
102
103 uint8_t uart_rxdata()
104 {
105 return ubcount;
106 }
107
108 void uart_write(uint8_t ch)
109 {
110 uint8_t bit;
111
112 PORTD &= ~(1 << TXBIT);
113 bit_delay(baudrate);
114 for(bit=0; bit <= 7; ++bit)
115 {
116 if(ch & 1)
117 PORTD |= (1 << TXBIT);
118 else
119 PORTD &= ~(1 << TXBIT);
120 ch >>= 1;
121 bit_delay(baudrate);
122 }
123 PORTD |= (1 << TXBIT); // stop bit
124 bit_delay(baudrate);
125 }
126