Hi,
I use some Xbee's and i want to give them a name, by founding index in an address array and using the index to found the name in a name array.
uint16_t myArray[]={0x40B14DFB,0x408DA113,0x407DB114,0x40C18CEC};
For example, if i have the address 0x407DB114 i want to know its index (2)
I found this code but for a char array, i don't know how to make it functionnal for int
Thks
char *myArray[]={"0x40B14DFB","0x408DA113","0x407DB114","0x40C18CEC"};
char *deviceName[] = {"Garage",
"Cave",
"Garden",
"Pool",
};
void setup() {
Serial.begin(9600);
Serial.println("Begin: ");
}
void loop() {
Serial.println(deviceName[getIndexByKey("0x408DA113")]);
delay(2000);
}
int getIndexByKey(char *key )
{
for ( uint8_t i = 0; i < sizeof( myArray ) / sizeof( char * ); i++ )
if ( !strcmp( key, myArray[i] ) )
return i;
return -1;
}
guix
2
Hello
strcmp is used to compare char arrays, you want to compare ints so simply use the comparison operator ( == ).
Edit:
Also you make an array of uint16_t but you store 32 bits values in it...
You could use something like this:
uint32_t myArray[]={ 0x40B14DFB, 0x408DA113, 0x407DB114, 0x40C18CEC };
uint16_t myArrayCount = sizeof( myArray ) / sizeof( myArray[0] );
int16_t counter = -1;
while ( ++counter < myArrayCount )
if ( myArray[ counter ] == 0x407DB114 )
break;
if ( counter == myArrayCount )
Serial.println( "Value not found in array" );
else
{
Serial.print( "Found value in array at pos " );
Serial.println( counter );
}
But, why not use a struct instead ?
You should consider learning the basics.
0x407DB114 is a 32 bits long data, so you should use uint32_t instead of uint16_t.
uint32_t myArray[]={0x40B14DFB,0x408DA113,0x407DB114,0x40C18CEC};
And then :
int getIndexByKey(uint32_t key)
{
for ( uint8_t i = 0; i < sizeof( myArray ) / sizeof( uint32_t ); i++ )
if ( key == myArray[i] )
return i;
return -1;
}
Thanks Guix an Bricoleau.
Works fine. I'm going to learn the basics now 