要实现的功能:
1. matlab发送‘a’的话,返回传感器数据
2. matlab发送数值的话,需要用这个数值做别的计算
有没有哪位大神做过,求例子。
下面是我编写的程序,arduino端运行的不错。但是matlab端老是出问题
1. 首先要是不在读到串口之后加个pause,程序好像不往下运行了,之后的计算都不显示。
2. 因为要不停的读取传感器数据(matlab一直发送‘a’),要是matlab再往arduino发送数值的时候,matlab就出错,,说错误使用pause
怎么解决啊
arduino程序:
[mw_shl_code=c,true]while (Serial.available() > 0){
comdata += char(Serial.read());
delay(5);
}
if (comdata.length() > 0){
if (comdata =="a"){
Serial.println(Pos);
comdata = "";
}
else{
char charData[comdata.length()+1];
comdata.toCharArray(charData,comdata.length()+1);
GoalPos=atof(charData);
comdata = "";
}
}[/mw_shl_code]
Matlab程序:
[mw_shl_code=c,true]%% 串口连接
serialCom = serialConnectionToArduino('COM5', 9600);
serialCom.startSerialConnection();
%% 读串口
while(status==1)
serialCom.sendValueToSerialArduino('a');
updatedPos = serialCom.getValueFromSerialArduino();
while(updatedPos=='a')
updatedPos = serialCom.getValueFromSerialArduino();
end
pause(0.01)
if class(updatedPos)=='char'
Pos=str2num(updatedPos);
else
Pos=updatedPos;
end
end
%% 写串口 comData可以是字符或数字
if class(GoalPos) == 'char'
comData=num2str(data);
else
comData=data;
end
serialCom.sendValueToSerialArduino(comData);
%% 子函数
classdef serialConnectionToArduino < handle
properties
Timeout
baudRate;
comPort;
serialConnection;
end
methods
function obj = serialConnectionToArduino(comPort, baudRate,Timeout)
if nargin == 0
comPort = 'COM5';
baudRate = 9600;
Timeout=0.2;
end
obj.comPort = comPort;
obj.baudRate = baudRate;
obj.Timeout=Timeout;
end
function startSerialConnection(obj)
obj.serialConnection = serial(obj.comPort, 'BaudRate', obj.baudRate, 'Timeout',obj.Timeout);
fopen(obj.serialConnection);
end
function sendValueToSerialArduino(obj, stringMsg)
fprintf(obj.serialConnection,'%s', stringMsg);
end
function inputValue = getValueFromSerialArduino(obj)
if (obj.serialConnection.BytesAvailable > 0)
inputValue = fscanf(obj.serialConnection);
%inputValue=str2num(fgetl(obj.serialConnection))
else
inputValue = 'a';
end
end
function closeSerialConnection(obj)
fclose(obj.serialConnection);
end
end
end[/mw_shl_code]