View previous topic :: View next topic |
Author |
Message |
jamalavedra
Joined: 25 Oct 2016 Posts: 62
|
variable problem |
Posted: Tue Mar 07, 2017 10:58 am |
|
|
Hi
I am currently developing some bargraph (8 LEDs) made with a shift register and, in order to test it i have developed to following code.
The problem I have encountered and that I need help with is regarding the variable "a". I have noticed that the value it takes isn't changing correctly.The values it is taking are between 0 and 1 and I don't know why .
Does anyone know why this variable "a" is taking this weird values?
Code: |
int8 z,a,i;
for (i=1; i<250; i++)
{
a=(i / 200)*8);
for(z=0; z<=a; z++){
output_high(pin_c1);
output_high(pin_c2);
bargraph_noD(z);
}
}
|
thanks
jaume |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1909
|
|
Posted: Tue Mar 07, 2017 11:11 am |
|
|
a is an int8 and i is also an int8.
Work through your math. Let's start with i = 1:
a = (1 / 200) * 8.
Remember, this is integer math we're dealing with. 1 / 200, using integer math, is 0. Therefore 0 * 8 = 0.
Let's skip ahead to i = 199:
a = (199 / 200) * 8.
Again, using integer math, 200 goes into 199 zero times. 199 / 200 is still 0. Therefore 0 * 8 = 0.
What about 200? 200 / 200 is 1, and a is then 1 * 8 = 8.
Think about what you want to do while keeping in mind what happens when integer math is performed. Hint: you'll want to use 16 bit math, and you'll want to do the multiplication BEFORE you do the division. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19552
|
|
Posted: Tue Mar 07, 2017 12:24 pm |
|
|
and this can be done very easily once you _understand_ what newguy has pointed out:
a=(i*8L)/200;
The single letter 'L' tells the compiler that the constant '8' is a 'long' (int16). |
|
|
jamalavedra
Joined: 25 Oct 2016 Posts: 62
|
|
Posted: Thu Mar 16, 2017 11:03 am |
|
|
Great, it worked perfectly. Thanks guys. |
|
|
|