V71+: rewrite chooseBestClock to fix errors
authorjoan2937 <joan@abyz.me.uk>
Fri, 29 Nov 2019 23:20:19 +0000 (23:20 +0000)
committerjoan2937 <joan@abyz.me.uk>
Fri, 29 Nov 2019 23:20:19 +0000 (23:20 +0000)
pigpio.c
pigpio.h

index da91ace7e00f07a44163025ea44bb16977326529..cf855e63b66428fba27d82f913e95adbd6c179f7 100644 (file)
--- a/pigpio.c
+++ b/pigpio.c
@@ -5087,51 +5087,33 @@ int serDataAvailable(unsigned handle)
 static int chooseBestClock
    (clkInf_t *clkInf, unsigned f, unsigned numc, unsigned *cf)
 {
-   int c, valid, offby, offby2, best_offby;
-   uint32_t div;
-   uint64_t frac;
+   int c, valid;
+   double fdiv, offby, best_offby;
+   unsigned div, frac;
 
    valid = 0;
    best_offby = 0;
 
    for (c=0; c<numc; c++)
    {
-      div = cf[c] / f;
+      fdiv = (double)cf[c] / (double)f;
+      if (f < PI_MASH_MAX_FREQ)
+      {
+         fdiv += (0.5 / 4096.0);
+         div = fdiv;
+         frac = (fdiv - div) * 4096.0;
+      }
+      else
+      {
+         fdiv += 0.5;
+         div = fdiv;
+         frac = 0;
+      }
 
       if ((div > 1) && (div < 4096))
       {
-         if (f < PI_MASH_MAX_FREQ)
-         {
-            frac = cf[c] - (div * f);
-            frac = (frac * 4096) / f;
-            offby = cf[c] - (div * f) - ((frac * f) / 4096);
-            if (frac < 4095)
-            {
-               offby2 = cf[c] - (div * f) - (((frac+1) * f) / 4096);
-               if (offby2 < 0) offby2 = -offby2;
-               if (offby2 < offby)
-               {
-                  offby = offby2;
-                  frac++;
-               }
-            }
-         }
-         else
-         {
-            frac = 0;
-            offby = cf[c] - (div * f);
-            if (div < 4095)
-            {
-               offby2 = cf[c] - ((div+1) * f);
-               if (offby2 < 0) offby2 = -offby2;
-               if (offby2 < offby)
-               {
-                  offby = offby2;
-                  div++;
-               }
-            }
-         }
-
+         offby = f - (cf[c] / (div + (frac / 4096.0)));
+         if (offby < 0) offby = - offby;
          if ((!valid) || (offby <= best_offby))
          {
             valid = 1;
index 0010fd8d2e87cb5bbe3f770ef3a3dfbb21915b03..b143c40e40f837e356c61cf4403dd03262eb61b5 100644 (file)
--- a/pigpio.h
+++ b/pigpio.h
@@ -30,7 +30,7 @@ For more information, please refer to <http://unlicense.org/>
 #include <stdint.h>
 #include <pthread.h>
 
-#define PIGPIO_VERSION 7104
+#define PIGPIO_VERSION 7105
 
 /*TEXT