Last month, I showed how to use Visual Basic .NET to transfer data via a
PC’s serial ports, including USB virtual COM ports. I described a Visual Basic
application that sends commands and receives responses from a device
connected via a serial port. This month, I’ll show a companion PICBASIC
PRO program for a PIC microcontroller. The program detects received
commands, takes requested actions, and sends responses. I’ll also show
how to use an RS-422 interface to create serial links as long as 4,000 feet.
Serial Port Hardware
‘ Define the oscillator’s frequency in MHz.
‘ The default = 4.
I wrote the code in this article for a PIC18F4520
microcontroller. Like many PICs, the 4520 has a
built-in serial port. The chip’s EUSART manages serial
communications and supports an asynchronous mode
that is compatible with serial ports on PCs. PORTC. 6
(TX) is the serial output, and PORTC. 7 (RX) is the
I ran the code on Microchip’s PICDEM 2 Plus
development board. On the board, the PIC’s serial port
interfaces to a MAX3232 chip, which converts between
the PIC’s 5V signals and RS-232 voltages. The board
has a nine-pin female D-sub connector for the RS-232
Most RS-232 serial ports on PCs have male nine-pin
D-subs. USB/RS-232 adapters are also available with these
connectors. To connect a PICDEM 2 Plus board to a serial
port on a PC, use a straight-across cable, not a null-modem cable or adapter, which swaps the lines in the
cable. If in doubt, use an ohmmeter. If you probe pin 2 of
each connector on the cable, and the resistance measures
close to zero, you have a straight through cable.
Why use a serial port and not USB? Serial ports are a
good choice when you want to keep things simple and
inexpensive. The program code to access a serial port is
less complex than what’s required to communicate via
USB. Plus, the number of microcontrollers with embedded
serial ports is much greater than those with embedded
define OSC 4
‘ Enable the port and receiver.
define HSER_RCSTA 90h
‘ Enable the transmitter and set BRGH = 1.
define HSER_TXSTA 24h
‘ Set the bit rate.
define HSER_BAUD 1200
‘ Clear serial-port overflow errors automatically.
serial_in var BYTE
received_text var BYTE
‘ PORTB.1 is an output that drives an LED.
TRISB.1 = 0
‘ Enable unmasked peripheral interrupts
INTCON = %11000000
‘ Enable the serial receive interrupt
PIE1 = %00100000
on interrupt goto receive_serial_data
‘ The main program loop.
Accessing the Port
‘ Perform additional actions here.
Listing 1 is PICBASIC code that configures the PIC’s
serial port and runs the main program loop. (The complete
code plus a Visual Basic .NET project to use with it are end
LISTING 1. A series of
registers configures the serial
port and the serial interrupt.
May 2008 67