Wednesday, October 2, 2013

PIC12F1822 UART loop test

A good way to start playing with the UART interface of a microcontroller is to do a loop test. You simply receive a character and send it right back. The PICKIT2 has a built in UART tool which is perfect for experimentation, since you can program the device and test the UART without disconnecting the PICKIT2.

I've set the baud rate to 31500 symbols/s, since this is the MIDI standard.

UART loop test using the PICKIT2 UART tool.






Loop test source code

1:  //Uart RX/TX loop test using PIC12F1822  
2:  #include <xc.h>  
3:    
4:  //Configuration bits  
5:  #pragma config WDTE=OFF, PWRTE = OFF, MCLRE=OFF, BOREN=OFF, FCMEN=OFF, CLKOUTEN = OFF, IESO=OFF, FOSC=INTOSC, CPD=OFF, LVP = ON, BORV = 0  
6:    
7:  void main()  
8:  {  
9:    //Set all I/O's to digital  
10:    ANSELA = 0x00;  
11:    
12:    //0 Internal oscillator, 3 <fosc> on, 6-4 4MHz  
13:    OSCCON = 0b01101000;  
14:    
15:    //Interrupt controller  
16:    //6 Peripheral interrupt enabled  
17:    //7 Global interrupt enabled  
18:    INTCON = 0b11000000;  
19:    
20:    //TRISA  
21:    //RA1 set as input, all other IO's set as output  
22:    TRISA = 0b0000010;  
23:    
24:    //Free running bad rate timer is 7  
25:    SPBRGH = 0x00;  
26:    SPBRGL = 0x07;  
27:    
28:    //TXSTA: TRANSMIT STATUS AND CONTROL REGISTER  
29:    //8-bit transmission, transmit enable, asynchronous mode, high baud rate selected  
30:    //Baud rate is FOSC/[16 (n+1)] = 4MHz/(16 (7+1)) = 31250, approx 31500 symbols/sec  
31:    TXSTA = 0b10100110;  
32:    
33:    //RECEIVE STATUS AND CONTROL REGISTER  
34:    //Serial port enabled, continuous receive enabled  
35:    RCSTA = 0b10010000;  
36:    
37:    //PERIPHERAL INTERRUPT ENABLE REGISTER  
38:    //USART Receive interrupt enabled  
39:    PIE1 = 0b00100000;  
40:    
41:    //Loop forever  
42:    while (1)  
43:    {  
44:    }  
45:    
46:  }  
47:    
48:  //Interrupt service routine  
49:    
50:  interrupt void isr(void)  
51:  {  
52:    
53:    //If receive interrupt is triggered, transmit received symbol  
54:    if (RCIF)  
55:    {  
56:      TXREG = RCREG;  
57:    }  
58:    
59:    return;  
60:  }  

2 comments: