strange pin behaviour

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Using SS (pin 10 or B2) as an input once caused me an issue with SPI dropping out of MSTR mode with an error. You could check MSTR after the wierd behavior to see if it has been cleared.

The '328p data sheet section 18.5.1 under Bit 4 - MSTR documents this behavior.

Good luck.

-br
http://bitlash.net
http://entropymouse.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Waw!!! The perfect answer for a difficult question, thanks!

That solved the problem!
I was unlucky enough to meet all these 3 conditions, plus use an "inappropriate" pin.

Just in case someone else is interested, it is clearly explained in the section 18.5.1 as billroy mentions:
http://www.atmel.com/dyn/resourc...
---
Bit 4 – MSTR: Master/Slave Select
This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic
zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Mas- ter mode.
---

Many thanks!
David