Saturday, December 13, 2008

Serial communication

The serial port of a PIC controller enables you to exchange information with other devices. Personally, I hook up every PIC to my PC via the serial port to debug my programs in real time. How? After the blink example, follow the steps:

Hardware setup
There is a lot of info on serial port hardware setup on the Internet. To get started it is good to know:
  • PC's all used to have serial ports with 9-pin male sub-D connectors. Today, standard serial ports become less common, especially on laptop computers. In case your PC does not have a serial port, get an USB to serial convertor.

  • Pin 2 and 3 of this connector contain the send and receive signal of the serial port. Pin 5 is ground.

  • The voltage on such a serial port range from +/- 3V to +/- 12V, wich is not compatible with the 0/5V range of PIC controlers. Use a 'level shifter' (often based on a max232 or alike) to convert the signal.

  • The output of the level shifter is connected to the RX and TX pin of the PIC.

If you need more info on this, Google is your friend!

Software setup

Now you have the hardware ready, you need to configure the Jallib serial_hardware lib, that uses the build-in USART to send and receive characters.

First, we have to set the desired speed:

const serial_hw_baudrate = 115_200

Next, include the library and call init:

include serial_hardware



Now you are ready to use the serial interface. So you can send a char like:


or use the pseudo-var interface to do the same:

serial_hw_data = "!"

To read a char, you can use the function serial_hw_read(). If there is a character waiting, it puts the char into the parameter var and returns true. If there is no character waiting, it returns false. So:

if serial_hw_read(char) then -- non-blocking

serial_hw_write(char) -- that's the echo...

end if

echo's back each character it receives. Be sure to call serial_hw_read often enough so no characters are lost.

An alternative way to receive characters is the pseudo-var:

char = serial_hw_data -- blocking receive
serial_hw_data = char

The first line puts the received character in variable char and the next echoes it back.
We've seen above that sending by the pseudo var is the same as calling the function. When receiving, there is a major difference: where there is no character waiting, function serial_hw_read immediately returns and program execution continues. This is called non-blocking.
When there is no character waiting when the pseudo-var is used, the program will wait until a valid character is received. So if it does not receive anything, it will wait forever!

How to continue
We've seen how to setup a hardware serial port, send characters and receive characters - either blocking or non-blocking. The test-program sample_serial_hardware.jal, provides a working example for the code shown.

Joep Suijs

No comments:

Post a Comment