Arduino 和 Matlab 之间的串行通信正在丢失数据 [英] Serial communication between Arduino and Matlab is losing data

查看:35
本文介绍了Arduino 和 Matlab 之间的串行通信正在丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在尝试在 Arduino 和 Matlab 之间建立串行通信.脚本很简单:

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

  1. Matlab 向 Arduino 发送一个名为 i 的数字;

Arduino 收到这个 i,然后将其发送回 Matlab;

Arduino receive this i, then send it back to Matlab;

重复步骤 1&2 10 次,即 Matlab 向 Arduino 发送 1,2,...,10,然后从 Arduino 接收 1,2,...,10.但是,Matlab 只取回 3,4,...,10,而第一个 i=1 和 i=2 丢失了(我现在已经使 inputbuffersize=200,仍然不对).

Repeat step 1&2 for 10 times, i.e., Matlab sends 1,2,...,10 to Arduino, then receive the 1,2,...,10 from Arduino. However, Matlab only get back 3,4,...,10, while the first i=1 and i=2 are lost (I have already made the inputbuffersize=200 now, still not right).

以下是来自 Matlab 的代码:

Hereby is the code from Matlab:

clc,clear;
s=serial('COM16','BaudRate',9600); 
s.InputBufferSize = 200;    
fopen(s);
a=10;
rx = zeros(1, a); % rx is used to store the data send back by Arduino
ry = zeros(1, a); % ry is just helping me to see what happens in Serial
for i = 1:1:a
  fwrite(s, i); % Start to write the value "i" through serial to Arduino
  pause(0.5) % if no pause, the result is worse than now
  ry(i) = s.BytesAvailable; % check how many data are there in the Buffer
  if s.BytesAvailable>0
      rx(i) = fread(s, s.BytesAvailable); % Record the data send by Arduino
  end
end
fclose(s);

和 Arduino 代码:

And the Arduino Code:

char ibyte;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  if(Serial.available()>0)
  {
    ibyte=Serial.read();
    Serial.write(ibyte);
  }
}

我的参考链接是:http://robocv.blogspot.com/2012/01/serial-communication-between-arduino.html

推荐答案

当您打开串行连接时,Arduino 会自行重置并且引导加载程序等待潜在的草图上传.这会在草图实际运行之前增加一些延迟.

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);

还有其他选择:

  1. 通过向 PC 发送一些信息,让 Arduino 在启动时发出通知.例如,您等到 Arduino 发送一个 S.

我不确定这是否适用于 MATLAB,但如果您禁用串行的 DTR 引脚,Arduino 将不会自动重置.

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.

直接用编程器烧写代码,没有bootloader等待启动.但这也会阻止您通过 USB 上传草图.

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.

防止自动重置的硬件解决方案. 但这会阻止在草图上传期间进行必要的重启,因此您必须手动确定重置时间.

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.

这篇关于Arduino 和 Matlab 之间的串行通信正在丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆