arduino读取matlab串口,Matlab Arduino实时串行通信,采样0.004 s
我正在嘗試與matlab和arduino Uno進(jìn)行實(shí)時(shí)通信 . 我們的想法是用PWM發(fā)送電機(jī)命令,并讀取傳感器值 . 但首先我想要在串口/ USB上進(jìn)行實(shí)時(shí)通信 .
因此,arduino代碼正在等待來自matlab的調(diào)用,并且根據(jù)調(diào)用的類型,答案將被轉(zhuǎn)發(fā)到電機(jī)(控制命令)或編碼器值將被發(fā)送到筆記本電腦(讀取命令) .
在matlab部分,我使用了串行對(duì)象,并以高波特率打開 . 當(dāng)我使用分析器檢查matlab中的時(shí)序時(shí),看起來問題不是來自matlab方面,而是來自arduino /或串行通信 .
問題是由于某種原因,我需要一個(gè)非常小的采樣時(shí)間大約0.004秒 . 但無論波特率有多大,我都無法做到這一點(diǎn) . 為了加快溝通,我應(yīng)該改變什么?重要的是要提到我需要實(shí)時(shí)控制 . 使用0.004,我得到一些非常嘈雜的數(shù)據(jù),平均值約為0.015;但是如果我將它改為0.015,仍會(huì)出現(xiàn)一些峰值 .
為了更好地理解這里是arduino代碼:
const byte numChars = 8;
char receivedChars[numChars]; // an array to store the received data
int numb = 0;
boolean newData = false;
void setup() {
Serial.begin(250000);
Serial.setTimeout(100);
}
void loop() {
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
numb = atoi(receivedChars);
}
void showNewData() {
if (newData == true) {
if (numb==256)
Serial.println(numb);
newData = false;
}
}'
這是MATLAB代碼
for k = 1:N,
% time(k)
alpha(k) = utread;
%simple constant input, here goes the control algorithm
% u(k) = (-1 + k/255);
u(k) = sign(mod(k,5)-2);
% for aaa=1:100
% 1+2;
% end
utwrite(u(k));
%synchronize, wait for next sample time
time(k+1) = toc;
while(time(k+1)
time(k+1) = toc;
end
end
為簡(jiǎn)單起見,我只提出了最重要的部分 . 和utread是一個(gè)具有以下形式的函數(shù):
utread.m
global utip
fprintf(utip.s,'256>');
dat = fscanf(utip.s,'%d');
while (isempty(dat)) % wait for data on the serial
fprintf(utip.s,'256>');
dat = fscanf(utip.s,'%d');
end
總結(jié)
以上是生活随笔為你收集整理的arduino读取matlab串口,Matlab Arduino实时串行通信,采样0.004 s的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是原始股
- 下一篇: centos中bash占用cpu,lin