On Mon, 25 Nov 2002, Spehro Pefhany wrote: > At 03:08 PM 11/25/02 +0200, you wrote: > > >I have written a algorith on the pic to mathematically convert the 10-bit > >number to a number between Ymin and Ymax but the algorithm takes far too > >long. Is there a way (hopefully easy) that you more or less can convert > >the 10-bit number to say between 100 and 200 almost directly (bit > >manipulation) without long and cumbersome arithmetic. > > Nic, > > One idea amounts to multiplying by (about) 25 and then dividing by 256 > (throw away the LS byte). > > Assuming you want 100-200 *inclusive*, you could do something like this > (I'll use pseudo-C code) > > Let's assume x (one byte) contains the MS byte of the left-aligned A/D > value (0x00 to 0xFF as the A/D output > goes 0x000 to 0x3FF) > > z = ((x + (x >> 1) >> 1) + (x >> 5) + (x >> 6); > ^^^^^^ > shift any carry from the addition in here > > z= (z >> 1) + 100; > > > You'll recognize the shifts and adds as hard-coded multiplication. > > This will reduce down to just a handful of PIC assembly instructions, > with no loops. This is the right idea. In general, if you want to linearly scale one range into another, then apply this formula (or a variation): X - Xmin Y - Ymin ----------- = ----------- Xmax - Xmin Ymax - Ymin Where X and Y are variables and the Xmin,etc are constants that describe the ranges. In your case, if the X's are the ADC's, Y - 100 = (200-100) * (X - 0) / (1023 - 0) Y = 100 + 100 * X / 1023 At this point, I'd be tempted to use Nikolai G's automatic code generator. But, this equation is especially simple to reduce: Y = 100 + 100 * ( 1023 - X) / 1023 = 100 + 100 * ( 1024 - (X+1)) / (1024 - 1) recall 1/(B+C) = 1/B * (1 - C/B + (C/B)^2 - (C/B)^3 +- ...) substitute Y = 100 + 100 * ( 1024 - (X+1)) * [ 1/1024 * ( 1 + 1/1024 + 1/1024^2 + ... ) ] Keep just the first two terms: Y = 100 + 100 * ( 1024 * (1/1024 + 1/1024^2) - (X+1) * (1/1024 + 1/1024^2) ) = 100 + 100 * ( 1 + 1/1024) - ( (X+1)/1024 + (X+1)/1024^2) = 200 + 100/1024 - 100*(X+1)/1024 - 100*(X+1)/1024^2 The third term is what Spehro expands above (except that he didn't add 1 to the ADC value first). Now, depending on how much accuracy you want or how fast the computation needs to be, you can make a judgement call on the number of terms to keep. Scott -- http://www.piclist.com hint: The PICList is archived three different ways. See http://www.piclist.com/#archives for details.