Arduino-Matlab Communication

11 次查看(过去 30 天)
Dear Matlab experts,
I'm starting on the Matlab world and I want to connect my arduino (which only blinks if receives data) with the following Matlab code.
The problem is that if I run it by sections, the code works perfectly. However, when I run the full code it runs out of time and cannot connect to the arduino code. Does anyone have found this issue? I have also tried the second port of MACOS (/dev/cu.usbserial-AR0KKSET) and the code didn't work.
Thanks in advance!
MATLAB CODE
close all;
clc;
clear all;
instrreset
%%Initialize the serial port in MACOS
arduinoPort= '/dev/tty.usbserial-AR0KKSET';
puerto_serial = serial(arduinoPort,'BaudRate',9600);
%%Opens the port
fopen(puerto_serial);
mode=3;
disp(mode);
%%Send argument to arduino
fprintf(puerto_serial,mode);
%%
%%Recibe OK from arduino
value=fscanf(puerto_serial,'%d');
disp(value);
value=fscanf(puerto_serial,'%d');
disp(value);
%%Close serial port
fclose(puerto_serial);
delete(puerto_serial);
clear all;
ARDUINO CODE
int mode=0;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if(Serial.available()>0)
{
Serial.println(4);
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000);
Serial.println(7);
}

回答(2 个)

Vidip
Vidip 2024-2-15
While running the entire MATLAB code at once, it's possible that the serial communication with the Arduino isn't being given enough time to establish before sending data. This can cause a timeout error or a failure to connect properly.
It seems that this issue is not related to MATLAB, rather it is related to the Arduino. This Arduino Community forum post talks about details of this issue: https://forum.arduino.cc/t/delay-when-receive-data-from-arduino-nano-in-first-time-plug-usb-cable/140746
For resolution try adding a "pause" statement immediately after opening the serial connection with "fopen", this change should prevent the timeout.

MathWorks MATLAB Hardware Team
Hi,
Here are few things you can consider :
Please feel free to contact us if you need any assistance,
https://www.mathworks.com/support/contact_us.html
Thanks,
MATLAB Hardware Team
MathWorks

类别

Help CenterFile 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!

Translated by