Serial communication between Arduino and Matlab is losing data

后端 未结 2 883
名媛妹妹
名媛妹妹 2020-11-30 15:18

I am now trying to establish the serial communication between Arduino and Matlab. The script is very simple:

  1. Matlab send a number named as i to

相关标签:
2条回答
  • When you open the serial connection, the Arduino resets itself and the bootloader waits for potential sketch upload. This adds some delay before the sketch actually runs.

    Add a pause after you open the serial connection.

    fopen(s);
    pause(3);
    

    There are other options:

    1. Make the Arduino to announce when it's booted up, by sending something to the PC. For example you wait until the Arduino sends an S.

    2. I am not sure if this is possible with MATLAB, but if you disable the serial's DTR pin, the Arduino won't auto reset.

    3. Burn the code directly with the programmer, so the there is no bootloader which waits at boot. But this also prevents you from uploading the sketch via the USB.

    4. A hardware solution to prevent auto reset. But this prevents the necessary reboot during the sketch uploading, so you have to time the reset manually.

    0 讨论(0)
  • 2020-11-30 16:16

    The link you provide clearly notes that delay(2500); needs to be added to the Arduino setup() code to allow time for rebooting, during which the device may "behave unpredictably" (like dropping sent data?). You may need to pause the MATLAB code to accommodate for that as well, such as adding a pause(2.5) to your code after you open the serial connection (unless the fopen step already waits for the Arduino setup() to finish).

    Regarding your MATLAB code, one problem is that your code is set up so that it could possibly move ahead with sending more data before it has a chance to get the prior response. In addition, you should specify the precision of the data you're sending, like 'uint8' for an unsigned 8-bit integer or 'double' for a double-precision number (as is your case).

    What you probably want to do is just call fread without checking BytesAvailable first, since fread will block until it receives all of the data specified by the size argument (1 in this case). Only after receiving will your loop move on to the next iteration/message:

    for i = 1:1:a
      fwrite(s, i, 'double');
      rx(i) = fread(s, 1, 'double');
    end
    

    You could also try using only uint8 data:

    rx = zeros(1, a, 'uint8');
    for i = 1:1:a
      fwrite(s, uint8(i), 'uint8');
      rx(i) = fread(s, 1, 'uint8');
    end
    
    0 讨论(0)
提交回复
热议问题