Serial Communication with Arduino
45 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I want that a serial communication with an Arduino.
They can communicate. I did it over the serial Connection without addons.
As next step I want to send with MatLab a "start send" message to the Arduino. At the moment the Arduino receive the message the controller should start the programm to send the data to matLab.
Sadly it doesnt work.
I hope that you can help me!
Thanks Lisa
0 件のコメント
回答 (1 件)
Mark Sherstan
2019 年 3 月 22 日
Your code should look something like this. Not the fprintf on the MATLAB side and the if (Serial.avilable() > 0 ) on the Arduino side.
MATLAB
% s is the serial port object...
fprintf(s, 'a'); % Send character to ardiuno
out = fscanf(s, '%40s\n'); % Read data from ardiuno
split = strsplit(out, ','); % Seperate data based off commas
% Continue to process...
ARDUINO
void setup(){
Serial.begin(115200);
Serial.setTimeout(3);
... set up
}
void loop(){
... data acquistion and processing
if (Serial.available() > 0) {
incomingString = Serial.readString();
if (incomingString == "a\n") {
Serial.print(data1); Serial.print(","); Serial.println(data2);
}
}
}
4 件のコメント
Mark Sherstan
2019 年 3 月 27 日
I would reccomend having the Ardiuno just printing a single analog value and use MATLAB to create your array of data for processing. You will have to modify the code below depending on the size of your array but this is a fully working system that should push you in the right direction. You may also want to consider checking out this link.
ARDUINO
// Declare variables
int rawSensorVal;
String incomingString;
void setup(){
// Initialize serial port
Serial.begin(115200);
Serial.setTimeout(3);
}
void loop(){
// Read analog pin
rawSensorVal = analogRead(A0);
// Check if MATLAB has sent a character
if (Serial.available() > 0) {
incomingString = Serial.readString();
// If character is correct send MATLAB the analog value
if (incomingString == "a\n") {
Serial.println(rawSensorVal);
}
}
}
MATALB
% Connect to serial port
s = serial('/dev/cu.usbmodem14101', 'BaudRate', 115200);
fopen(s);
pause(3);
fprintf("Connection established\n")
% Start a counter and timer
count = 0;
tic
startTimer = toc;
% Get data for 5 seconds
while (toc < startTimer+5)
% Send character and receive data
fprintf(s, "a");
out = fscanf(s, '%d\n');
% Display data to user
fprintf("%d\n",out)
% Increment counter
count = count + 1;
end
% Display sample rate to user
endTimer = toc;
fprintf("Sample rate was: %0.2f Hz\n",count/(endTimer - startTimer))
% Remove serial port connection
fclose(s);
delete(s)
clear s
参考
カテゴリ
Help Center および File Exchange で MATLAB Support Package for Arduino Hardware についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!