PIC RS232

From Mech
Revision as of 18:52, 20 February 2008 by Lynch (talk | contribs)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Code on the PIC

The essential line is #use rs232(baud=19200, UART1). This sets up the PIC's hardware UART. The PIC can also can do software RS232, but that is susceptible to mistiming caused by interrupts.

Once the UART is set up, you can use most of the usual C serial i/o functions, such as printf(). There's no scanf() in PIC C, and be sure to read about the formatting codes (%d and so on.)

Note - Characters transmitted to the PIC faster than your program reads them cause the UART to choke. After that happens, kbhit() never returns TRUE again, and no characters can be read. So use PIC RS232 input with care. If you want reliable input you have to set up an interrupt on incoming characters.

#include <18f4520.h>
#fuses HS,NOLVP,NOWDT,NOPROTECT        
#use delay(clock=20000000)         // 20 MHz crystal on PCB
#use rs232(baud=19200, UART1)      // hardware UART; uses  RC6/TX and RC7/RX  
 
int16 i;
int j;
 
void main() {
 
   while (TRUE) { 
    
      for (i=1; i<10000; i++) {
         printf("Hello world. %Lu %u\r\n", i, j);  // \r is carriage return, \n is scroll up
         delay_ms(100);
         if (kbhit()) j = getc();     // type slowly so kbhit() doesn't choke
      }
   }
}


Serialconfiguration.gif


Configuring your COM port and the Loopback Test

Shown at right are the usual configuration options for the COM port on your computer. Baud rate must match that of the PIC. There is the problem of which COM port to select, and whether the one you have made electrical connection to (through a DB-9 connector) is that one.

To check your COM port, try the Loopback Test. With the DB-9 disconnected, if you type "hello" into the text window ("serial port monitor") you will not see "hello" appear in the window, because your characters went out on pin 3 of the DB-9. The window shows only characters arriving on pin 2 of the DB-9; there is no Local Echo. If you connect pin 2 to pin 3 temporarily and type again, you will now see your words. Thus you have identified electrical signals that correspond to your COM port and text window.

Typical other problems are:

  • Different baud rates (sometimes resulting is garbled transmission, sometimes no transmission)
  • DB-9 pins 2 & 3 (computer receive and transmit) not going to partner's transmit & receive, respectively
  • You didn't level shift appropriately and now things are burned out.
  • Partner (e.g. PIC) is not transmitting anything. Look with a scope and see if there's anything happening on partner's transmit line.

Textwindow.gif