I have a strange behaviour.
This works fine on an ATmega328P.
void setup() { Serial.begin(115000); Serial.println("test1"); pinMode(10, OUTPUT); digitalWrite(10, 0); Serial.println(digitalRead(10)); //prints 0 Serial.println("test2"); pinMode(10, OUTPUT); digitalWrite(10, 0); Serial.println(digitalRead(10)); //prints 0 } void loop() {}
However, if these three conditions are met:
C0. pin 10 (PORTB, bit 2) is connected to a SPI EEPROM,
C1. I set-up the Arduino SPI using SPCR, and
C2. I set pinMode(INPUT), but again to pinMode(OUTPUT) just afterwards
then, test2 prints 1, instead of 0. <<Very strange. Why??
If I remove any of C0, C1 or C2, then it works again as expected.
If I add C3 (digitalWrite(1) before pinMode(INPUT)), then it works as expected again.
This is the test program:
void setup() { Serial.begin(115000); SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1)|(1<<SPR0); // C1. removing this, it works as expected Serial.println("test1"); pinMode(10, OUTPUT); digitalWrite(10, 0); Serial.println(digitalRead(10)); Serial.println("test2"); digitalWrite(10, 1); // C3. adding this line, it works as expected pinMode(10, INPUT); // C2. removing this, it works as expected. pinMode(10, OUTPUT); digitalWrite(10, 0); Serial.println(digitalRead(10)); } void loop() {}
The program cannot be simplified any further. Simplifying it a bit more, then it works as expected.
What can be the problem? Why this strange thing???
I've tried this test using Arduino functions pinMode, digitalWrite and digitalRead,
and the same test without using Arduino functions (DDRB, PORTB, PINB instead), with the same results.