Go Down

Topic: Understanding Library Code (Read 870 times) previous topic - next topic

extasic

Hi!

I am currently using and trying to understand the OneWire Library. This library helps to interact with devices on the 1Wire bus by Dallas.

Let pin = 2 be the digital pin of Arduino that is used.

The variables bitmask and baseReg (uint8_t) are initialized as

Code: [Select]
#define PIN_TO_BASEREG(pin)             (portInputRegister(digitalPinToPort(pin)))
#define PIN_TO_BITMASK(pin)             (digitalPinToBitMask(pin))
bitmask = PIN_TO_BITMASK(pin);
baseReg = PIN_TO_BASEREG(pin);


and setting the pin to low is done by

Code: [Select]

#define IO_REG_TYPE uint8_t
#define IO_REG_ASM asm("r30")
#define DIRECT_MODE_OUTPUT(base, mask)  ((*(base+1)) |= (mask))
#define DIRECT_WRITE_LOW(base, mask)    ((*(base+2)) &= ~(mask))
IO_REG_TYPE mask=bitmask;
volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg;
DIRECT_WRITE_LOW(reg, mask);
DIRECT_MODE_OUTPUT(reg, mask); // drive output low



  • bitmask contains the position of the pin in the related registers DDRX, PORTX and PINX where X is A,B,C or D - depending on the pin and AVR used, right?

  • What does basereg contain?

  • If I do understand the code right, the line starting with "volatile" declares a pointer to an unsigned char called reg that is stored in register 30 of the AVR. But why is that register used? Is the pointer itself or its value stored there?

  • How does the DIRECT_WRITE_LOW macro work? Does (base+1) correspond to the DDR and (base+2) to the PORT register?

  • Why is DIRECT_MODE_OUTPUT called after DIRECT_WRITE_LOW?



Could you please help me to answer these questions?

Thanks in advance!

PeterH

Are you trying to understand how to use it, or how the library's internal implementation works? You should not need to know what's going on under the covers in order to use the library in your sketch.
I only provide help via the forum - please do not contact me for private consultancy.

extasic


Are you trying to understand how to use it, or how the library's internal implementation works? You should not need to know what's going on under the covers in order to use the library in your sketch.


I try to understand how the library's implementation works. I know what it does but I want to know why it works.

I do know that I don't need this to just run it, but I don't want to use something I don't understand  ;) Therefore I already read about (PORT-,PIN-,DDR-) registers and some AVR stuff, but nevertheless am currently stuck.

Go Up