@@ -203,6 +203,7 @@ void SPIClass::setFrequency(uint32_t freq) {
203
203
static uint32_t lastSetRegister = 0 ;
204
204
205
205
if (freq >= ESP8266_CLOCK) {
206
+ // magic number to set spi sysclock bit (see below.)
206
207
setClockDivider (0x80000000 );
207
208
return ;
208
209
}
@@ -215,7 +216,7 @@ void SPIClass::setFrequency(uint32_t freq) {
215
216
const spiClk_t minFreqReg = { 0x7FFFF020 };
216
217
uint32_t minFreq = ClkRegToFreq ((spiClk_t*) &minFreqReg);
217
218
if (freq < minFreq) {
218
- // use minimum possible clock
219
+ // use minimum possible clock regardless
219
220
setClockDivider (minFreqReg.regValue );
220
221
lastSetRegister = SPI1CLK;
221
222
lastSetFrequency = freq;
@@ -227,8 +228,14 @@ void SPIClass::setFrequency(uint32_t freq) {
227
228
spiClk_t bestReg = { 0 };
228
229
int32_t bestFreq = 0 ;
229
230
230
- // find the best match
231
- while (calN <= 0x3F ) { // 0x3F max for N
231
+ // aka 0x3F, aka 63, max for regN:6
232
+ const uint8_t regNMax = (1 << 6 ) - 1 ;
233
+
234
+ // aka 0x1fff, aka 8191, max for regPre:13
235
+ const int32_t regPreMax = (1 << 13 ) - 1 ;
236
+
237
+ // find the best match for the next 63 iterations
238
+ while (calN <= regNMax) {
232
239
233
240
spiClk_t reg = { 0 };
234
241
int32_t calFreq;
@@ -239,8 +246,8 @@ void SPIClass::setFrequency(uint32_t freq) {
239
246
240
247
while (calPreVari++ <= 1 ) { // test different variants for Pre (we calculate in int so we miss the decimals, testing is the easyest and fastest way)
241
248
calPre = (((ESP8266_CLOCK / (reg.regN + 1 )) / freq) - 1 ) + calPreVari;
242
- if (calPre > 0x1FFF ) {
243
- reg.regPre = 0x1FFF ; // 8191
249
+ if (calPre > regPreMax ) {
250
+ reg.regPre = regPreMax;
244
251
} else if (calPre <= 0 ) {
245
252
reg.regPre = 0 ;
246
253
} else {
@@ -254,19 +261,21 @@ void SPIClass::setFrequency(uint32_t freq) {
254
261
calFreq = ClkRegToFreq (®);
255
262
// os_printf("-----[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d = %d\n", reg.regValue, freq, reg.regEQU, reg.regPre, reg.regN, reg.regH, reg.regL, calFreq);
256
263
257
- if (calFreq == ( int32_t ) freq) {
264
+ if (calFreq == static_cast < int32_t >( freq) ) {
258
265
// accurate match use it!
259
266
memcpy (&bestReg, ®, sizeof (bestReg));
260
267
break ;
261
- } else if (calFreq < ( int32_t ) freq) {
268
+ } else if (calFreq < static_cast < int32_t >( freq) ) {
262
269
// never go over the requested frequency
263
- if ((freq - calFreq) < (freq - bestFreq)) {
270
+ auto cal = std::abs (static_cast <int32_t >(freq) - calFreq);
271
+ auto best = std::abs (static_cast <int32_t >(freq) - bestFreq);
272
+ if (cal < best) {
264
273
bestFreq = calFreq;
265
274
memcpy (&bestReg, ®, sizeof (bestReg));
266
275
}
267
276
}
268
277
}
269
- if (calFreq == ( int32_t ) freq) {
278
+ if (calFreq == static_cast < int32_t >( freq) ) {
270
279
// accurate match use it!
271
280
break ;
272
281
}
0 commit comments