1
\$\begingroup\$

The pins i connect some LEDs to might change during the development (and routing) so I would like to assign the Port bits to a variable (so if the LED has to be connected to another port I only have to change port assigned to the variable and instead of updating each call in the code).

I would like to do some kind of the following in C:


#define myvariable = PORTB.RB11;
#define myvariable2 = PORTB.RB12;

main(){
    if(...)  myvariable = 1;     // B11 is HIGH
    else myvariable = 0;         // B11 is LOW
    if(...)  myvariable2 = 1;
    else myvariable2 = 0;
}

Does anyone know how to do this?

I'd be happy if you could post the two lines of code. (assignment and usage)

Thanks!

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

If you look at the device header file you should find unions defined to access individual bits of IO and other registers.

e.g. from Pic24 code - not sure if PIC32 is the same

#define thepin LATBbits.LATB13

thepin=0;
\$\endgroup\$
1
  • \$\begingroup\$ thanks! It worked perfectly! comment for beginners (like me): don't add any semicolon after a #define statement!! - that costed me 20 min..:D Then the code works perfectly! \$\endgroup\$
    – ndrizza
    Jan 27, 2012 at 1:18
1
\$\begingroup\$

I tend to use a lot of defines and structures with enumerations to prevent my code from being tied to a particular peripheral, or sometimes a particular microcontroller family. The below code assumes outputting a 1 turns the LED on, and a 0 turns it off. By using defines, you are less likely to get these things confused when coding and debugging.

 #define LED1_TRIS (TRISAbits.TRISA1)
 #define LED1_IO (PORTAbits.RA1)
 #define SET_INPUT (1)
 #define SET_OUTPUT (0)
 #define LED_ON (1)
 #define LED_OFF (0)

 /* Set as an output. */
 LED1_TRIS = SET_OUTPUT;
 /* Turn LED on. */
 LED1_IO = LED_ON;
 /* Wait. */
 Nop();
 /* Turn LED off. */
 LED1_IO = LED_OFF;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.