Clear Filters
Clear Filters

Arduino-Matlab Communication

7 views (last 30 days)
Sílvia Viñals
Sílvia Viñals on 3 Jun 2021
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);
}

Answers (2)

Vidip
Vidip on 15 Feb 2024
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

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!