1

I have read through a number of posts including How do I split an incoming string? However I cannot work out how to extract numbers from a serial string.

My challenge is this;

I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.

The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.

Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.

If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.

Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.

Thanks

Callum

3

I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a decimal point just after it. You can use strchr() to find them. Then, you will have to prepend a zero if needed, and terminate the string one character before the decimal point.

The following code does this by overwriting the original string. If you need to keep that string, you will instead have to copy the relevant characters to another buffer:

char * get_freq(char *message)
{
    char *space = strchr(message, ' ');
    char *dot   = strchr(message, '.');

    if (!space || !dot || dot - space < 5)
        return NULL;    // invalid message

    if (dot - space == 5)
        *space = '0';   // prepend a zero

    *(dot - 1) = '\0';  // terminate the string

    return dot - 5;
}
| improve this answer | |
  • Forgive me if I sound a little dense with this question but how do I fit that in to a routine that is called every 5 seconds. I call the serial command 'freq\r' command every 5 seconds to check the frequency of the radio? Not sure why this is not obvious to me but I am, obviously, a beginner. – Callum Aug 6 '16 at 5:06
  • @Callum: Standard approach: whenever a char is .available() on the Serial port, you .read() it into a buffer[]. When you see a '\n', you know you have a complete message and you can get_freq(buffer). Do this in loop(), not in the query-sending routine that you call every 5 seconds. – Edgar Bonet Aug 6 '16 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.