When I try to program my SPI device with the below Settings, My output clock frequency is always 125Khz. even Upon trying with 150Khz, the output is still 125 Khz, But When I try using 250KHz I am getting 250Khz as expected.
Please read this post, and then follow it by inclucing the specification for all the devices in your circuit, your schematic, and post the full code in code tags:
If you're talking about an Uno R3 or the like, a look in SPI.h is instructive:
// Clock settings are defined as follows. Note that this shows SPI2X
// inverted, so the bits form increasing numbers. Also note that
// fosc/64 appears twice
// SPR1 SPR0 ~SPI2X Freq
// 0 0 0 fosc/2
// 0 0 1 fosc/4
// 0 1 0 fosc/8
// 0 1 1 fosc/16
// 1 0 0 fosc/32
// 1 0 1 fosc/64
// 1 1 0 fosc/64
// 1 1 1 fosc/128
// 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).
uint8_t clockDiv;
// When the clock is known at compile time, use this if-then-else
// cascade, which the compiler knows how to completely optimize
// away. When clock is not known, use a loop instead, which generates
// shorter code.
if (__builtin_constant_p(clock)) {
if (clock >= F_CPU / 2) {
clockDiv = 0;
} else if (clock >= F_CPU / 4) {
clockDiv = 1;
} else if (clock >= F_CPU / 8) {
clockDiv = 2;
} else if (clock >= F_CPU / 16) {
clockDiv = 3;
} else if (clock >= F_CPU / 32) {
clockDiv = 4;
} else if (clock >= F_CPU / 64) {
clockDiv = 5;
} else {
clockDiv = 6;
}
} else {
uint32_t clockSetting = F_CPU / 2;
clockDiv = 0;
while (clockDiv < 6 && clock < clockSetting) {
clockSetting /= 2;
clockDiv++;
}
}
// Compensate for the duplicate fosc/64
if (clockDiv == 6)
clockDiv = 7;
Regardless of the exact value you specify, for a 16MHz system clock you always get one of 8MHz, 4MHz, 2MHz, 1MHz, 500KHz, 250KHz or 125KHz for the SPI clock.
I am using Arduino UNO R3,
Is my understanding that ; though we give a custom frequency at SPISetting() function, the output SPI clock will always follow any one in 8MHz, 4MHz, 2MHz, 1MHz, 500KHz, 250KHz or 125KHz.
// We find the fastest clock that is less than or equal to the
// given clock rate.
So when you ask for 150KHz, the fastest clock rate that is less than that is 125K, so that's what you get. If you asked for 200KHz, you'd still get 125KHz. If you asked for 300KHz, you'd get 250KHz.
The exception to the "use the fastest clock that is <= to the requested clock" rule that is if you asked for something less than 125KHz, you'd get 125KHz, because that's as low as the clock can be divided.