3

This piece of code was taken from AMIS30543- Arduino library,

void init(uint8_t slaveSelectPin) {
    ssPin = slaveSelectPin;
    digitalWrite(ssPin, HIGH);
    pinMode(ssPin, OUTPUT);
}

Facts I know

  • digitalWrite - makes the pin to the corresponding voltage level
  • pinMode - makes the pin either input or output
  • ssPin is active low pin usually.

So I was wondering before setting the pinDirection why the pin is made HIGH, Then immediately after that the pinDirection was declared as OUTPUT

Also I know , if a pin was made HIGH and on the next line if the direction of the same is set as INPUT will bring the internal pull up resistor in action .

So what am I missing here. More over in Arduino does the order of pinMode/digitalWrite matter.? if So what is the meaning of this particular lines of code Github link to the library

2 Answers 2

0

The library is doing this to make sure, that the pin will never go low during initialization.

Imagine doing it the other way round:

pinMode(ssPin, OUTPUT);
digitalWrite(ssPin, HIGH);

If the corresponding PORT bit is set to zero (LOW) previously (which is also the standard after reset/power cycle), the pin will go LOW for a very short time, until digitalWrite() sets it HIGH again. That LOW time is short, but it might needlessly activate the slave. If you first use digitalWrite(ssPin, HIGH), you activate the internal pullup (as standard mode after reset/power cycle is INPUT) and set the corresponding PORT bit to 1. Thus, when you now change the pin mode, the pin is HIGH immediately, without ever going to LOW in between.

Internally the Arduino uses 3 SFRs (Special Function Registers), which are directly connected to the IO hardware of the pins. The DDR register of each port controls the "pin mode" aka direction of the pin (input or output). The PORT register controls the output value (HIGH or LOW; or turning the pullup resistor on or off in input mode). The PIN register reflects the current state of the pin (for reading it). In this case the double function of the PORT register is important, as it activates the internal pullup resistor, when set while in input mode.

1

This initialization will work with spi communication for PIC32 microchip too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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