Question

I have 6 led's connected to different ports of a microcontroller. Say

LED0 -> P1.0

LED1 -> P1.3

LED2 -> P1.2

LED3 -> P2.0

LED4 -> P3.0

LED5 -> P4.1

Is there any way I can map the different addresses to a single name?

Lets say LED_DATA = 0xFF should assign HIGH to all the corresponding LED pins. Preferably it has to be done without using a function and also not like the below one

#define ( LED_DATA = a ) ( function(a) )

Is there any other way of doing this using struct, union, memory mapping or something like that?

Was it helpful?

Solution 3

I don't know if there's a way to do exactly what you want - assigning a single name to non-sequential memory areas without a mapping function. I think the best you can do is minimize the time you spend in said function.

Depending on real-time requirements and your tolerance for carrying global state around, you could define a global variable, e.g. unsigned char g_led_data;, and assign the individual LED states e.g. using g_led_data &= 0xef; to indicate you want to turn off LED4. Then from your main loop, you can call a function which writes the value from g_led_data to the hardware:

/* Call this from the main loop. */
void update_leds( void )
{
  P1.0 = ( g_led_data & 0x01 );
  P1.3 = ( g_led_data & 0x02 ) >> 1;
  ...
}

The advantage of this approach is that it minimizes the amount of time you're spending in a function call to set the LED values - you only call the function once per iteration of the main loop, rather than every time your code sets the value of a particular LED. The disadvantage is the aforementioned effect on real-time performance and now you have to carry a little bit more global state.

OTHER TIPS

I recommend not to use macros or direct access.
It's better to write a function, it encapsulates the complete led handling.

void led_set(unsigned char ledNo, unsigned char mode)
{
  switch (ledNo)
  {
    case 0:
      P1.0 = mode;
      break;
    ...
  }
}

void led_set_mask(unsigned char bitmask)
{
  for (i=0; i< 8; i++)
  {
     led_set(i, bitmask & ( 1 << i) );
  }
}

Only in the case that you need really fast or often access to the LED pins, macros are better.

To clarify; you seem to be wanting here to map multiple pins on separate ports to a single variable?

That can be done easily enough in C++ but not in C. In C++ you would create a class that overloads the assignment operator, so that when a value is assigned, a function runs that extracts the bits and assigns them to the associated pins. However even that is syntactic sugar, it still runs a function, it is merely syntactically identical to a normal assignment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top