Problem with serial Communication from MATLAB to Arduino

I'm trying to implement a communication from MATLAB to an Arduino Uno using Serial port.
I tried the simplest case I could imagine to test this communication but it still doesn't work.
My arduino code is the following :

#include <Servo.h>

Servo myservo;  // create servo object to control a servo


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  myservo.attach(3);
}

void loop() {
  // put your main code here, to run repeatedly:
    if(Serial.available()>0)
    {
      myservo.write(80);
    }
}

Basically, when Serial recieves anything, it moves the servo to a random position. I tried it with directly sending something in the serial monitor and it works fine.

However,
When I try to send anything with MATLAB using the simple following code :

clc;
delete(instrfindall);
clear s;
s=serial('COM16', 'BAUD', 9600);
fopen(s);
fprintf(s,"anything");
fclose(s);

The program runs, terminates, but nothing happens with the servo, indicating that nothing was recieved.

Thank you in advance for your help with this issue.

That is not what the code tells it to do

Which COM port is the Arduino using ?

Maybe I expressed myself poorly. From my understanding the code I wrote constantly listens to the port and when it detects any data published to the port, the servo moves to a specific position. Is it correct ?

It uses the COM16, as specified in the MATLAB code.

Hi @hugomil ,

are you sure about this

s=serial('COM16', 'BAUD', 9600);

I found different examples like this

s=serial('com4','baudrate',9600);

You may give it a try ...
ec2021

P.S.: You could also set the Baudrate separately:

s = serial('COM1');
s.Baudrate = 115200;
s.Terminator = 'CR';

Source 1 : mathworks 80833
Source 2 : mathworks baudrate

It's true that it looks like more the documentation page in MATLAB
Unfortunately I tried with this syntax but it doesn't change anything.

That's a pity...

A silly question: Did you close the Arduino IDE comms when you started Matlab communication?

If yes, do you know the default Baudrate of Matlab? It might be worth to test it (possibly 115200???).
ec2021

Does fwrite make a difference over fprintf

I even found examples that don't use a file in that way

s=serialport("COM16",9600)
configureTerminator(s,"CR")
writeline(s,"anything")

I second your post:

see https://de.mathworks.com/help/matlab/ref/serialport.write.html

image

@hugomil

Did you try that approach?

ec2021

Another thing to bear in mind when using PC software to communicate with your Arduino is that sometimes before you start you should peform a reset on the Arduino by setting RTS or DTR high like this

setRTS(s,true)
setDTR(s,true)

do this after creating your serial connection and before you try to communicate.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.