MATLAB and Arduino Communications

6 ビュー (過去 30 日間)
Kishita Rajesh
Kishita Rajesh 2023 年 11 月 29 日
コメント済み: Mohammed Yakoob 2025 年 1 月 21 日
Hello Everyone,
So I am working on a robotics project that has two levels of control. The main control algorithms are written in MATLAB and lower-level control is developed to control driving and steering motors using Arduino.
The Matlab sends steering and speed commands to Arduino and using that Arduino will run the robot. Now everything is working fine on MATLAB end and it sends the commands but the Arduino is only processing the first command and doesn't run the following commands.
Also, sometimes I get an error on MATLAB saying a timeout occurred during write operation. Now I researched about it and basically the read operation started before the write function could complete. How can I overcome this problem?
Here is MATLAB code:
function [ ard_serial_port, Error ] = setup_arduino( device_port )
% concatenation preserves whit space instead of strcat
PROMPT01 = ['Please enter COM port # (1 for COM1, etc.) for Arduino'];
TITLE01 = 'COM port';
Error = false;
ard_serial_port = '';
% Use the default port for the device you're using in your pc:
ComNum = char(inputdlg(PROMPT01, TITLE01, 1, {num2str(device_port)}));
if isstrprop(ComNum, 'digit')
% Create a serial port object.
ard_serial_port = instrfind('Type', 'serial', 'Port', strcat('COM', ComNum), 'Tag', '');
% Create the serial port object if it does not exist
% otherwise use the object that was found.
if isempty(ard_serial_port)
ard_serial_port = serial(strcat('COM', ComNum)); % Create serial object (PORT Dependent)
else
fclose(ard_serial_port);
ard_serial_port = ard_serial_port(1);
end
% Number of bytes in inout buffer
% ard_serial_port.InputBufferSize = 512;
ard_serial_port.BaudRate = 38400;
ard_serial_port.DataBits = 8;
ard_serial_port.StopBit = 1;
ard_serial_port.Timeout = 5;
ard_serial_port.Parity = 'none';
ard_serial_port.StopBits = 2;
ard_serial_port.BytesAvailableFcnMode = 'terminator';
ard_serial_port.Terminator = 'CR/LF';
try
% Connect to the instrument, Open the serial port for r/w
fopen(ard_serial_port);
catch exception
fprintf(['\n' exception.message '\n']);
h = msgbox(exception.message);
Error = true;
end
else
fprintf('\nInvalid COM port for Arduino selected\n');
% msgbox('Invalid COM port selected.');
Error = true;
end
And here is code to send commands to Arduino
function [control_command] = serial_write_master_arduino(ard_serial_port, delta_master, speed_ref)
control_command = sprintf('%f,%f$', delta_master, speed_ref)
fprintf(ard_serial_port, control_command);
end

回答 (1 件)

Namnendra
Namnendra 2024 年 9 月 9 日
Hello Kishita,
It sounds like you're encountering a couple of issues with the serial communication between MATLAB and Arduino. Let's address the problems one by one:
Problem 1: Arduino Only Processes the First Command
This issue might be due to how the Arduino is handling incoming serial data. Ensure that the Arduino code is structured to continuously read from the serial buffer and process each command. Here are some tips:
1. Arduino Code: Make sure the Arduino is set up to read until a specific terminator (like `$`) and then process the command. Here's a basic structure for the Arduino code:
void setup() {
Serial.begin(38400);
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('$'); // Read until the terminator
// Process the command here
// Example: parse and execute the command
}
}
2. Clear the Buffer: Ensure the Arduino is clearing the buffer after processing each command to avoid overflow or incorrect reads.
3. Flow Control: Consider implementing a simple handshake mechanism where the Arduino sends back an acknowledgment after processing a command, and MATLAB waits for this acknowledgment before sending the next command.
Problem 2: MATLAB Timeout During Write Operation
The timeout error suggests that the write operation might be blocking or taking too long. Here are some suggestions to mitigate this:
1. Increase Timeout: You can try increasing the `Timeout` property in MATLAB to give more time for the operation to complete:
ard_serial_port.Timeout = 10; % Increase this value as needed
2. Flush the Output Buffer: Before sending a new command, ensure the output buffer is clear.
3. Check for Acknowledgment: Modify your MATLAB script to wait for an acknowledgment from Arduino before sending the next command:
function [control_command] = serial_write_master_arduino(ard_serial_port, delta_master, speed_ref)
control_command = sprintf('%f,%f$', delta_master, speed_ref);
fprintf(ard_serial_port, control_command);
% Wait for acknowledgment
ack = fscanf(ard_serial_port);
if ~strcmp(ack, 'ACK') % Replace 'ACK' with your actual acknowledgment
error('No acknowledgment received from Arduino');
end
end
4. Error Handling: Implement error handling to retry sending commands if a timeout occurs.
General Tips
- Debugging: Use serial monitors or print statements in Arduino to debug and ensure commands are being received correctly.
- Synchronization: Ensure that both systems (MATLAB and Arduino) are synchronized in terms of baud rate and terminators.
- Testing: Test with simple commands first to ensure basic communication works before moving on to more complex commands.
By addressing these areas, you should be able to improve the reliability of the communication between MATLAB and Arduino.
Thank you.
  1 件のコメント
Mohammed Yakoob
Mohammed Yakoob 2025 年 1 月 21 日

Hello dear, Please I need to know how to clear the internal buffers when I have been using the arduino() class to connect with??

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeModeling についてさらに検索

製品


リリース

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by