首页 > 解决方案 > MATLAB - Arduino 串行通信

问题描述

我想将一个整数从 MATLAB 发送到 Arduino。我希望将整数发回并在 MATLAB 中显示。有时 MATLAB 上不显示任何内容,有时会显示错误的整数,例如 -457。如果有人可以阅读以下代码,我将不胜感激。如果有更简单的方法来解决这个问题,请告诉我。谢谢。

MATLAB代码:

s = serial('/dev/tty.KeySerial1')
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',9600);
set(s,'Parity','none');
fopen(s);
a='b';
while (a~='a');
    a=fread(s,1,'uchar');
end 
if (a=='a')
    disp('serial read');
end 
fprintf(s,'%c','a');
mbox= msgbox('serial com set up complete'); uiwait(mbox);
fprintf(s, '%d\n', 589367);
fscanf(s,'%s')

Arduino草图:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  // check serial communication 
  Serial.println('a');
  char a='b';
  while (a !='a')
  { a=Serial.read();
  }

}

void loop() {
  // put your main code here, to run repeatedly:
  while(Serial.available()==0); 
  int val=Serial.parseInt();
  Serial.print("integer received: ");
  Serial.println(val);
}

标签: matlabserializationarduino

解决方案


推荐阅读