2 *** Serial Port driver for 16f1455 and kin
9 /* outgoing text buffer */
14 /* incoming text buffer */
19 void serial_init(void)
21 /* Enabling transmitter 26.1.1.1 page 259 - TX/CK I/O pin */
25 /* Enabling receiver 26.1.2 page 262 - RX/DT I/O pin */
28 /* Switch serial port to alternate pins */
29 APFCON0bits.RXDTSEL = 1;
30 APFCON0bits.TXCKSEL = 1;
34 /* Select pins 4&5 as the uart - page 102 */
35 TRISAbits.TRISA4 = 0; /* RA4 as TX output */
36 TRISAbits.TRISA5 = 1; /* RA5 as RX input */
38 #if _XTAL_FREQ != 32000000L
39 #error "Adjust serial port baudrate settings"
42 /* assume 32MHz clock, 19k2 baud */
44 BAUDCONbits.BRG16 = 1;
47 /* Enable interrupts */
51 /* enable uart receiver interupt */
56 /* is the queue empty yet */
59 if (outp == 0) return 1;
63 /* new message in the queue */
64 void msg_write(const char *msg)
66 char * p = outbuff + outlen;
67 while (outlen < sizeof(outbuff) && *msg != 0) {
78 void msg_writebyte(const char msg)
80 if (outlen+1 >= (uint8_t)sizeof(outbuff)) return;
81 outbuff[outlen++] = msg;
89 /* some library functions will use this if defined, eg printf */
95 /* called from interrupt routine to send next char */
96 void msg_sendnext(void)
98 /* we have finished, turn off the iterrupt */
99 if (outp == 0 || *outp == 0) {
109 /* called from interrupt routine to receive next byte */
110 void msg_recvnext(void)
112 while (PIR1bits.RCIF) {
113 /* bad char, skip it */
114 if (RCSTAbits.FERR) {
115 RCREG==0?0:0; // discard by reading
119 /* our input buffer has overflowed */
120 if (inlen > sizeof(inbuff)) {
121 RCREG==0?0:0; // discard by reading
126 inbuff[inlen++] = RCREG;
130 /* is there text waiting to be read */
131 bool msg_recvready(void)
133 if (inlen > 0) return 1;
137 /* read next byte from inpout buffer */
140 if (inlen == 0) return 0;
142 /* record and disable the interupt */
143 bool in = PIE1bits.RCIE;
146 char new = inbuff[0];
149 /* shuffle them down one */
150 for (char i=0;i<inlen;i++)
151 inbuff[i] = inbuff[i+1];
153 /* restore the interupt */
158 inline void msg_flush(void)
160 while (!msg_empty());