Fads to Obsessions and Beyond...




Free domain for life, exceptional technical support, website transfer

USART (RS232) Serial Comms Module

Demonstrate the necessary circuitry and software (firmware) to utilise the USART on PIC microcontrollers to interface with PC (or other device) using RS-232 protocol.

Communication between a PIC microcontroller and a personal computer (PC) and or between PIC microcontrollers is a requirement of many projects. For example, monitoring and logging of temperature using a DIY Digital Thermometer or enabling PC control of stepper motors for positioning of various devices.

PIC microcontrollers have a USART (Universal Synchronous Asynchronous Receiver Transmitter) which implements the RS-232 protocol enabling PIC microcontrollers to be either transmitters or receivers of serial data. RS-232 is just a set of standards for serial transmission of data (1) which specifies the actual electrical signal characteristics, form of physical connectors etc, and the PIC microcontroller USART implements these requirements.

Even though RS-232 is now largely superceded on the majority of "consumer" equipment (due to relatively low transmission speed compared to current norms and large voltage swing of signal lines) it is mature technology (i.e., well known and now low cost) that is readily and easily applicable in the DIY environment, and with USB-to-RS232 converters being cheaply available, still very useful to the DIY hobbyist in interfacing projects to PC's, laptops etc.

The actual details of the RS-232 protocol and the relevance of parallel versus serial, synchronous and asynchronous transmission, baud rate, start/stop bits and the details of the associated registers in the PIC microcontroller is left to the interested reader referencing the plethora of sites on the web (2). However, one item of particular relevance from the RS-232 standard is that voltages below -3V represent logic "1" and voltages above 3V represent logic "0". Since the PIC microcontroller I/O pins operate 0 to 5V, voltage level conversion circuitry is required. This is generally handled by the now ubiquitous MAX232 IC or similar.

The Testing/Experimental Results Section demonstrates the use of CCS C code to implemented RS-232 connectivity between a PIC 18F248 and PC using a MAX232.


The minimum requirements for a PIC (PIC16 and PIC18 dealt with here) are:

  • Power Supply (generally 5V, but 3.3V also widely available)
  • Oscillator (RC network, external crystal oscillator)
  • In-circuit serial programming (ICSP) - to upload hex code

Power Supply

A typical "wall-wart" power-supply is used (a surplus laptop charger in this case) in conjunction with a voltage regulator (LM7805) to provide the regulated 5V required by the PIC microcontroller.

The 'wall-wart' avoids resorting to the use of a transformer/rectifier with AC input etc (after which likely a LM7805 would be used in any case to provide load and line regulation). As a 'disclaimer', the DIY hobbyist should avoid dealing with AC power as a general rule.

Oscillator

An external crystal oscillator is used (X1 in the schematic) with associated capacitors C1 and C2. The PIC datasheet specifies a range of suitable capacitance values for C1 and C2 depending upon the oscillator frequency being used. Higher capacitance will increase the stability of the oscillator but will also increase the start-up time.

Note, the oscillator crystals can be either series or parallel cut. The PIC18FXX8 oscillator design requires the use of a parallel cut crystal.

In-circuit serial programming (ICSP)

I use a PICkit2 as the ICSP. Connection is as per the Microchip recommendations.

PIC microcontrollers can be serially programmed while in the end application circuit (i.e don't need to remove the component). This is simply done with two lines for clock and data and three other lines for power, ground and the programming voltage. This means the microcontroller can be programmed with the latest firmware and or updated as required. The Flash program memory is readable, writable and erasable during normal operation over the entire Vdd range.

MAX232 - Voltage Level Converter

As noted in the Project Background Section, the RS-232 standard operates at voltage levels outside those provided by PIC microcontroller I/O pins, and hence the MAX232 IC is used to provide the necessary voltage conversion of received and transmitted signals. The circuit implementation for the MAX232 is standard as per the datasheet.

Other

A resistor and diode is connected to pin 1 of the PIC. This is to take advantage of the PIC power-on reset (POR) circuitry, which requires MCLR (pin 1) connected directly (or through a resistor) to Vdd. The diode is to provide protection against incorrect voltage polarity.


Note: Image loading can be slow depending on server load.

  • PIC Schematic - RS232PIC Schematic - RS232

    Silver Membership registration gives access to full resolution schematic diagrams.

    PIC Schematic - RS232

    PIC Schematic - RS232 Interface to PC

This project did not require a PCB.

The construction was done using a DIY PIC development board. See the photographs and schematic diagram sections.

Qty Schematic Part-Reference Value Notes
Resistors
2R1-R310K1/4W, 10% 
Capacitors
2C1,C222pFCeramic 
1C30.33uF 
1C40.1uF 
5C5-C101uF 
Diodes
1D21N-4001 
Integrated Circuits
1U1PIC18F248PIC microcontroller datasheet
1U27805Linear Voltage Regulator  datasheet
1U1MAX232ERS232 Driver/Receiver datasheet
Miscellaeous
1J1CONN-H55-pin connector for ICSP
1SW1SW-SPDT 
2SW2SW-SPDT-MOM 
1X110MHzCrystal Oscillator
Description Downloads
RS232 - Bill of Materials Text File Download

Before connecting the PIC, check the supply voltages to ensure that the linear voltage regulator (or other power supply scheme) is supplying optimally 5V. Note (from datasheet), absolute maximum voltage on Vdd with respect to Vss is -0.3V to +7.5V.

In terms of the actual MAX232, ensure that the polarity of the electrolytic capacitors are correct, and that a 10uF (or similar value) by-pass capacitor is installed as close to the MAX232 as possible.

The TX pin of the MAX232 goes to the RX of the PIC and vice-versa.

Programming the PIC

The CCS compiler C compiler provides driver code for the PIC USART RS-232 which makes the firmware/software relatively straight forward. The following line of code is required:


              
#use rs232(baud=9600,parity=N,xmit=PIN_B6,rcv=PIN_B7,bits=8, ERRORS)
              
              

The #use rs232 directive provides the compiler the information about the RS-232 connection to be made, which includes (as is fairly obvious from the statement syntax) items such as baud rate, parity etc). The inclusion of the ERRORS directive is important. This instructs the compiler to "reset" the hardware USART due to buffer overrun conditions if they occur. This avoids "hanging" the USART.

The following code snippet demonstrates the code necessary to interface a PIC microcontroller with a PC to receive data (using a MAX232). The code includes an timer interrupt driven routine that flashes a LED at ~2 second intervals to provide feedback that the programme is running. When a character is received by the PIC micrcontroller (sent with a suitable terminal program on the PC), it is echoed back to the PC with a suitable status message.

Code Snippet 1:


#include <RS232.h>
#zero_ram //all variables automatically initialised to 0

int8 readCount = 0;
int8 toggleReadCount = 0;

#int_timer1
void timer1_interrupt() { /* Timer1 has wrapped around to 0. */
   toggleReadCount=1;
   set_timer1(3035); //prescaler=8, 10Mhz, preload=3036 -> Freq 5hz, period=0.2sec
}
        
void main() {
   char recChar;  //the received character from the serial port via keyboard
   setup_timer_1(T1_INTERNAL | T1_DIV_BY_8); //prescaler 8
   enable_interrupts(GLOBAL); 
   enable_interrupts(INT_TIMER1); 
   printf("\n\rstart\n\r");
   
   while(TRUE){      
     if (toggleReadCount==1) {
         toggleReadCount = 0;
         readCount++; //10 counts of 0.2sec = read every 2 secs 
      }
      if (readCount>=10) { //10 counts of 0.2sec = read every 2 secs 
         output_toggle(PIN_B0); //flash LED to show program active
         readCount = 0;
         toggleReadCount = 0;
         set_timer1(3035); //prescaler=8, 10Mhz, preload=3036 -> Freq 5hz, period=0.2sec
      }
      if (kbhit()) { //if character received by RS232 then process data     
         recChar = getc();
         printf("received=%c \n\r",recChar);
         switch (recChar) {
            case 'c':
            case 'C': printf("cmd C\n\r");
                      break;
            default:  printf("Unknown cmd\n\r");
                      break;
         }
      }
   }
}   
   				

Before connecting the PIC, check the supply voltages to ensure that the linear voltage regulator (or other power supply scheme) is supplying optimally 5V. Note (from datasheet), absolute maximum voltage on Vdd with respect to Vss is -0.3V to +7.5V.

If the RS232 communications fail, carefully check your breadboard circuit against the schematic and the photographs in the Photographs Section. Look for "gotcha's" like the connection polarity of capacitors etc.

I found that the inclusion of a 10uF by-pass capacitor (i.e., capacitor connected between Vdd and Gnd pins) as close to the MAX232 as possible was necessary to give "glitch" free operation of the RS-232 connection.

Another source of potential problems is that the baud rates that are acceptable are determined by the PIC crystal frequency (or more correctly the limited divider range of the PIC baud rate generator in the microcontroller IC). With the "usual" PIC16F and PIC18F parts and crystals of 10-20 MHz baud rates up to 19200 have not proven to be a problem (maybe "non-intuitively" slower baud rates with higher frequency crystals can be problematic). Refer to the relevant datasheet for calculation of acceptable baud rates from desired crystal frequencies (which depends upon particular PIC parts, width of available registers etc).

Note, the TX pin of the MAX232 goes to the RX of the PIC and vice-versa.

Finally, if using the CCS C complier, include ERRORS in the #use rs232 statement. If not using the CCS C compiler, use the equivalent of the relevant compiler as if the OERR or FERR flags are set in the internal PIC microcontroller (due to USART buffer overflow condition), then the CREN flag needs to be cleared and re-enable the USART (the datasheet contains the full procedure, but much easier and less error prone if leave it to the compiler).


Comments/Questions

No comments yet.

Add Comment/Question

Only Logged-In Members can add comments

"If we could sell our experiences for what they cost us, we'd all be millionaires".

Please donate any amount to help with hosting this web site.

If you subscribe (only $2/annum) you can view the site without advertisements and get emails abouts updates etc.

X

Sorry!

Only logged-in users with Silver Membership and above can download.


Silver Membership is only $2, so join now!