View previous topic :: View next topic |
Author |
Message |
Inventor-George
Joined: 28 Mar 2006 Posts: 74
|
Posted: Wed Nov 22, 2023 1:26 am Post subject: Multiplication by a fraction |
|
|
I am setting a variable to the output of ADC(1). I need to then multiple that variable by a fraction [or decimal].
I am using this variable to set a timer, but I need the timer [in us] to wait for 3/4 [.75] of the ADC value.
The variable is DIMed as a word. I don't need an exact value, if the variable does not divide evenly by the desired fraction. I only need a reasonably approximation.
This is probably a dumb question, but it's something I have never had to deal with in the past.
(BASCOM-AVR version : 2.0.8.6 ) |
|
Back to top |
|
|
JC
Joined: 15 Dec 2007 Posts: 586 Location: Cleveland, OH
|
Posted: Wed Nov 22, 2023 3:52 am Post subject: |
|
|
There are probably lots of ways to do this, but to get you started it is perhaps easiest to pick a simple method.
The Single Type is used for floating point math, (numbers with a decimal part).
So, assign a Single Type variable with the value of the ADC.
Now simply multiply the Single Type variable by 0.75.
You can add 0.5 to the result to force a round up, if needed, or just skip this.
Now assign the Word variable with the Single Type variable.
The Word will acquire the integer part of the Single Type variable, and the decimal part will just be ignored.
Now set the Timer with the Word variable.
The floating point multiply should generally NOT be done within in Interrupt Service Routine.
If you must do this, then you must save and restore a couple of special registers yourself.
(The Manual discusses using Floating point in ISRs.)
It would be helpful it you stated the micro being used, how many bits the ADC value is, (8, 10, 12, etc.), and how many bits the Timer/Counter is, (8, 16, etc.).
You need to make sure that the maximum ADC value, * 0.75, will fit in the T/C register (s).
JC |
|
Back to top |
|
|
Inventor-George
Joined: 28 Mar 2006 Posts: 74
|
Posted: Wed Nov 22, 2023 6:39 am Post subject: |
|
|
Thank you, JC for the discussion. I am using the mega8 processor.
I will want only the integer part of the compilation. You have also given me the answer on how to do that. |
|
Back to top |
|
|
MWS
Joined: 22 Aug 2009 Posts: 2262
|
Posted: Wed Nov 22, 2023 7:34 am Post subject: |
|
|
Is speed and flash-space an issue?
If not, stick to float, as it is more flexible.
For speed and space with somewhat decreased resolution:
Set ADMUX.ADLAR, extract the high byte of the ADC-result and add it three times.
Space and a bit slower:
Shift the ADC-result two times right and one time right, add both. |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You cannot download files in this forum
|
|