2

I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:

unsigned int m_SPISpeed = 400000;
SPI.begin();
pinMode(m_SPISelect, OUTPUT);
m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
...
SPI.beginTransaction(m_SPISettings);
digitalWrite(m_SPISelect, LOW);
SPI.transfer(regAddr | 0x80);

Where m_SPISpeed is 400000. No matter what i set this value to it is always operating at 125000Hz.

asked Feb 13, 2015 at 15:46
7
  • What data type is the variable m_SPISpeed? Commented Feb 13, 2015 at 20:09
  • @RogerRowland, unsigned int Commented Feb 13, 2015 at 20:11
  • If that's a Uno, then unsigned int is only 2 bytes, so max 65536. Which Arduino? Commented Feb 13, 2015 at 20:14
  • 3
    Try unsigned long m_SPISpeed = 400000L; Commented Feb 13, 2015 at 20:17
  • 1
    Put another zero in that literal, 4000000L, looking at the source code for the new SPI library, it applies a simple algorithm to get a clock divider, so unless you're spot on with a multiple, you get the next lowest. Commented Feb 14, 2015 at 10:50

1 Answer 1

1

As was pointed out in the question comments, your use of unsigned int is the problem. The prototype for SPISettings is:

SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) {

The comments in spi.h say:

// We find the fastest clock that is less than or equal to the
// given clock rate. The clock divider that results in clock_setting
// is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the
// slowest (128 == 2 ^^ 7, so clock_div = 6).

So your SPI speed will be the processor speed divided by 128, which is 16 MHz divided by 128, being 125000 Hz, which is your observed result (since unsigned int cannot possibly hold more than 65535 on this platform).

answered Jun 26, 2015 at 22:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.