Question about arrays and port bits

Thread Starter

hunterage2000

Joined May 2, 2010
487
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.
 

ErnieM

Joined Apr 24, 2011
8,377
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.
 

takao21203

Joined Apr 28, 2012
3,702
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.
 

korchoi

Joined Jun 5, 2015
59
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.
 

JohnInTX

Joined Jun 26, 2012
4,787
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:
 movf index,W
addwf PCL,F
goto Index0_IO
goto Index1_IO
...
Index0_IO:
bcf PORTB,0
return

Index1_IO:
bsf PORTB,0
return
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:
Top