I've connected SD card module to Arduino UNO. I want to use PIN 10 for PWM DC motor control and because of that, I've connected CS pin directly to another pin (A3).

SD card is working properly, but after calling SD.begin(A3), it set PIN 10 to HIGH! Immediately after SD.begin(A3) and set that pin to LOW, but meanwhile the motor took a small rotation.

I've digged into SD.cpp and Sd2Card.cpp, but couldn't find where this problem occured!

Any help appreciated....

The Solution:
Simply call SD.begin(-1) and it doesn't touch PIN10. Hope helps somebody else!

  • I do not see a difference for pin 10 between SD.begin(A3) and SD.begin(-1), but how do you set the SS pin for the SD card? – Juraj Jul 19 at 10:42
  • I've grounded SD csPin and it works. – Khalil Laleh Jul 19 at 10:46
up vote 3 down vote accepted

Pin 10 is special. It's the hardware chip select pin for SPI. It is integral to the SPI peripheral in the chip.

That pin must be an OUTPUT for SPI to operate as master, or INPUT for it to operate as a slave.

It's a stupid design decision by Atmel if you ask me, but there you go. So basically trying to use SPI at the same time as PWM on pin 10 is "undefined" and to be avoided.

Use a different pin for PWM or if you need more than there are PWM pins available then consider an external PWM control chip.


Just probing around to get more detail on exactly how it all works, this is what I have found:

  • digitalWrite() explicitly disables PWM on a pin.
  • The direction of pin 10 defines the SPI operation as master or slave.
  • analogWrite() sets pinMode(OUTPUT).
  • The SD library calls pinMode(OUTPUT) and digitalWrite(HIGH) on pin 10.

This means that:

  • SD.begin() will terminate any existing PWM on pin 10.
  • Using PWM on pin 10 will force the pin to output rendering SPI slave mode impossible

You should be able to use PWM on pin 10 if, and only if:

  • You use analogWrite() after using SD.begin(), and
  • You never want to use SPI slave mode.
  • I am not saying it's a stupid design decision on your part - I am saying it's a stupid design decision by Atmel by tying the SPI operation to the direction of a specific pin. – Majenko Jul 18 at 13:46
  • Sorry, my mistake – Khalil Laleh Jul 18 at 13:48
  • 10 must be OUTPUT for SPI master. not important if LOW or HIGH or PWM. only problem is the SD library assuming other SPI device on pin 10 – Juraj Jul 18 at 14:04
  • second upvote for an obviously wrong answer? – Juraj Jul 18 at 14:53
  • @Juraj What's wrong about it? The issue isn't HIGH or LOW - that is irrelevant. The issue is pin 10 is integral to SPI. – Majenko Jul 18 at 14:55

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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