Pages: [1]   Go Down
Author Topic: How to extract int from string (RSSI value from WiFly shield)  (Read 1300 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 8
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am reading the signal strength (RSSI) from my WiFly shield. I receive the RSSI in the following format:

RSSI=(-84) dBm

I want to store the "-84" number in an int variable and discard the other characters. I have tried to do this using switch case but it hasn't worked reliably.

    SpiSerial.println("show rssi");    //requesting RSSI value
  while(SpiSerial.available() > 0) {
    char ch = SpiSerial.read();         //reads RSSI raw data

    switch(ch){
      case '0'...'9':
        pos = pos * 10 + ch - '0';
        break;
       
      case 'smiley-cry-':
        chara = (pos);       //stores unwanted chars
        pos = 0;
        break;
       
      case ') dBm':
        rssi_val = (pos);    //writes just RSSI number into rssi_val
        pos = 0;
       
   
   // Serial.print(SpiSerial.read(), BYTE);
   Serial.println();
   Serial.print("RSSI value is");
    Serial.println(rssi_val);
    break;
    }
  }





Can anyone suggest a better method to grab just the number?
Logged

Des Moines, WA - USA
Offline Offline
God Member
*****
Karma: 25
Posts: 779
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Look into 'sscanf'
Logged

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

I don't think that I have ever had the opportunity to have a smiley face case. You are mighty lucky...
Logged

Wellington, New Zealand
Offline Offline
Sr. Member
****
Karma: 1
Posts: 404
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The code looks pretty close to a working solution, except you can only use one value per case statement, so case '0'..'9' and case ') dBm' are not going to work.  You'll have to use if statements instead.

e.g.

Code:

    if ((ch >= '0') && (ch <= '9')) {
       pos = pos * 10 + ch - '0';
    }


The WiFly sends a carriage return and a newline character at the end of that message, so the string is actually this: "RSSI=(-84) dBm\r\n".  So you can watch for the '\n' character to know when the full line has been received.

Logged


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

Quote
The code looks pretty close to a working solution, except you can only use one value per case statement, so case '0'..'9' and case ') dBm' are not going to work.
The '0'..'9' thing is an Arduino extension. It will work. The others do look unworkable, since there is not a range defined. Syntax-wise the code is correct, but the serial port will never contain a multibyte character value, so the case will never occur.
Logged

Pages: [1]   Go Up
Jump to: