Monday, March 24, 2014

Microchiping - I/O Ports

I/O ports are the interface between the uC and the outside world. Every pin of a port can be configured as a digital input/output. Some of them can also be configured as analog inputs.

There are 4 registers used to configure and control I/O ports on PIC16F1938:
  • TRISx Register - Sets up the direction of the port pins;
  • PORTx Register - Used for reading the values of the port pins;
  • LATx Register - Used to set the values of the port pins;
  • ANSELx Register - Sets up the analog/digital function for port pins.
Note: The 'x' from every register name should be replaced with the corresponding letter!


Set up the port direction - TRISx Register

Setting a TRISx bit will make the corresponding pin an input and clearing a bit from the TRISx register will make the corresponding pin an output. To remember it easier I use the following association:
  • 1 - 'i' - input.
  • 0 - 'o' - output.

If you want to set the pins 0, 3 and 4 of the port B (8 bit port) as inputs and the rest of them as outputs you will write the following code line:

   TRISB = 0b00011001;


Reading the port value - PORTx Register

The port pins are set up as inputs. How do you read the value of the port?! You simply read the value of the associated PORTx register.

Let's say the logic levels on pins 2, 3 and 6 are high and the others are low. The value of the port will be 0b01001100 (76 - decimal). The next code lines will run until the value of the port will be greater then 100:

   while(PORTC <= 100) {

      valueSum = PORTC;
      counter++;

   }

You can also read the value of one single pin by using the name of the corresponding bit. For example if you only need to execute some code if the logic level on pin 5 is high:

   if(PORTA.B5 == 1) {

      // code to run

   }


Setting the port value - LATx Register

Your port is set up as output. To set the logic levels on the port bits you only need to write the apropriate value on the associated LATx register.

For example if you need high output levels on pins 7, 6 and 4, value of the LATx register will be 0b11010000 (208 - decimal).

   LATB = 0b11010000;

If you only need to set up the output level of one single pin, use the corresponding bit:

   LATB.B2 = 1;


Enabling/disabling analog function of the port - ANSELx Register

Setting a bit in the ANSELx register will assign the corresponding pin as analog input and will disable the digital input buffer.

Clearing a bit in the ANSELx register will make the corresponding pin function as a digital I/O.

If the pins 0 and 1 need to be configured as analog inputs and the rest of the port as digital I/O, register ANSELx gets the following value:

   ANSELA = 0b00000011;

No comments:

Post a Comment