Question about arrays and port bits

Discussion in 'Embedded Systems and Microcontrollers' started by hunterage2000, Jun 7, 2015.

  1. hunterage2000

    Thread Starter Active Member

    May 2, 2010
    Hi, Does anyone know a way of using port bits in an array? I want to use indexes to turn on a port bit i.e PORTAbits.RA0 = 1 for index 0, PORTAbits.RA1 = 1 for index 1etc.
  2. takao21203

    AAC Fanatic!

    Apr 28, 2012
  3. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    When you have say 10 byte sized quantities you can always save them in an array and access any item with a simple "array[x]" where x is the number or position of the byte you want. It seems natural to do the same thing with a bit array for port bits.

    This question gets raised over and over. The answer is decidedly no it cannot be done in any direct way.

    Port bits are pieces of a structure, not items in an array.

    There are an infinite ways to write some function to accomplish this task, but internally they use code to choose which pin is being accessed.
  4. takao21203

    AAC Fanatic!

    Apr 28, 2012
    most controllers dont have port bits cpu instructions but some cpus have

    you need to use AND, OR, and masks.

    which you can access with array index. its quite slow.
  5. korchoi


    Jun 5, 2015
    Most CPU architectures don't allow indirect Bit setting and clearing of registers at machine-code level.
    However, you can do that indirectly through Conditional checks and IF statements.
    example: If(index = 0), PortA= 0b00000001; if(index=1), PortA=0b00000010, and so on.
    At machine-level, it should take about 5 instructions, but it's better than not being able to do that.
  6. JohnInTX


    Jun 26, 2012
    For PICs, which this looks like, I've used the techniques ErnieM and takao21023 describe with the attendant problems. There really isn't a slick way on a PIC due to the hard-coded bit number but after trying lots of others my preferred way is just to use the index into a table of vectors to code snippets that do the IO.

    In assembler its:
    Code (Text):
    1.  movf index,W
    2. addwf PCL,F
    3. goto Index0_IO
    4. goto Index1_IO
    5. ...
    6. Index0_IO:
    7. bcf PORTB,0
    8. return
    10. Index1_IO:
    11. bsf PORTB,0
    12. return
    13. etc..
    Note that in this example, the LSB of the index is the value to set the port pin to.

    In C, the same thing is accomplished with an array of pointers-to-fuction.

    Its ugly but assembles/compiles to decent code, at least as good as logical operations or arrays of structures with port addresses and masks. Also, since each IO operation is a routine, you can incorporate other stuff as well. Maybe instead of describing as individual port pins, you can describe IO functions and combine multiple IO ops i.e. turn off RB0, turn on RB1 for digit select etc... The index then becomes a state indicator for the IO machine.
    Last edited: Jun 8, 2015