arduino读取matlab串口,Matlab Arduino实时串行通信,采样0.004 s
我正在嘗試與matlab和arduino Uno進行實時通信 . 我們的想法是用PWM發送電機命令,并讀取傳感器值 . 但首先我想要在串口/ USB上進行實時通信 .
因此,arduino代碼正在等待來自matlab的調用,并且根據調用的類型,答案將被轉發到電機(控制命令)或編碼器值將被發送到筆記本電腦(讀取命令) .
在matlab部分,我使用了串行對象,并以高波特率打開 . 當我使用分析器檢查matlab中的時序時,看起來問題不是來自matlab方面,而是來自arduino /或串行通信 .
問題是由于某種原因,我需要一個非常小的采樣時間大約0.004秒 . 但無論波特率有多大,我都無法做到這一點 . 為了加快溝通,我應該改變什么?重要的是要提到我需要實時控制 . 使用0.004,我得到一些非常嘈雜的數據,平均值約為0.015;但是如果我將它改為0.015,仍會出現一些峰值 .
為了更好地理解這里是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
為簡單起見,我只提出了最重要的部分 . 和utread是一個具有以下形式的函數:
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
總結
以上是生活随笔為你收集整理的arduino读取matlab串口,Matlab Arduino实时串行通信,采样0.004 s的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是原始股
- 下一篇: centos中bash占用cpu,lin