Go Down

Topic: Compare hexadecimal string with instruction " strcmp " (Read 235 times) previous topic - next topic

Roberto70

Hi, can anyone tell me where I'm wrong?

I need to read hexadecimal strings from the serial. I'm using this program as a test, using the "strcmp" instruction. The program seems to work up to the 3 byte check, while it seems that it does not do any kind of control from 4 bytes onwards

Code: [Select]
#include <string.h>

byte variable[11];
byte index = 0;
byte flag = 0;

byte coderead1 [] = {0x7E, 0x09, 0x00, 0x03, 0x01, 0x73, 0x41, 0x00, 0x18, 0xD7, 0xA7};
byte coderead2 [] = {0x7E, 0x09, 0x00, 0x03, 0x01, 0x73, 0x01, 0x00, 0x18, 0x97, 0x27};


//===================================
//=              SETUP              =
//===================================
void setup() {
  Serial.begin(9600);
  delay(2000);
  Serial.println("-----START----");
  pinMode(3, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  flag =0;
} //
//===================================
//=              LOOP               =
//===================================
void loop() {
             digitalWrite(3, LOW);
             while (Serial.available() > 0)
                    {
                    byte b = Serial.read();
                    variable[index++] = b;
                    }
                    if (index == 11)
                         {
                          index = 0;
                          if (strcmp(coderead1, variable) == 0)
                            {
                            Serial.print("Corretto !!!!!");
                            Serial.println();
                            digitalWrite(2, HIGH);
                            delay(1000);
                            digitalWrite(2, LOW);
                       
                            }
                 else
                            {
                            Serial.print("ERRATO");
                            Serial.println();
                           
                            }
                          }
   }

Robin2

strcmp() expects to compare two NULL terminated cstrings

I think you need a different function to compare two arrays of bytes. Simplest thing might be to iterate over the array comparing each byte one by one. Stop when you get a mismatch.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

Roberto70

I've already done this test and it works. But I would like to make a simpler program, also because I have to check many strings.
Don't you know lighter alternatives? thank you


Roberto70

Perfect !!!!

 with the "memcmp" instruction, it works correctly.

Thank you very much ... now the program is very simple :)

Go Up