1

I new to C and I'm attempting to writte a simple code for Arduino (based on Wiring language) like this:

void loop() 
{  
  distance(cm);
  delay(200);    
}

void distance(char[3] unit) 
{
  if (unit[] == "cm") 
    Serial.println("cm");
}

Could somebody please advise me how to writte it correctly? Thanks in advance!

1 Answer 1

2

There are several ways.

The most "basic" one is using the strcmp function:

void distance(char* unit) 
{
    if (strcmp(unit, "cm")  == 0) 
        Serial.println("cm");
}

Note that the function returns 0 if the strings are equal.

If you have fixed-length strings maybe testing every single character is faster and less resources-consuming:

void distance(char* unit) 
{
    if ((unit[0] == 'c') && (unit[1] == 'm') && (unit[2] == '\0')) 
        Serial.println("cm");
}

You can also do other things (such as iterating through the arrays if the strings can have different length).

Bye

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.