Go Down

Topic: [SOLVED]Variable Type After strcpy() Cant use variable in If statement (Read 1 time) previous topic - next topic


Apr 23, 2020, 07:35 pm Last Edit: Apr 23, 2020, 10:03 pm by technorocker Reason: Figured out my own solution
Hey everyone. Ive been using arduino for a lil over a year now but still learning each day. I have been using String for everything cause I also use Unity which uses C#. I am attempting to use chars now and am trying to split data coming in from Unity over UDP packets. I can get the packets to the arduino and see the data in Serial Monitor. The problem is that even when I print both pieces of split data the very next line I try a if(data == "tb") but it wont recognize it.

I dont know if I'm confused about starting to use pointers. I got an example sketch from Serial Input Basics at https://forum.arduino.cc/index.php?topic=396450.0 and am using example #5 but tweaked for my usage needs. Here is a chunk of code that I'm confused about.

Code: [Select]

  Serial.println("Parsing Incoming Data.");
  char * strtokIndx; // this is used by strtok() as an index

  strtokIndx = strtok(tempChars,",");      // get the first part - the string
  strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
  messageFromPC[sizeof(messageFromPC)-1] = 0;

  strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
  integerFromPC = atoi(strtokIndx);     // convert this part to an integer

  //Serial.print("MessageFromPC is: ");
  //Serial.print("IntergerFromPC is: ");

  if(*messageFromPC == "tb"){
    Serial.println("Message for ThumbBuzzer");
    if(integerFromPC == 0){
      Serial.println("ThumbBuzzer Off");
      analogWrite(thumbBuzzer, integerFromPC);
    else if(integerFromPC == 128){
      Serial.print("ThumbBuzzer Half");
      analogWrite(thumbBuzzer, integerFromPC);
    else if(integerFromPC == 255){
      Serial.println("ThumbBuzzer Full");
      analogWrite(thumbBuzzer, integerFromPC);

As you can see I can print both variables to the monitor but the If statement wont "react" to "tb" to enter the function. Any help would be most appreciated. Still trying to wrap my head around chars and pointers.

So after a bit more trial and error I ended up having to use strcmp() inside the if statement like so...
Code: [Select]
if(strcmp(messageFromPC, "pb") == 0)

Then I was able to use it to activate other functions

Go Up