Serial communication between Arduino and Matlab is losing data

后端 未结 2 894
名媛妹妹
名媛妹妹 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条回答
  •  无人及你
    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
    

提交回复
热议问题