Frequently Asked Questions

How does one map a variable to an I/O port?

Two methods are as follows:

#byte PORTB = 6 
#define ALL_OUT 0 
#define ALL_IN 0xff 

main() { 
   int i;
   set_tris_b(ALL_OUT); 
   PORTB = 0; // Set all pins low 
   
   for(i=0;i<=127;++i) // Quickly count from 0 to 127 
      PORTB=i; // on the I/O port pin 
   
   set_tris_b(ALL_IN); 
   i = PORTB; // i now contains the portb value. 
}

Remember when using the #BYTE, the created variable is treated like memory. You must maintain the tri-state control registers yourself via the SET_TRIS_X function.

Following is an example of placing a structure on an I/O port:

struct port_b_layout {int data:4; int rw:1; int cd:1; int enable:1; int reset:1; }; 
struct port_b_layout port_b; 
#byte port_b = 6 
struct port_b_layout const INIT_1 = {0, 1,1,1,1}; 
struct port_b_layout const INIT_2 = {3, 1,1,1,0}; 
struct port_b_layout const INIT_3 = {0, 0,0,0,0}; 
struct port_b_layout const FOR_SEND = {0,0,0,0,0}; // All outputs 
struct port_b_layout const FOR_READ = {15,0,0,0,0}; // Data is an input 

main() { 
   int x; 
   set_tris_b((int)FOR_SEND); // The constant structure is 
            // treated like a byte and 
                     // is used to set the data direction 
   port_b = INIT_1; 
   delay_us(25);
   port_b = INIT_2; // These constant structures
   
   delay_us(25); // are used to set all fields 
   port_b = INIT_3; // on the port with a single command
   set_tris_b((int)FOR_READ); 
   port_b.rw=0;      // Here the individual 
   port_b.cd=1;      // fields are accessed 
   port_b.enable=0;  // independently. 
   x = port_b.data; 
   port_b.enable=0; 
}

C-Aware IDE Demo
Embedded C Learners Kit
EZ App Lynx