How to properly connect my Arduino with the serial port?

13 visualizaciones (últimos 30 días)
Abrahim
Abrahim el 3 de Dic. de 2022
Respondida: Dhruv el 23 de Mzo. de 2023
I am working on a project that works with two arduinos. One arduino contains a stepper motor and a servo motor. While the other one only has a stepper motor. However, every time I run my program I always get a, "Error uing serialport".
Here is my program:
%Clear exisiting ports
clear s;
%Setup arduino
a=arduino;
%Set up stepper for x direction
stx=serialport("COM4",9600);
pause(2);
%Set up servo
sr = servo(a, 'D6', 'MinPulseDuration', 700*10^-6, 'MaxPulseDuration', 2300*10^-6);
%Set up stepper for trigger
stt=serialport("COM6", 9600);
pause(2);
%Move launcher
distx=500;
write(stx,int2str(distx),'string');
pause(2);
%Move servo
writePosition(sr, 0);
pause(2);
writePosition(sr, 0.25);
pause(2);
%Move trigger
distt=-500;
write(stt,int2str(distt),'string');
pause(2);
%Move trigger back
distt=500;
write(stt,int2str(distt),'string');
pause(2);
%Move servo back
writePosition(sr, 0);
pause(2);
%Move launcher back to initial position
distx=-500;
write(stx,int2str(distx),'string');
pause(2);
disp("Finish");

Respuestas (1)

Dhruv
Dhruv el 23 de Mzo. de 2023
Based on the error message "Error using serialport", it appears that there is a problem with opening the serial port. This could be caused by several factors, such as the port being used by another program, incorrect port settings, or a faulty connection between the computer and the Arduino.
In the program, which uses two serial ports: "COM4" and "COM6". It's possible that one or both of these ports are not available or are already in use by another program. This can be checked by verifying it in the Device Manager on the computer and looking under the "Ports (COM & LPT)" section to see if the ports are listed and available.
If the ports are available, try adjusting the port settings to make sure they match the settings used by your Arduino code. For example, make sure the baud rate (9600 in your code) is the same on both the MATLAB side and the Arduino side.
If none of these solutions work, check the wiring and connections between the Arduino and your computer. Make sure the USB cable is properly connected and that the correct port is selected in MATLAB.
Also, it's good practice to close any open serial ports before re-running your program.
Hopefully, one of these suggestions will help you resolve the issue.

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by