Click here to Skip to main content
969 members (217 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.3K views
5 downloads
Posted 29 Feb 2012

RS-232 / RS-423 Communications With Microchip Technology's "PIC" Microcontrollers

, 29 Feb 2012
Rate this:
Please Sign up or sign in to vote.
Provides code and circuit designs for two-way communications between a PIC microcontroller and RS-232 / RS-423 devices such as terminals, the PC serial port, etc.


Introduction






Microchip Technology's "PIC" microcontrollers are characterized by the diverse suite of on-board peripherals they contain. Many PIC devices include an on-chip transceiver capable of interfacing with a variety of serial networks. Microchip refers to this transceiver as an "Enhanced Universal Synchronous/Asynchronous Receiver/Transmitter," abbreviated EUSART.






The EUSART is a general device, meaning that a bit of design work is necessary to interface it with a given real-world network. The article at hand describes a quick technique, including schematics and code, for interfacing many PIC chips directly with RS-232 devices such as a PC serial port or dumb terminal. This capability greatly enhances the utility of the PIC chip, which can now do such things as expose a user interface for configuration / control.






Background






The category "serial communications" encompasses a wide variety of basically similar technologies, which are all based on the use of a voltage differential to transmit one bit of a digital data at a time. These serial technologies differ greatly in their specifics, however. In particular, serial devices of different types exhibit big differences in such areas as the expected voltage levels, the speed at which data is transmitted, and the absence or presence of a definite clock signal for the transmission.






A common problem faced by the designer of serial communications circuitry is the relatively wide voltage range specified by RS-232 and related standards in comparison with most digital computing hardware. RS-232 specifies a waveform residing between -25V (defined as a digital 1) and +25V (digital 0). Digital devices typically operate in a 0V to +5V range, or less.






PIC chips are no exception. While the EUSART present on most PICs is (quite reasonably) advertised as compatible with RS-232, it is still incumbent upon the circuit designer to respect the electrical maxima of the PIC device. In practice, this means translating from an RS-232 serial waveform of ±15V to a so-called "TTL" waveform ranging from about 0V to 5V.






It is quite typical to use an IC such as Maxim's MAX232 to perform this translation. The MAX232 is a full-featured, reliable device. This article presents an alternative approach to the problem, based around a single, large PNP transistor. This is a handy technique when something like a MAX232 is not readily available; it is also noteworthy that the MAX232 requires auxiliary capacitors, which are not used in the design presented below. Nevertheless, for critical production circuits, a dedicated device like the MAX232 should certainly be considered. For development work - especially work involving the development of assembly-language-based firmware - the techniques given here should generally be adequate. The assembly language code shown here is valid for all cases, regardless of whether or not the MAX232 is used.






Much of the explanatory text below involves digital DC logic of the sort typically found in modern computers and electronics. The article aims to be as self-contained as possible. For example, photos and diagrams designed for easy accessibility to the layman are included in the hardware setup sections below. However, it is not possible for the article to discuss every aspect of DC-based logic. Many other online resources address the topic of basic digital logic, including this article by the same author.






Using the Code






The target platform for the demo as provided is Microchip's "Low Pin Count" (LPC) demo board, part number DM164120-1. This demo board consists of a PIC microcontroller placed onto a small prototyping board, without much else. This is sufficient to run a demo of PIC serial communications without much extra hardware. The LPC board comes with a PIC 16F690 microcontroller, a 20-pin device with ample serial communications ability.






The LPC board is typically purchased as a part of the "PICKit 2 Starter Kit" (see here and here), which has part number DV164120. The starter kit includes the PICKit 2 programmer, which is used to write programs to the PIC device. The programmer also powers the device, so that programs can execute after programming is completed. This PICKit 2 programmer connects to a standard Windows PC using a supplied USB cable. An installation CD for the MPLAB Integrated Development Environment is also included in the starter kit. This allows the developer to build object code from assembly language, and to write it to a variety of PIC devices using the PICKit 2 programmer.






While the discussion below gives specifics designed around the LPC board, information about portability is also given as appropriate, and the demonstration program should be capable of running on any PIC with a EUSART with only minimal changes. When targeting other devices, for example, it will be necessary to #include the correct .inc file instead of "16F690.INC." On some setups, it may be required to reduce the baud rate to 9,600, and instructions to do so are provided. Some applications will need to locate the code provided differently, meaning that the .org directive will need to be edited. Full-featured implementations of the techniques given here might even place object code into a relocatable block using a CODE directive. Finally, many pins have multiple functions on the various PICs; on some devices, it will be necessary to disable specific functions in order to allow for serial communications. The datasheet often summarizes the necessary steps in pseudocode format, in the section dedicated to the EUSART.






Whatever the specifics of a given architecture may be, though, the demonstration code / circuit provided should be basically adaptable to it. The code provided imposes few requirements on its target platform. It does not, for instance, allocate any SRAM or EEPROM storage, relying purely on the accumulator for storage. Also, care has been taken to make proper use of the banksel macro, in order to provide for portability to other PIC devices with their own register configurations.






The wiring techniques used below should also be applicable to a wide array of hardware, encompassing most families of digital logic, at least in the development realm. The basic need to translate between RS-232 and TTL voltage levels is inherent to any digital computing or control device which must perform RS-232 communications.






Finally, it should be noted that Microchip has recently released the PICKit 3 programmer. This is very similar to the PICKit 2, and can substitute for it without major changes in the demonstration below. However, the PICKit3 is packaged with a different demo board from the PICKit2 (in Microchip Part DV164131), and this requires some different wiring techniques (discussed below).






Demonstration 1 - PIC Transmission






This section of the article describes in detail how to wire up and run a one-way (PIC to terminal) communications demo. In the narrative below, the physical connection of the RS-232 circuit is described first. Then, instructions are given to program the PIC to run the demo program, and to view the PIC's transmissions in a terminal program.






Hardware Setup






The suggested hardware setup for the demo consists of the LPC demo board and PICKit 2 programmer, plus a PC. The PC will serve as host for the MPLAB IDE, and will thus be responsible for building the demo program from assembly language, and writing it to the Flash memory that the PIC uses to hold its firmware.






The PC will also serve as the terminal communicating with the PIC. RS-232 ports are no longer ubiquitous on general-purpose computers, but it is not difficult to find a USB-based adapter. During development, the Dynex UBDB9 adapter was used. RS-232 has also made a resurgence among business computers recently, e.g. in some iterations of the Toshiba Tecra laptop. The simple, deterministic nature of RS-232 and its related protocols is still the best choice for many applications. As shown below, the ease with which RS-232 interfaces with the PIC 16F690 IC is impressive, and this is a point in favor of the RS-232 protocol and its revival.






In all cases, it is advisable to disconnect power from both sides of the RS-232 connection prior to performing any wiring. Under the typical setup, where a USB / RS-232 adapter is used, it is possible to safely wire up the RS-232 link for the demo by first unplugging the USB connectors for:







  1. the PICKit 2 programmer, and  





  2. the USB / RS-232 adapter






This serves to remove power from both sides of the RS-232 connection, and allows the developer to wire up this connection without worrying about causing electrical damage. In cases where the PC has a true RS-232 port, it is prudent to power down the PC before wiring up the RS-232 link, at least during the initial setup. For a more robust application, a custom cable should eventually be fabricated. If made correctly, this cable will be sufficiently well-insulated to allow for a "hot swap" capability.






Two pins of the PC or terminal serial port are connected to the PIC in the demo below. The figures and explanations below refer to these two pins as they are typically located on a 9-pin "DB9" connector. It should be possible to apply these techniques to any RS-232 (or similar) device, though, so long as the three necessary pins can be located.






To transmit from the PIC to a terminal typically requires only two wires. A MAX232 or other device is not generally necessary in practice, especially for this simply one-way transmission. This is possible because, although the RS-232 standard allows for wide voltage swings in the transmission waveform, it also specifies that the terminal must be able to distinguish a wave ranging from -3V to +3V.






The PIC naturally generates a serial waveform ranging from 0 to +5V, with +5V serving as a digital one. So, beyond the issue of voltage range, the PIC waveform is inverted 180° compared to the equivalent RS-232 waveform, in which the bottom of the waveform (e.g. -15V) represents a logical one.






Fortunately, the PIC EUSART offers an "inverted" mode that corrects this problem; and although inverted mode does nothing to translate the 0-to-5V waveform to a ±3V waveform, it has been the author's experience that an RS-232 terminal will typically tolerate this slight shift in the expected waveform, so long as the EUSART is set to inverted mode. Again, in critical production applications, something like Maxim's MAX232 should be considered, in order to ensure a waveform that is fully standards-compliant. Also, it should be noted that the maximum cable lengths specified by the RS-232 standard will not necessarily be achievable using the techniques described here.






The PIC 16F690 emits serial transmissions from pin RB7. This is on the same side as pin 1 (which is marked with a dimple in most packages), but at the opposite corner. With pin 1 positioned at the top left of the assembly, as is the case in the PICKit 2 LPC demo board, pin RB7 is found at the bottom left corner of the microcontroller. In addition, a ground connection must be made; conveniently, the ground pin (Vss) of the PIC 16F690 is found at the exact opposite corner from pin RB7. In the case of the PICKit 2 LPC demo board, this will be the top right corner pin. The wiring diagram below shows a diagram of the LPC demo board, a hypothetical 9-pin RS-232 device, and the connections necessary between them:



In interpreting this diagram, note that the pins of the serial port are numbered from one, beginning with the top left pin if one holds the connector with the wide side up and facing toward one's self. Pin 2 is the next pin to the right in the top row of pins, and so on, with the smaller, bottom row of pins beginning with pin 6 at its left side. Pin 1 of the serial port is marked with a small "1" in the diagram above. Note also that, on the LPC demo board, the three holes adjacent to each PIC pin are connected to that pin. The connections in the diagram go to a convenient hole, but in a real application, any one of the three holes can be used. Or, in some cases, a connection onto the pin itself can be made. In any case, pin 2 of the serial port ("receive" or "RX") is connected to pin RB7 of the PIC. Pin 5 of the serial port (common ground) is connected to the Vss pin of the PIC.






Any convenient small-gauge wire can be used to make the actual connections necessary for communications. One approach is to use copper wire of about 20 AWG, together with female "D-Sub crimp pins" (Black Box part number FA820, or equivalent). The D-Sub connectors are designed to connect to the male pins of a terminal serial port, and a jumper wire can be crimped, or simply wrapped, onto them. The other end of the jumper wire can be threaded through the appropriate demo board hole and soldered to the board back.






Another approach is to use D-Sub connectors on the PIC side of the connection as well. These connectors actually slide easily onto the RB7 and Vss pins of the 16F690. This works for the 16F690 in the PICKit 2 Starter Kit, with its very accessible transmit and receive pins. In other applications - for example, if the PICkit 3 Debug Express Starter Kit, with its "surface mount" microcontroller, is used - this will not be possible. Instead, it will probably be necessary to solder connections to the demo board.






The two photographs below this paragraph show some details of the wiring setup described. The first image shows the pinout of the DX-UBDB9, with D-Sub crimp pins connected. The two necessary jumper wires are wrapped around the crimp pins. The second photo below shows a detail of the LPC demo board, around the PIC device itself.








In the implementation pictured above, D-Sub connectors are slipped directly onto the appropriate PIC pins to complete the two necessary connections. More robust techniques for making this connection are explored later in this article; the technique shown in the pictures above is adequate for a quick, one-way connection, but is not workable for anything more advanced.






After the RS-232 link has been wired, it is next necessary to set up the LPC board and PICKit 2 programmer for development. Instructions to do this are provided with the PICKit 2 starter kit. The starter kit includes a series of lessons in assembly language programming, and instructions for building each lesson's program and executing it on the LPC demo board. If you have obtained the PICKit2 and set it up correctly to program and run these lessons, then you should be set up for the demo program presented here. In summary, though, a USB cable connects the PICKit2 programmer to the PC, at the back of the programmer. At the other end of the programmer, a six-pin plug connects the programmer to the demo board. This setup also serves to power the 16F690, and the rest of the demo board, so that programs naturally execute after they are written to the microcontroller.






The MPLAB development environment must be installed as well, and will be the central location for development activities, including writing the assembled program to the PIC device. Again, instructions to do this are provided with the starter kit, and if you have obtained the PICKit2 and set it up correctly to program and run Microchip's assembly language lessons, then you should be set up for the demo program presented here as well. The main configuration menu item in MPLAB in need of attention on an unconfigured system will be the "Select Device..." submenu of the "Configure" menu, where the 16F690 (or other device, as appropriate) will need to be selected from the central drop-down control.






Also, note that each time MPLAB is opened, the correct programmer (e.g. "PICKit 2") will need to be selected from the "Programmer" menu. When this is done, MPLAB attempts to establish a connection to the programmer. The programmer, in turn, checks for the presence of the configured device (e.g. the PIC 16F690), and if there are any breakdowns in this chain of communication, this is reported by MPLAB.






Once MPLAB is up and running, and connectivity has been established, it should be possible to open the first demo program (PICRS232.ASM) and then build it using the "Quickbuild" menu item of the "Project" menu. Then, assuming everything is connected correctly, "Program" should be selected from the "Programmer" menu. This loads the object program into the Flash memory present on the PIC. Then, the PIC will begin execution at code location 0, where the demo begins. This first demo program transmits a constant stream of data to the terminal. The program will persist in the Flash memory of the PIC, even if power is removed from the device.






The final setup step for the first demo is to configure the terminal, or terminal program. In the development setup originally used to write the code presented here, the PICKit 2 Starter Kit communicated with Windows XP and Vista machines running the Hyperterminal terminal emulator program. This program was included with most versions of Windows prior to Vista; users of other versions of Windows can download Hyperterminal from Hillgraeve Software. Virtually every other general-purpose OS offers some sort of terminal program, and all of these should work for the demonstration given below. The communications settings in all cases will be 57,600 baud, 8 bit bytes, "No" parity, and one stop bit. "VT100" terminal emulation should be specified, although in fact any ASCII-based terminal or terminal emulator ought to work well with the setup provided in this article.






As a convenience for users of Hyperterminal, the ".HT" connection file appropriate for the demo has been included in the source code download ("PIC576.HT"). This can be opened in Hyperterminal (using "File, Open" or the file folder icon) to ensure that settings are correct.






Once the terminal is set up, a high-speed stream of incoming dot characters ('.') should be evident. An example of Hyperterminal receiving the output of the demo is shown below:



Firmware






The beginning of "PICRS232.ASM" is shown below this paragraph. This passage of code includes some preliminary directives, plus the entry point and first few instructions of the demo program:






 #include <p16F690.inc>
 __config (_INTRC_OSC_NOCLKOUT & _WDT_OFF & _PWRTE_OFF & 
    _MCLRE_OFF & _CP_OFF & _BOR_OFF & _IESO_OFF & _FCMEN_OFF)
 org 0
prog:
 banksel OSCCON
 movlw   B'01110000'   ; full 8mhz internal osc
 iorwf   OSCCON,f 





The first #include directive brings in definitions related to the 16F690 and its particular register configuration. This can be adjusted for applications with other processors. The next, __config directive begins by turning on the internal oscillator, with no clock signal out. This is done using setting _INTRC_OSC_NOCLKOUT. This setting is the simplest setting, since it removes any need to wire up an external oscillator, and since a clock signal out is not needed.






The remaining settings disable several features that are not used in this demo. In order, these are the watchdog timer, the power-up timer, the master clear feature, code protection, brownout reset, internal / external mode switchover, and the fail-safe clock monitor. In general, these features can be used with the communications techniques described here; but they are not used in this demo.






After these directives, the program proper begins at location 0. To start, three bits of the OSCCON register (the oscillator controller) are turned on, to indicate full 8mhz speed. This is done by the instruction iorwf OSCCON,f, which performs an inclusive OR operation between 01110000 binary and OSCCON. The result is stored in OSCCON, and indicated by the final ,f clause.






Note that banksel is used to ensure that the proper SRAM bank is selected for these operations. This is done generally throughout the demo code, whenever a special-purpose register is accessed. This practice reflects Microchip guidelines; banksel abstracts over the details of an evolving product line, where special-purpose registers are moving from page to page in different designs. The nature of the page selection instructions used to implement that macro is also evolving; see here or here for a Microchip presentation containing a description of the evolution of banksel.






Pseudocode for much of the remainder of the transmission demo program can be found in the PIC 16F690 data sheet. In the data sheet used during development (publication DS41262A), this could be found on page 141:







To set up an Asynchronous Transmission:







  • Initialize the SPBRGH:SPBRG registers for the appropriate baud rate. Set or clear the BRGH and BRG16 bits, as required, to achieve the desired baud rate.





  • Enable the asynchronous serial port by clearing bit SYNC and setting bit SPEN.





  • If interrupts are desired, set enable bit TXIE.





  • If 9-bit transmission is desired, set transmit bit TX9. Can be used as address/data bit.





  • Enable the transmission by setting bit TXEN, which will also set bit TXIF.





  • If 9-bit transmission is selected, the ninth bit should be loaded in bit TX9D.





  • Load data to the TXREG register (starts transmission).





  • If using interrupts, ensure that the GIE and PEIE bits in the INTCON register (INTCON<7:6>) are set.


--Microchip Publication DS41262A, page 141, section 12.3.1, "EUSART ASYNCHRONOUS TRANSMITTER"





The initialization of SPBRGH:SPBRG is handled by the snippet below:






 banksel SPBRG
 movlw   .34     ;34 -> ~57.6kbps@8mhz (207 for 9600bps )
 movwf     SPBRG
 banksel SPBRGH
 movlw   .0
 movwf     SPBRGH    





The code above sets the SPBRG register to 34 (decimal) and sets the SPBRGH register to 0. These values were obtained from the table titled "12-3: BAUD RATES FOR ASYNCHRONOUS MODES" in the PIC 16F690 data sheet. According to this table, when register SYNC = 0, BRGH = 1, BRG16 = 1, and BRG16 = 1, an SPBRG value of 34 decimal, at 8 mhz, will yield a transmission rate of 57,142 baud. Note that the "SPBRG" number quoted in the tables refers to the 16-bit value formed by SPBRGH:SPBRG. A value of 34 thus implies that SPBRGH is 0, and this is ensured in the code above.






The 57,142 baud rate is close enough to 57,600 for a typical terminal to correctly interpret the data. As noted in the comment in the last code block, replacing the value of 34 with a value of 207 will result in a transmission rate of ~9,600 baud. Making this change (in conjunction with an appropriate terminal configuration change) has several potential advantages. Certain hardware may not support the higher baud rate. Also, the 9,615 nominal rate given in the data sheet table is significantly closer to the ideal 9,600 baud rate than 57,142 is to 57,600. In rare cases, it may thus be necessary to use a 9,600 baud channel. Finally, many standards specify 9,600 baud, e.g. the MDB protocol used in vending machines.






The demo code continues with the section shown below:






 banksel TXSTA
 bcf     TXSTA,SYNC     ;async, i.e. timed by bits in the xmit stream
 banksel RCSTA
 bsf     RCSTA,SPEN
 banksel TXSTA
 bsf     TXSTA,TXEN     ;enable TX
 bcf     TXSTA,TX9      ;we want 8 bit
 bsf     TXSTA,BRGH     ;enable *64 baud generator w/o using SPBRGH
 banksel BAUDCTL
 bsf     BAUDCTL, BRG16
 bsf     BAUDCTL, SCKP  ;reverse polarity 





This code first sets up asynchronous (i.e. unclocked) mode by turning off SYNC, then enables the serial port by asserting SPEN. Next, TXEN is set to true in order to enable transmission capabilities. In this demo, an 8-bit word is used, so TX9 is turned off. Some protocols use a 9-bit word, and for these TX9 should be set to true; the MDB protocol mentioned earlier is in fact an example of a 9-bit protocol. Finally, the snippet above asserts SCKP to reverse the polarity of the transmission. The reasons for this were discussed above.






Just a bit more setup code is necessary before entering the transmission loop. This code enables interrupts, which are used in the demo. Three bits must be set: the transmit interrupt must be enabled by setting bit TXIE of the PIE1 register. Also, interrupts in general are enabled by setting bit GIE of the INTCON register, and interrupts for peripheral devices are enabled by setting bit PEIE of INTCON: These tasks are performed by the following code:






banksel PIE1
bsf PIE1,TXIE           ;Xmit interrupt on
 

 

banksel INTCON          ;General and peripheral interrupt enable
bsf INTCON,PEIE
bcf INTCON,GIE  





The demo code concludes with the following snippet:






userprog:
 

 

 movlw '.'
 call printch
 goto userprog
 

 

printch:
 

 

 banksel TXREG
 movwf   TXREG
 nop
 btfss   PIR1,TXIF
 goto    $-1
 return
 

 

 end





At userprog, the code enters an infinite loop. First, the ASCII character '.' (code 46 decimal) is moved to the accumulator. Then, function princth, which prints the ASCII character in the accumulator, is called. Finally, a goto instruction returns to the top of the loop.






Function printch operates by moving the value in the accumulator into the TXREG register, which is a latch for the output of the EUSART. This will take at least one instruction on the 16F690 at 8mhz, per the datasheet, so a NOP is executed. Then, the code enters a polling process, where it essentially blocks until the TXIF bit is set. Specifically, instruction btfss ("bit test file and skip if set") will execute the goto that follows it (i.e. will decrement the Program Counter and thus continue the polling loop) unless its operand bit is set. In this case, the operand bit is TXIF, which gets set when the EUSART has completed the serial output process. Once this has happened, the code is free to resume transmission, and printch therefore returns to its caller, i.e. the main loop of the program.






Demonstration 2 - Bidirectional Communications






The second demonstration shows an echo program, i.e., a PIC program which receives input from the terminal device and repeats it back to that device. While this demo is running, pressing a key at the terminal results in the associated character being displayed at the cursor position on the terminal. This result is only evident once the character has been transmitted to the PIC, processed by it, and echoed back to the terminal on a second channel. At 57,600 baud, though, this does not take long at all.






The code for the PIC firmware for this demonstration is present in the same archive as the first demonstration, and has file name "ECHO.ASM." Before the demo can be successfully executed, a two-way wiring scheme must be implemented.






Hardware Setup






The main obstacle to adding two-way communication to the setup described above is the electrical issue. The ±15V waveform typical of RS-232 cannot be fed to the PIC without destroying it. The PIC is a generally durable device, but it has little ability to handle negative voltage. In fact, section 17.0 of the datasheet ("Electrical Specifications") lists a maximum negative voltage on any pin compared to Vss of -0.3V. The RS-232 waveform can include sustained negative voltages of many times greater magnitude than -0.3V.






Beyond this voltage difference, the receive circuit must also deal with the fact that the RS-232 and TTL waveforms are inverted (i.e. differ by 180°) compared to each other. The SKCP bit used to correct this issue for transmission does not work for incoming data.






In the circuit described here, a PNP transistor is employed to deal with these issues. This transistor has Fairchild Semiconductor part TIP42, or equivalent; most electronics manufacturers sell a "TIP42" transistor.






The PNP transistor is a device which closes a switch-like circuit between two pins in response to a negative voltage applied to a third pin. This switch-like circuit is designed to flow negative voltage from a "collector" pin to an "emitter" pin. However, it can just as easily flow a positive voltage from the emitter to the collector; if the collector is connected to ground, the resultant backward flow will be electrically equivalent to a negative flow from collector to ground. The third pin, which controls the quasi-switch at the heart of the transistor, is termed the "base" pin.






In the circuit presented here, the collector is connected to the receive pin of the PIC (pin "RB5" or "12"), and the emitter to a +5V power source. This allows for a 0V / +5V incoming waveform, which is exactly what the EUSART expects. Furthermore, since the PNP transistor closes its circuit (i.e. supplies positive voltage) in response to negative voltage, it properly inverts the RS-232 signal, or at least the negative portion of it (which is all that is necessary to establish a square wave). Because the transistor connects to a +5V power source at the emitter, the PNP transistor will supply a maximum of +5V, i.e. it solves the voltage level problem as well.






Another electrical component is necessary to provide a reliable signal to the PIC: a pull-down resistor. When negative voltage is not present at the base of the PNP transistor, the quasi-switch connecting it to the +5V voltage source is open. The receive pin is thus connected to nothing at all. The logical value perceived by the PIC is therefore undefined. The pull-down resistor creates a relatively weak connection between the receive pin and ground. When no other connection is present, this resistor serves to place a logical zero value on the receive pin. The resistor can be connected between any of the holes connected to pin RB5 and the row of ground holes beneath (and to the right of) the PIC.






A 1,000 Ohm resistor is suggested for the demo circuit. A wide variety of resistors will in fact work for this purpose, though. So long as the connection provided by the resistor is weaker than that provided by the transistor, the desired effect will be obtained.






One final electrical consideration bears mention: it is the voltage level at the emitter of the PNP transistor that determines its ground voltage. Because +5V is present at the emitter in the circuit described here, this means that, for example, +4V will be perceived as -1V by the transistor. After all, relative to ground, +4V is one negative volt in this case. In theory, this introduces the possibility of misinterpreting a logical one as a zero. This will not be a problem, though, so long as the positive RS-232 signal used for a zero is at least +5V. Most devices should meet this requirement; signal levels of ±10 V, ±12 V, and ±15 V are typical. Even the ad hoc transmittal circuit described in the first demo uses a +5V signal for zero.






The diagram below this paragraph has the same format as the wiring diagram presented for the first demo, but adds the necessary circuitry for the receive function. The resistor is indicated by a line labelled "1000?." In all cases, when looking at the front of the transistor, the leftmost pin will be the base, the rightmost pin will be the emitter, and the middle pin will be the collector.



The next figure shows an electronic schematic of the total PIC / RS-232 interface as described thus far. This is done in the format typically used for such diagrams. More information about this format is available from many sources, including here and here.



A photograph of the entire setup is shown below this paragraph. Note that the use of unshrouded D-Sub connectors has been eliminated from this implementation. A neat DB-9 connector now surrounds the crimp pins used at the serial port. Several manufacturers make such hardware; examples include NorComp Part #170-009-273L000 and Tyco Part #205203-8. After being properly crimped down, the pins are simply pushed into the back of the appropriate hole of this enclosure. "Solder cup" D-Sub pins can be used instead of the crimp pins for an even more permanent connection. On the PIC side of the connection, each jumper wire is routed through one of the holes connecting to the appropriate pin, and then soldered to the back of the demo board.



In the implementation shown above, the TIP-42 transistor is held in the air by the three wires soldered to its pins, and is visible near the top left corner of the photo. It would be cleaner to solder this transistor's pins through holes in the LPC demo board's prototyping area. One obstacle to this approach is the fact that the circular soldering points in this prototyping area do not connect to each other at all. So, the TIP-42 could be soldered down to the prototyping area, but jumper wires would then have to be added to connect each pin of the transistor appropriately.






Firmware






The code for demonstration 2 is contained in file "ECHO.ASM." Its additions to "PICRS232.ASM" (the first demo) are discussed in this section, from the top of the file down. First, when RCSTA is being adjusted, some new code is necessary to enable receive mode:






banksel RCSTA
bcf RCSTA,CREN              ;NEW
bsf RCSTA,CREN              ;NEW
bsf RCSTA,SPEN  





Cycling CREN in this way serves first to clear any errors associated with the receive function of the EUSART, and then to enable continuous (versus clock-driven) receiving.






In addition, code to disable analog input AN11 must be executed. This is necessary because AN11 uses the same pin as the receive function (RB5). In the demo code, this is done immediately before interrupts are enabled:






banksel ANSELH          ;NEW
bcf ANSELH,ANS11        ;NEW





Then, when interrupts are enabled, bit RCIE must be set in addition to TXIE. This enables the "receive" interrupt:






banksel PIE1
bsf PIE1,RCIE           ;NEW
bsf PIE1,TXIE   





In the main loop of the program, the literal load movlw '.' is replaced with a call to function getch. This waits for a character to arrive on the serial port, and places it in the accumulator. Because the call to getch is followed by a call to printch, the net effect will be a character-for-character echo back of whatever is typed at the terminal. The code for getch is inserted just before the end directive, and takes the following form:






getch:
 banksel PIR1
 btfss PIR1,RCIF
 goto getch
 movf RCREG,w
 return





First, this function polls RCIF to await data. This blocks the thread-of-execution in a fashion similar to that seen in printch. There, the program had to wait for output to complete. Here, the program must wait for input to arrive, and although the associated bit is different, the technique (skippable goto) is the same. Once the data has arrived, it is moved from register RCREG to the accumulator, and a return back to the main program loop is executed. There, a call to printch completes the echo functionality.






History







  • 23rd June, 2010: First major version of this article






If this article is well-received, I hope to follow it with other articles that make use of the capabilities described here, and extend them.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

_beauw_
United States United States
I was educated at Southern Miss.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
RA-Web1 | 2.8.170813.1 | Last Updated 29 Feb 2012
Article Copyright 2012 by _beauw_
Everything else Copyright © RootAdmin, 1999-2017
Layout: fixed | fluid