Help with array : How to compare

Goodevening, using virtual wire i received a message that is inside a buffer with the code below reported I can print on the serial the buffer that i received … what I’d like to do is take this buffer and compare with a static array is possible ? Thanks andrea

#include <VirtualWire.h>

void setup()
{
    Serial.begin(9600);	// Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
   
    vw_setup(1200);	 // Bits per sec

    vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    if (vw_get_message(buf, &buflen)) // Non-blocking
    {
	int i;

        digitalWrite(13, true); // Flash a light to show received good message
	// Message with a good checksum received, dump it.
	Serial.print("Got: ");
	
	for (i = 0; i < buflen; i++)
	{
	    Serial.print(buf[i]);
	    Serial.print(" ");
	}
	Serial.println("");
        digitalWrite(13, false);
    }
}

what I'd like to do is take this buffer and compare with a static array is possible ?

Sure. Look at the memcmp() function. If the data is character data, and the array is NULL terminated, you could use strcmp().

or if you know how many characters you’ve received… just run a simple for loop comparing each element in your pre-stored array with the received message in the buffer…

there are lots of ways & you can keep tweaking this… eg. ignore case etc :slight_smile: just google & lookup the refs of <string.h> in AVR LibC which is the underlying C library on top of which Arduino libs sit - there are a rich set of string functions… though these come at a slight cost in terms of compiled program size

Hi Pauls, you mean in this way

/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[256];
  char str2[256];
  int n;
  printf ("Enter a sentence: "); gets(str1);
  printf ("Enter another sentence: "); gets(str2);
  n=memcmp ( str1, str2, 256 );
  if (n>0) printf ("'%s' is greater than '%s'.\n",str1,str2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",str1,str2);
  else printf ("'%s' is the same as '%s'.\n",str1,str2);
  return 0;
} 


If the result it's 0 that means that equal correct ?

however thanks for the help,

Andrea

Hi Pauls, you mean in this way

Like that, yeah. But, I'm pretty sure that won't work on an Arduino.

Hi paul, using strcmp() function if didn’t wrong should be result in this way the code …

if (vw_get_message(buf, &buflen)) // Non-blocking
    {
	int i;
        // Static string that I want to compare
        char text_static[2] =  {'2','?'};
        char text_arrived[buflen];
        char msg[1];
        digitalWrite(13, true); // Flash a light to show received good message
	// Message with a good checksum received, dump it.
	Serial.print("Got: ");
	for (i = 0; i < buflen; i++)
	{
	    // Received the string and assign to another variable 
                 text_arrived[i] = buf[i], char();
	    Serial.print(" ");
	}
            // check the string and do something if are equal ...
        if (strcmp(text_static, text_arrived) == 0)
          {
              // do something
          }

I hope is correct :wink:

thanks for the help :slight_smile:

                 text_arrived[i] = buf[i], char();

What do you think this is doing? Specifically, what is the , char() bit doing?

        char text_static[2] =  {'2','?'};

This is NOT a string. A string is a NULL terminated array of chars. This is an array of chars, but it is not NULL terminated, so it can not be passed to the strcmp() function.

        char text_arrived[buflen];

There is no room for a NULL, so this can’t be passed to strcmp(), either.

So, due the fact convert what arrive in char ... so due the fact I don't know what virtualwire send out then I convert every buffer element in char and the I compare the result ... is wrong like thinking ?

thanks Andrea

So, due the fact convert what arrive in char ... so due the fact I don't know what virtualwire send out then I convert every buffer element in char and the I compare the result ... is wrong like thinking ?

I don't understand all of this, but I think that what you are saying is that you are trying to cast the value to a char. That is not how to do it.

 text_arrived[i] = (char)buf[i];

I edited my previous response. You should re-read it.

yeah you have reason, I'd like to do a cast ... so the cast correct is that

text_arrived[i] = (char)buf[i];

thanks for the explanation, so I want id like to do this :

I've a trasmitter and the receiver, from the trasmitter I send out something for example the char '2' , on the receiver Id like to check if '2' is for the receiver or not ... I'm trying to find out an easy way for to do that ... you can suggest something ?

So, im spending a lot of hours on that ... but I didn't find an effeciency solution ...

Thanks Andrea ...

Moderator edit: Italics tag removed.

on the receiver Id like to check if '2' is for the receiver or not

if(text_arrived[0] == '2')
// or
if(text_arrived[0] == text_static[0])

So, im spending a lot of hours on that

I think you are trying to make it more difficult than it needs to be.

so, I've think mee too what you have suggest but I've think that was not good ...

Thanks I will Try to do this and then I'll you know ...

So, then If need to check '22' I can check in the mean time [0] first element and [1] the second one correct ?

Thanks for your useful help ;-) you are very kindly ...

Moderator edit: Bullet point tags removed

Hi Paul, yestarday evening i was very happy because I’ve follow your indication with success. to be hones I don’t know why I’ve tried to run the same program this morning and won’t work … :frowning: again … what I’ve did is wait until is pressed, when is pressed send out data, wait until have an answer and then blink each n times based on the keypressed … from your stand point is there error in my code ?
Trasmitter:

#include <VirtualWire.h>
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
const int ledPin =  13;  
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
 {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {8, 7, 6, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {4, 3, 2}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 


void setup()
{
    Serial.begin(9600);	// Debugging only
    pinMode(ledPin, OUTPUT);
    Serial.println("setup");
    // Initialise the IO and ISR
    vw_setup(1200);	 // Bits per sec
    vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
   //delay(80);
   char customKey = customKeypad.getKey();
   char msg[1];
   msg[0] = customKey;
 if (customKeypad.getState() == PRESSED)
   {  
     if (customKey != NO_KEY)
      {
       Serial.println(customKey);
       // digitalWrite(13, true); // Flash a light to show transmitting
       vw_send((uint8_t *)msg, strlen(msg));
       vw_wait_tx(); // Wait until the whole message is gone
       Serial.println("Sent");
       // digitalWrite(13, false);
       customKey = NO_KEY;
       uint8_t buf[VW_MAX_MESSAGE_LEN];
       uint8_t buflen = VW_MAX_MESSAGE_LEN;
       // Wait at most 200ms for a reply
       vw_wait_rx();
       //if (vw_wait_rx_max(265))
       //{
       char testo[buflen];
       char testo1;
         if (vw_get_message(buf, &buflen)) // Non-blocking
	  {
	    int i;
	    // Message with a good checksum received, dump it.
	    Serial.print("Got: ");
	    //for (i = 0; i < buflen; i++)
	    //{
                // testo[i]= buf[i], char();
		// Serial.println((char)buf[i]);
            testo[0]= buf[0], char();
            Serial.println(testo[0]);
            Serial.print(" ");
	    //}
            
           // Serial.println(testo[0]);
	    Serial.println("");
            //Serial.println(testo);
            //Serial.println("");
            switch (testo[0]) 
             {
              case '1':
                Serial.println("Im number 1");
                digitalWrite(13, HIGH);
                delay(250);
                digitalWrite(13, LOW);
                break;
              case '2':
                Serial.println("Im number 2");
                volatile int b;
                volatile int c;
                b = 1;
                c = 3;
                asled(b,c);  
                break;
              case '3':
                Serial.println("Im number 3");
                volatile int d;
                volatile int e;
                d = 1;
                e = 4;
                asled(d,e);     
                break;
              case '4':
                volatile int f;
                volatile int g;
                f = 1;
                g = 5;
                asled(f,g);  
                break;
              case '5':
                volatile int h;
                volatile int i;
                h = 1;
                i = 6;
                asled(h,i); 
                break;
              case '6':
                volatile int l;
                volatile int m;
                l = 1;
                m = 7;
                asled(l,m); 
                break;
              case '7':
                volatile int n;
                volatile int o;
                n = 1;
                o = 8;
                asled(n,o); 
                break;
              case '8':
                volatile int p;
                volatile int q;
                p = 1;
                q = 9;
                asled(p,q); 
                break;
              case '9':
                volatile int r;
                volatile int s;
                r = 1;
                s = 10;
                asled(r,s); 
                break;
              case '0':
                Serial.println("Im number 0");
                break;
              case '*':
                Serial.println("Im number *");
                break;
              case '#':
                Serial.println("Im number #");
                break;  
            
               } 
	}
    //}
    else
	Serial.println("Timout");
     }  
   } 	
}

void asled(int a,int cont)
{
  for (a = 1; a < cont; a++)
    {
     digitalWrite(13, HIGH);
     delay(250);
     digitalWrite(13, LOW);
     delay(250);
    }
  
}

Receiver:

#include <VirtualWire.h>

void setup()
{
    Serial.begin(9600);	// Debugging only
    Serial.println("setup");
    vw_setup(1200);	 // Bits per sec
    vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
    //const char *msg = "hello";
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;
    // Wait for a message
    vw_wait_rx();
    if (vw_get_message(buf, &buflen)) // Non-blocking
    {
	int i;
        char testo[buflen];
        char msg[1];
	Serial.print("Got: ");
	//for (i = 0; i < buflen; i++)
	// {
	    // Received the string and assign to another variable 
            // testo[i] = buf[i], char();
            testo[0]= buf[0], char();
	    Serial.print(" ");
	// }
            // check the string and do something if are equal ...
        Serial.println(testo[0]);
	// Serial.println("");
        // Serial.println(testo);  
	// Serial.println("");
        msg[0] = testo[0];
	// Send a reply
	vw_send((uint8_t *)msg, strlen(msg));
        vw_wait_tx(); // Wait until the whole message is gone
        Serial.println("Sent");
        // digitalWrite(13, false);
    }
}

Sure I’ve seen that was working yestarday …

thanks for yout advise,

Andrea

I've note this ... randomly start to work again ... but I didn't know why ... I've tried in different way ... so the message start from the trasmitter but seems doesn't arrive to the receiver ... Maybe I've miss something but is strange ...

From the hardware stand point the 2 arduino are connected transmitt receiver pin 12 --> pin 11 pin 11 --> pin 12

gnd --> gnd Vin --> +5V usb cable to the computer

Andrea

   char customKey = customKeypad.getKey();
   char msg[1];
   msg[0] = customKey;

This is a complete waste of resources and is nonsense. Any time you are trying to create a one element array STOP!

       vw_send((uint8_t *)msg, strlen(msg));

You can NOT pass msg to strlen(). The string functions, like strlen() expect to receive a NULL terminated array of chars. There is absolutely no possible way for a one element array to contain a character AND a NULL. For that, you need a minimum of 2 elements in the array AND you have to explicitly add the NULL.

You KNOW how many elements you are going to put in the array to send. After you do that, why do you need to ask the strlen() function how many characters you put into the array.

Get smart, and just use:

       vw_send((uint8_t *)customKey, 1);