Pages: [1]   Go Down
Author Topic: read, save and compare arrays  (Read 502 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Jr. Member
**
Karma: 0
Posts: 55
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi, I am currently doing some serial communication program.
As for the part to read from the Serial.read and save it in an array, I've managed to do it.

let say, if we send 'ms1'

Code:
if (Serial.available() > 0) // if new data is available, repeat this loop until Serial.available= 0
        {
           inByte = Serial.read(); // Read new byte
           //Serial.print("READ : "); // Display the new byte
           stringx[string_len] = inByte; // Save the data in a character array
          // Serial.println(string[string_len]); // Print the characters that was recieved. -1 so that we would not read the '>' end string
           string_len++;  //add array 
         
    }

on this line, stringx will have 'ms1'.

As usual, if I want to check the array, one of the ways are doing like:

Code:
     if(stringx[0]=='m'){
        if(stringx[1]=='s'){   // if received 'm','s'
             if(stringx[2]=='1'){  //if received 'm','s','1'
             Serial.println("main switch is on");
             }
             
             else if(stringx[2]=='0'){  //if received 'm','s','0'
             Serial.println("main switch is off");
              blinkLED(ledPin, 2, 200); // blinkLED(ledPin, times, delay);
             }
        }

which will check whether 'ms1' has received.

Is it possible for me to use something simple like this?

Code:
for(char i=0; i<(string_len-1); i++)   // this function copies and combine all the char

   if(stringx=="ms1"){
       Serial.println ("success!");   //put a new line
        }

So I can compare all the string is stringx array, with the char that I wanted.

With above code, it gives me an error. Any simpler options also would be good.

Thank you.
Logged

UK
Offline Offline
Faraday Member
**
Karma: 17
Posts: 2884
Gorm deficient
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Use strcmp?
Logged

Per Arduino ad Astra

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48556
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
Use strcmp?
Use strcmp!
Logged

0
Offline Offline
Jr. Member
**
Karma: 0
Posts: 55
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks both of you. 
 

Code:
if (strcmp(stringx, "ms1>")  == 0)  // test to see if the two strings are equal
   {
       Serial.println ("success!");   //put a new line
   }
   
Logged

Pages: [1]   Go Up
Jump to: