Em 13/6/2012 06:20, Goran Hosinsky escreveu: > I am working on a 16f887 project in Hitec C which will use many output=20 > pins. I > > #define LINE1 RA0 > #define LINE2 RA1 > > etc which gives me a readable code. The program is basically > > if ... > LINE1 =3D ON; > if ... > LINE2 =3D ON; > > With the few output connections that I am starting with I just repeat=20 > the code for each output line, but I am amplifying to 24 lines, which=20 > makes for a rather massive code. Also, the "if" part will grow with time= =20 > as I add more sensors > Is there a way to handle the RA0 RA1... bits in C with a loop? This=20 > would simplify the code for me. > > Goran > Canary Islands A simple approach is to create a function to manipulate the pins, passing a sequential pin number (you assign these number at your will) and the value. Inside that function it is much to like what you have now, but a 'switch' is probably more efficient than the 'if' chain. Although this approach doesn't simplify the overall code, your main function becomes more readable. A more elaborate solution is to create a table with bit-masks and pointers to the PORT registers. For instance: typedef struct { unsigned char *Port; unsigned char BitMask; } portpin_t; portpin_t IOPins[2] =3D {{ &PORTA, 0x01 }, { &PORTA, 0x02 }}; .... void SetPin( unsigned char PinNumber ) { *IOPins.Port[PinNumber] |=3D IOPins.BitMask[PinNumber]; } void ClearPin( unsigned char PinNumber ) { *IOPins.Port[PinNumber] &=3D ~IOPins.BitMask[PinNumber]; } You can use macros also: #define SETPIN(p) do{ *IOPins.Port[(p)]|=3D IOPins.BitMask[(p)];}while(0) #define CLEARPIN(p) do{ *IOPins.Port[(p)]&=3D ~IOPins.BitMask[(p)];}while(0) If all your pins reside in the same port then you don't need to use a struct (the '*port' member is not necessary) and if besides this all your pins follow a numeric sequence then you don't need the masks, you can create them ad-hoc: "PORTA |=3D 0x01 << PinNumber;" / "PORTA &=3D ~(0x0= 1 << PinNumber);" This solution is good when your I/O pins are all spread over several ports without a logic sequence. It can be much less efficient than the 'switch' with several cases (but can also be much more efficient, depending on the number of pins, compiler and target architecture). Isaac --=20 http://www.piclist.com PIC/SX FAQ & list archive View/change your membership options at http://mailman.mit.edu/mailman/listinfo/piclist .