Scale readadc10 input to limit max value

I'm using readadc10 with a pot to set 2 variables separately, switching between them with a button, however one must not be greater than the other but I dont want to limit the usable range on the potentiometer.

Code:
readadc10 C.4,w0
if w0!=w1 AND w0!=w2 then
    if b12=0 then
        w7=w0
        w10=w7/4
        pokesfr $1B, w10
        gosub period
    else
        w8=w0
        >>>scale w8 so 0-1023 fits within 0-w7<<<
        pwmduty C.2, w8
        gosub duty
    endif
    w2=w1
    w1=w0
endif
 

hippy

Technical Support
Staff member
You effectively want to calculate, without overflow -

w8 = ( w0 * w7 ) / 1023

If you approximate 1023 to being 1024 that can become a shift right by 10 because 210 = 1024 -

w8 = ( w0 * w7 ) >> 10

One can do that in two parts ...

w8 = w0 * w7 >> 10
w8 = w0 ** w7 << 6 + w8

And, if you aren't using an X2 which supports the shift operators -

w8 = w0 * w7 / 1024
w8 = w0 ** w7 * 64 + w8

That might be good enough.

Editied : Corrected the second shift to be in the right direction.
 
Last edited:
But w0 * w7 can overflow.

Forgot to mention its a 08M2.

w8 = w0 * w7 / 1024
w8 = w0 ** w7 / 64 + w8
doesn't work.
 
Last edited:

Aries

New Member
I think you will find it does "work". The reason that the calculation is split into two is to deal with the potential overflow.
w0*w7 is the low (16-bit) part of the 32-bit answer, which is divided by 1024
w0**w7 is the upper (16-bit) part of the 32-bit answer, which is MULTIPLIED by 64 (because 1024 = 2^16/2^6) and added to the previous result.
Try it in a spreadsheet (this is an Excel CSV starting at A1:
Code:
w0,1000
w7,1000
w0*w7,"=MOD(B1*B2,2^16)"
w0**w7,=INT(B1*B2/2^16)
w0*w8/1024,=INT(B3/1024)
w0**w7*64,=B4*64
w8,=B6+B5
Actual,=INT(B1*B2/1024)
 
Last edited:

hippy

Technical Support
Staff member
Code:
       w0 ** w7                 w0 * w7
.---------------------. .---------------------.
| ---- ---- ---- abcd | | efgh ijkl mnop qrst |
`---------------------' `---------------------'
         << 6                    >> 10
.---------------------. .---------------------.
| ---- --ab cd-- ---- | | ---- ---- --ef ghij |
`---------------------' `---------------------'
           |                       +
           |            .---------------------.
           `----------> | ---- --ab cd-- ---- |
                        `---------------------'
                                   =
                        .---------------------.
                        | ---- --ab cdef ghij |
                        `---------------------'
 
Top