View previous topic :: View next topic |
Author |
Message |
The Puma
Joined: 23 Apr 2004 Posts: 227 Location: The Netherlands
|
How convert this to a simple routine |
Posted: Sun May 21, 2006 9:57 am |
|
|
Code: |
#define DIGIT_0 0x01 // Digit 0 register
#define DIGIT_1 0x02 // Digit 1 register
#define DIGIT_2 0x03 // Digit 2 register
#define DIGIT_3 0x04 // Digit 3 register
#define DIGIT_4 0x05 // Digit 4 register
void max7221_display_message() {
int column,matrix,index;
for(column=DIGIT_0;column<=DIGIT_4;column++) {
if(column==DIGIT_0)
index=4;
if(column==DIGIT_1)
index=3;
if(column==DIGIT_2)
index=2;
if(column==DIGIT_3)
index=1;
if(column==DIGIT_4)
index=0;
output_low(MAX7221_CS);
for(matrix=DOT_MATRIX_DISPLAY_LEFT;matrix<=DOT_MATRIX_DISPLAY_RIGHT;matrix++) {
spi_write(column);
spi_write(message[index]);
index+=5;
}
output_high(MAX7221_CS);
}
}
|
If the column has the value of DIGIT_0
the variable index must have a value of: 4
Column = DIGIT_1
index must be 3
column = DIGIT_2
index must be 2
column = DIGIT_3
index must be 1
colomn = DIGIT 4
index must be 0
How can i do that in a simpler code than that above? |
|
|
KamPutty Guest
|
|
Posted: Sun May 21, 2006 5:40 pm |
|
|
You can get rid of the if's by using a formula...
~Kam (^8*
Code: |
#define DIGIT_0 0x01 // Digit 0 register
#define DIGIT_1 0x02 // Digit 1 register
#define DIGIT_2 0x03 // Digit 2 register
#define DIGIT_3 0x04 // Digit 3 register
#define DIGIT_4 0x05 // Digit 4 register
void max7221_display_message() {
int column,matrix,index;
for(column=DIGIT_0;column<=DIGIT_4;column++)
{
index=5-column;
output_low(MAX7221_CS);
for(matrix=DOT_MATRIX_DISPLAY_LEFT;
matrix<=DOT_MATRIX_DISPLAY_RIGHT; matrix++)
{
spi_write(column);
spi_write(message[index]);
index+=5;
}
output_high(MAX7221_CS);
}
}
|
|
|
|
The Puma
Joined: 23 Apr 2004 Posts: 227 Location: The Netherlands
|
|
Posted: Mon May 22, 2006 11:58 am |
|
|
@KamPutty
It works, thx |
|
|
KamPutty Guest
|
|
Posted: Mon May 22, 2006 4:35 pm |
|
|
Also,
If you ever need to do a bunch of "if's", use else's to make it faster
Change
Code: |
if(column==DIGIT_0)
index=4;
if(column==DIGIT_1)
index=3;
if(column==DIGIT_2)
index=2;
if(column==DIGIT_3)
index=1;
if(column==DIGIT_4)
index=0;
|
to
Code: |
if(column==DIGIT_0)
{
index=4;
}
else if(column==DIGIT_1)
{
index=3;
}
else if(column==DIGIT_2)
{
index=2;
}
else if(column==DIGIT_3)
{
index=1;
}
else if(column==DIGIT_4)
{
index=0;
}
|
This way, when one is true, it does not need to recheck anymore.
Also (!!!)
Using "case/switch" can be faster then the "if's"!
A good compiler will take the "case/switch" can create a very fast lookup table based on the index (i.e. An array of pointers to functions)
The thing that is awesome about programming (IMHO) is that there are soooooo many ways to doing the same thing!
Well, thats it! Take care,
~Kam (^8* |
|
|
|