9 years, 4 months ago.

scanf problems with Serial and Matlab

I am trying to pass some values from Matlab to mbed and have been experiencing problems with the scanf function. I am using the following code

include the mbed library with this snippet

if (pc.readable() > 0){
        int number;
        pc.scanf("%d", &number);
        wait(0.1);
        
        if (number == 1) {
            led_red = 0;
        }
        sendData(number);
    }

And in matlab I have

include the mbed library with this snippet

s = serial('/dev/tty.usbmodem1422')
fopen(s)
fprintf(s,'%d', 1) // have tried fprintf(s,'%d', '1'), fprintf(s,'%d\r\n', 1) and combinations of these

I am using the red led in the mbed to check that the 1 I am sending from Matlab is reaching the device. The problem is that the led is not turning on. I see the small green led blink as I send the fprint but nothing happens in the mbed. I have tried different things with newlines etc...

Solution: check your Matlab terminator: http://www.mathworks.com/help/instrument/terminator.html and use it every time you printf

posted by eum c 09 Jan 2015

1 Answer

9 years, 4 months ago.

I think for sure it needs a terminator (so \n) in the end. But in general, try it with a serial terminal program first, and see if that works.

Accepted Answer

What exactly needs a \n? Matlab or mbed?

posted by eum c 09 Jan 2015

scanf as far as I am aware. Or at least some kind of terminator. Maybe even whitespace works, but it needs to know the number is finished. So in the matlab code.

posted by Erik - 09 Jan 2015