This example shows how to use the port library. It demonstrates setting up, reading and writing an I/O port.
Figure 2-1. source code ioport.c
void main(void) { DDR(PORTL,IIIIOIII); /* set PORTL.3 to an output */ while(1) /* loop forever */ PORTLD.3 = !PORTLD.3; /* toggle the output pin */ }
Including port.h gives your program access to the I/O port macros and predefined port symbols. The I/O port library defines macros that make it easy to configure and address I/O ports from within the C source.
The DDR() macro is available to set the port's data direction register. DDR() uses symbols to determine the data direction of port bits in a device-independent manner. For instance, the symbol IIIIOIII sets all bits as inputs except bit 3. In the port library, this identifier is defined as 0b00001000. The bit pattern symbols help avoid typographical errors, but more importantly, they make your program more portable.
Identifiers for the ports themselves are given in the device header file. You can address individual port bits using the '.' structure notation. For example, PORTLD.0 is the least significant bit and PORTLD.7 is the most significant bit of port PORTLD. The port bit is treated as a boolean type.
Figure 2-2. compiler listing file output ioport.lst
void main(void) { DDR(PORTL,IIIIOIII); /* set PORTL.3 to an output */ while(1) /* loop forever */ 0200 BC D1 08 LD 0D1,#08 PORTLD.3 = !PORTLD.3; /* toggle the output pin */ 0203 98 01 LD A,#001 0205 9F D0 LD B,#0D0 0207 73 IFBIT 03,[B] 0208 64 CLRA 0209 92 00 IFEQ A,#000 020B 02 JP 0020E 020C 7B SBIT 03,[B] 020D 01 JP 0020F 020E 6B RBIT 03,[B] 020F F3 JP 00203 }