how to use scanf

21 Aug 2010

hello,

I'm sure it's a simple matter but it doesn't seem to be working the way I expect it to.  I have a device that transmits a string like "R125\r".  I need to store 125 as an integer, and from research it looks like I'm supposed to do something like serialobj.scanf("R%3d", &result); and then int result should be 125.  This is not working and result is some incorrect number constantly.

Are there any more docs for Serial::scanf that I could look at, or could someone explain this function better?  Thanks to everyone.

21 Aug 2010

Hi Thomas,

What you are doing looks spot on. Here is a test program I just wrote:

// serial scanf test
// wire p9 - p10

#include "mbed.h"

Serial s(p9, p10);

int main() {
    s.printf("R125\n");
    int r;
    int n = s.scanf("R%3d", &r);
    printf("n = %d, r = %d\n", n, r);
}
and the result i get is:

n = 1, r = 125
In your code, i'd have a go at reading the return value of scanf to see how many elements it thinks it has read. If it is not what you expect (i'd suspect it is 0), the result is unlikely to be valid. Maybe your serial connection is sending other characters too, so the first thing it reads is not "R" and hence it exits scanf at that point?

For more information on scanf, a good reference is:

When you find out what is up, it'd be great if you could share it. You won't be the last to be fighting scanf :)

Simon

22 Aug 2010

Hey Simon, thanks man!

The device outputs ASCII 'R', followed by a 3 digit int, follwed by ASCII 13.  The debugging advice worked.  The problem is scanf will not read ASCII 13 (carriage return).  I tried to use

serialobj.scanf("R%d\r", &range);

with the "\r" escape sequence for the ASCII 13.  For some reason this does not work (I have no idea why).  To take care of this, i did

serialobj.scanf("R%d", &result);
serialobj.getc();

to store the number into result and follow it with a char read to get that ASCII 13 out of the buffer.  This makes the next R the next byte in the buffer, which allows the next scanf to work correctly.

Let me know if there is a way to fix the ASCII 13 issue, I'm not sure if it is my mistake or the chip's (probably mine).  Thanks again for all of the help.

Thomas

11 Oct 2010

I had a similar problem reading the CR '13' in a strcmp() function.  I ended up replacing the '13' with a '\0' in the buffer and things started to work fine.