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

Callum
  • 13
  • 3

1 Answers1

2

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;
}
Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81