View previous topic :: View next topic |
Author |
Message |
vtrx
Joined: 11 Oct 2017 Posts: 142
|
Looping for with variable |
Posted: Wed Jul 28, 2021 4:59 am |
|
|
How should I declare the variable in this looping?
Code: |
var x=10;
int8 c;
for(c=0;c < x;c++){do something;} |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19520
|
|
Posted: Wed Jul 28, 2021 6:33 am |
|
|
Any way you want....
x here can be char, int, int8, int16, float, int32, etc. etc. etc..
If it is anything but an int, there will be a variable conversion carried out for
every comparison, which costs space and time, but it will still work. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9229 Location: Greensville,Ontario
|
|
Posted: Wed Jul 28, 2021 6:34 am |
|
|
As the comparison ranges from 0 to something positive...
NO negative numbers involved.
First, I'd declare 'C' as a CHAR ( 0 to 255).
2nd, declare 'X' as CHAR as well (again 0 t0 255 ).
CCS C makes 'char' same as unsigned int8, so less typing. |
|
|
vtrx
Joined: 11 Oct 2017 Posts: 142
|
|
Posted: Wed Jul 28, 2021 6:48 am |
|
|
Code: |
int8 chip;
...
chip = 4;
.......
void sendData(unsigned int16 data)
{
int8 c;
output_low(CS);
spi_xfer(max7912,data);
for(c=0;c < chip;c++){spi_xfer(max7912,REG_NO_OP);}
output_high(CS);
} |
The code above doesn't work, but if I put a fixed value, it works.
Code: | void sendData(unsigned int16 data)
{
int8 c;
output_low(CS);
spi_xfer(max7912,data);
for(c=0;c < 4;c++){spi_xfer(max7912,REG_NO_OP);}
output_high(CS);
} |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19520
|
|
Posted: Wed Jul 28, 2021 8:09 am |
|
|
You probably don't actually ever get to the line where chip is set to 4 before
you call the function.... |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19520
|
|
Posted: Sun Aug 01, 2021 9:16 am |
|
|
Now you don't say what processor you are using. On a DsPIC,
a 'char is a signed int8. Can't hold things over 127. Generally learn to
be explicit on variable sizes:
Code: |
unsigned int8 posi, offset;
//don't use 'chars' for numeric valus their size chages
for(posi=0;posi < 8;posi++)
{
for(offset=248; offset>=128; offset-=8)
{
MAX7219_write(8-posi,scroll_buf[offset + posi],chip);
}
}
|
Your problem is almost certainly that you are not using a variable that
can actually 'hold' the values you are trying to use. If your char is a
signed int8, the maths will wrap, and the result will be completely wrong.
Also, if you are counting in eights, just count in eights. No point in
fiddling with separate counts and offsets. |
|
|
|