Voting resources, early voting, and poll worker information - VOTE. ... Adafruit is open and shipping.
0

Pointer (I think) Arithmetic
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Pointer (I think) Arithmetic

by nogginboink on Sat Jul 30, 2011 4:42 pm

I'm just fluent enough in C to be dangerous and I'm afraid I need help on this one.

I want to be able to define, in my code, the microcontroller port on which my LED is connected:

#define LED_PORT PORTD

Now, I happen to know that on the ATTiny2313, the DDR register for the port is the register immediately after the PORT register. I shouldn't have to manually #define this in my code. I want some kind of macro so that I can write code such as:

DDR(LED_PORT) |= 1 << LED_BIT;

To me, this line of code is readable, self-explanatory, and simple. It also eases code maintenance in case I need to move the LED to another port, I only have to redefine LED_PORT and the code will still work because the DDR register will be found automatically.

Can anyone help me write a macro (or other code automation) that would allow me to write code that automagically determines the DDR register from the PORT register?

nogginboink
 
Posts: 20
Joined: Sat Jul 30, 2011 4:32 pm

Re: Pointer (I think) Arithmetic

by westfw on Sat Jul 30, 2011 7:16 pm

Code: Select all | TOGGLE FULL SIZE
#define DDR(port) *((&port)+1)

Maybe. Seems to work for PORTB; I'm not sure what will happen when the address switch from IO addresses to memory addresses.

westfw
 
Posts: 1734
Joined: Fri Apr 27, 2007 1:01 pm
Location: SF Bay area

Re: Pointer (I think) Arithmetic

by nogginboink on Mon Aug 01, 2011 8:50 pm

This doesn't seem to work on my hardware. (I really wish I understood C pointer arithmetic better than I actually do.)

nogginboink
 
Posts: 20
Joined: Sat Jul 30, 2011 4:32 pm

Re: Pointer (I think) Arithmetic

by nogginboink on Mon Aug 01, 2011 8:56 pm

Actually, it does appear to work. The DDR register is the port register MINUS one, not plus one. Changing that solves the problem.

nogginboink
 
Posts: 20
Joined: Sat Jul 30, 2011 4:32 pm

Please be positive and constructive with your questions and comments.