Issue moving data into arduino

Hello all, I do hope this question is appropriate for this forum. I'm interested in generating a vector in MATLAB, and subsequently transferring this data into Arduino. However, the code I have written thus far doesn't seem to work, and I'm having trouble pinpointing why that is exactly.

Here is the MATLAB code:

clear all
clc
if isempty(instrfindall)==0, delete(instrfindall), end;
data=[10,11,3,-6,-55,1,0,-10]; %here is the data I want to transfer
serialPort=serial('COM13','BaudRate',9600); %make communication
warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
fopen(serialPort); %Open serial port
    for i=1:length(data)
        fprintf(serialPort,'%d',data(i)); %write the data
    end
    fclose(serialPort);

And here is the Arduino Code:

int data;
void setup(){
  Serial.begin(9600);//defining serial communication
}
void loop(){
  //If there is data to read at the serial port
  if(Serial.available() > 0){
    data=Serial.read(); //save the data into a variable
    //Serial.println(data);
  }
  Serial.println(data); //print the data because I want to check if everything worked correctly
  //delay(10);
}

When I open the serial monitor after running the MATLAB code, all I see is that it is continuously printing 0's. Can anybody point out my mistake here? I'm still a bit new to Arduino, and I fear that I may have a simple lack of understanding as to how the serial monitor/communication works. I would appreciate any help I can get.

You are printing data every pass through loop whether or not you recieved anything. If you only print data inside the if block where you assigned it a value what happens?

    //Serial.println(data);

What happens if you uncomment this line ?

You can't use Matlab to communicate over the serial port and use the serial terminal at the same time. I'd start by flashing an LED when you get data from the serial connection so you can see when you are finally communicating. I'd also delay sending each data set by a second or so, just to be sure you are getting data to the Arduino. Since you are using com13 on the Matlab I assume that that's the serial port that you are using for the serial connection in the Arduino IDE, correct?

Jim.

UKHeliBob:

    //Serial.println(data);

What happens if you uncomment this line ?

Delta_G:
You are printing data every pass through loop whether or not you recieved anything. If you only print data inside the if block where you assigned it a value what happens?

Thank you both for your very quick replies. When I execute the printing inside the if block, nothing gets printed at all. It is completely blank.

AverageGuy:
You can’t use Matlab to communicate over the serial port and use the serial terminal at the same time. I’d start by flashing an LED when you get data from the serial connection so you can see when you are finally communicating. I’d also delay sending each data set by a second or so, just to be sure you are getting data to the Arduino. Since you are using com13 on the Matlab I assume that that’s the serial port that you are using for the serial connection in the Arduino IDE, correct?

Jim.

Hi Jim, yes, COM13 is the serial port I’m using in the Arduino IDE. Also, are you implying that if I waited long enough after transferring the data from MATLAB, then I would be able to use the serial monitor in Arduino? So, theoretically, if I had a long enough delay before I do Serial.begin(), then it should work?
Thanks for your insight.

Edit: Are you also saying that the data is in fact being transferred, but I am unable to save it into my variable in Arduino?

Aside from our fellows orientations, you might want to take a look at the code I just posted in this page in order to help another fellow user.

jalperto34: Thank you both for your very quick replies. When I execute the printing inside the if block, nothing gets printed at all. It is completely blank.

Hi Jim, yes, COM13 is the serial port I'm using in the Arduino IDE. Also, are you implying that if I waited long enough after transferring the data from MATLAB, then I would be able to use the serial monitor in Arduino? So, theoretically, if I had a long enough delay before I do Serial.begin(), then it should work? Thanks for your insight.

If you disconnect from the serial port in the Matlab instance, then you could connect the serial terminal in the IDE, but you are not collecting the data in the Arduino code, so you will never see it displayed. Also the data is coming over as a string but you are reading it into an int. That will give you problems. How many data points are you sending over? Remember the Arduino has limited memory.

Take a look at Serial.parseInt() to get the data from a string to a long integer. You'll have to dimension a long to receive the data and increment the array index to store it.

If you want, I'll give you some (untested) sample code.

Jim.

AverageGuy: If you disconnect from the serial port in the Matlab instance, then you could connect the serial terminal in the IDE, but you are not collecting the data in the Arduino code, so you will never see it displayed. Also the data is coming over as a string but you are reading it into an int. That will give you problems. How many data points are you sending over? Remember the Arduino has limited memory.

Take a look at Serial.parseInt() to get the data from a string to a long integer. You'll have to dimension a long to receive the data and increment the array index to store it.

If you want, I'll give you some (untested) sample code.

Jim.

Jim,

I think I'd like to take a look at your sample code, if anything I can at least compare it to what I'm doing with mine.

I thought by using "fclose(serialPort);" in MATLAB, I was in fact disconnecting the serial port. Or is there a time delay I'm not accounting for? And yes, I completely forgot that it's actually a string I'm reading-I'll go ahead and correct that and then see if it changes anything. And lastly, I think in my final project, I will be transferring around 120 data points to Arduino-which I realize I'll have to keep an eye on. I'll work on this and will update you soon, thanks.

/**
 * Run the matlab program for a maximum of 100 data points when it stops
 * bring up the serial terminal of the IDE and enter 999999 followed by an enter key, 
 * it should print what it got.
 * note you probably need a newline after each datapoint in the matlab program
 */
long data;
long hold[100]; // max of 100 data points
int n;
int done;
void setup(){
    Serial.begin(9600);//defining serial communication
    n=0;
    done=0;
}
void loop(){
    //If there is data to read at the serial port
    if(!done) {

        if(Serial.available() > 0){
            data=Serial.parseInt(); //save the data into a variable
            if(abs(data-999999) <1) {
                done=1;
            } else {
            hold[n++]=data;
            //Serial.println(data);
            }
        }
    }
    for(int i=0;i<n;i++) {
        Serial.println(hold[i]); //print the data because I want to check if everything worked correctly
    }
    //delay(10);
}

You may WILL have to tweak things to make it work.

SInce you are doing:

        fprintf(serialPort,'%d',data(i)); %write the data

You are running your numbers all together. The output of the matlab code if you printed a 25 followed by a 123 would be 25123 and the arduino wouldn’t know where the beginning/end of the numbers were.

I suggest (again, untestested)

        fprintf(serialPort,'%d\n',data(i)); %write the data

I know nothing about Matlab string formats so it might use " instead of ’ for special character expansion.

I’d also use the led blink I mentioned if all else fails to see if you are getting anything at all.

Jim.

You may find the examples in serial input basics useful for a simple reliable way to receive data. There is also a parse example

You need to design the system for sending data at the same time as the system for receiving it. Generally it is easier to tailor PC code to suit an Arduino than vice versa.

…R

This has been tremendously difficult for something I thought would be very straightforward. I've had absolutely no luck thus far.

AverageGuy: SInce you are doing:

        fprintf(serialPort,'%d',data(i)); %write the data

You are running your numbers all together. The output of the matlab code if you printed a 25 followed by a 123 would be 25123 and the arduino wouldn't know where the beginning/end of the numbers were.

I suggest (again, untestested)

        fprintf(serialPort,'%d\n',data(i)); %write the data

I know nothing about Matlab string formats so it might use " instead of ' for special character expansion.

I'd also use the led blink I mentioned if all else fails to see if you are getting anything at all.

Jim.

Unfortunately, while I think you're close, this code hasn't worked for me. I tried tweaking it myself many times as well to no avail. Each time I try to run it, and open the serial monitor, I don't see anything at all being printed. I beginning to wonder if the data from MATLAB is even reaching the serial monitor in the first place.

As for the LED blink, I found the following code online, and it seems to work perfectly:

MATLAB code:

clear all
clc

answer=1; % this is where we'll store the user's answer
arduino=serial('COM4','BaudRate',9600); % create serial communication object on port COM4

fopen(arduino); % initiate arduino communication

while answer
    fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
    answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): '); % ask user to enter value for variable answer
end

fclose(arduino); % end communication with arduino

Arduino Code:

int ledPin=13;
int matlabData;

void setup() 
{
  pinMode(ledPin,OUTPUT);
  Serial.begin(9600);
}

void loop() 
{
   
   if(Serial.available()>0) // if there is data to read
   {
    matlabData=Serial.read(); // read data
    if(matlabData==1)
      digitalWrite(ledPin,HIGH); // turn light on
    else if(matlabData==2)
      digitalWrite(ledPin,LOW); // turn light off
  }
}

When I tried running this it worked fine-I was able to turn the LED on and off by entering numbers in MATLAB. Perhaps the biggest difference with what's happening here and what I want to do is have both programs "use" the serial monitor? I'm not sure if that's even the case or what exactly it is I'm doing wrong at this point.

Robin2: You may find the examples in serial input basics useful for a simple reliable way to receive data. There is also a parse example

You need to design the system for sending data at the same time as the system for receiving it. Generally it is easier to tailor PC code to suit an Arduino than vice versa.

...R

fabianoantunes: Aside from our fellows orientations, you might want to take a look at the code I just posted in this page in order to help another fellow user.

Robin, I think the bolded is key-I guess I'm just not capable of doing something like that at this point. Do you have specific suggestions?

However, thank you both for posting this. Although I wasn't able to find anything in these two links that helped me solve my issue, they were useful in that they gave me a better basic understanding of serial communication.

If I can't transfer data from MATLAB directly into Arduino, does anyone have any other suggestions? Is it possible for Arduino to simply read from a text file, for example? Although I'd much prefer to use MATLAB, I think I just need to solve this problem anyway I can.

Edit: Would it be possible for example, if I wrote the data from MATLAB to a .txt file, then used some code written in C that reads in that data?

Edit (again): I guess I would have to write it in C then import it as a library in arduino since arduino doesn't support file reading/writing? Or would that not make sense?

You might want to let this code running in your Arduino, in order to see what MATLAB is spitting out to the serial port. Do not use String for your final version, thought your use can/will be memory intensive, but this should help you check if MATLAB is providing you with accurate information.

String inData = "";

void setup ()
{
    Serial.begin (9600); // Starting serial communication.
    Serial.println ("Serial Ready."); // Letting you know I'm ready.
    Serial.flush (); // For serial output to finish.
}

void loop ()
{
    inData = "";
    while (Serial.available () > 0)
    {
    int inChar = Serial.read (); // Collecting each byte at a time.
    inData += (char) inChar; // Concatenating it into a String.
    delay (10); // For serial read stability.
    }
    Serial.print ("Data Received: "); // Anouncing output for received data.
    Serial.println (inData.toInt ()); // Outputing received data as Int.
    while (Serial.available () == 0); // Waits for data to be available at serial port to start over again.
}

Your original code, with minor modifications, should definitely show something on the arduino

int data;
void setup(){
  Serial.begin(9600);//defining serial communication
}
void loop(){
  //If there is data to read at the serial port
  if(Serial.available() > 0){
    data=Serial.read(); //save the data into a variable
    Serial.println(data);
  }
}

So, if that is showing nothing, then nothing is coming in the serial port.

jalperto34: Robin, I think the bolded is key-I guess I'm just not capable of doing something like that at this point. Do you have specific suggestions?

If you give me an example of what you want to send, I will try. Just give an example of the data without any code.

...R

fabianoantunes: You might want to let this code running in your Arduino, in order to see what MATLAB is spitting out to the serial port. Do not use String for your final version, thought your use can/will be memory intensive, but this should help you check if MATLAB is providing you with accurate information.

String inData = "";

void setup () {     Serial.begin (9600); // Starting serial communication.     Serial.println ("Serial Ready."); // Letting you know I'm ready.     Serial.flush (); // For serial output to finish. }

void loop () {     inData = "";     while (Serial.available () > 0)     { int inChar = Serial.read (); // Collecting each byte at a time. inData += (char) inChar; // Concatenating it into a String. delay (10); // For serial read stability.     }     Serial.print ("Data Received: "); // Anouncing output for received data.     Serial.println (inData.toInt ()); // Outputing received data as Int.     while (Serial.available () == 0); // Waits for data to be available at serial port to start over again. }

I think you've gotten to the root of the problem here. When I ran this code, here is what I saw appear on the serial monitor:

Serial Ready.

Data Received: 0

I'm guessing this suggests that the data isn't even being sent in the first place? This is very bizarre, seeing as how simple my MATLAB code is, and also that the LED code I used earlier worked fine (showing me what I'm trying to do is possible?). I could be way off here, but do you think that the data could somehow be disappearing after I close serial communication in MATLAB (last line of my code)? I'm just not sure of how to make sense of all this.

arduinodlb: Your original code, with minor modifications, should definitely show something on the arduino

int data;
void setup(){
  Serial.begin(9600);//defining serial communication
}
void loop(){
  //If there is data to read at the serial port
  if(Serial.available() > 0){
    data=Serial.read(); //save the data into a variable
    Serial.println(data);
  }
}

So, if that is showing nothing, then nothing is coming in the serial port.

I can confirm that this indeed shows nothing. There must be something very fundamental I'm missing. Either way, I think that it's something wrong in MATLAB, rather than arduino. Or, there's something about serial communication/the serial monitor that I'm missing. Do you have any suggestions?

Robin2: If you give me an example of what you want to send, I will try. Just give an example of the data without any code.

...R

Hi Robin, thanks a lot for your offer. Basically, if you just imagine a one dimensional vector filled with random positive and/or negative integers (ranging from a length of 6 as a minimum, and a maximum of 120)-that's what I want to transfer to Arduino. For example, a vector v =[1,0,-10,185,-99]. Is this enough information? Is my MATLAB code of any help, or am I completely off the mark with that? Again, thanks a lot either way.

jalperto34: When I open the serial monitor after running the MATLAB code, all I see is that it is continuously printing 0's. Can anybody point out my mistake here? I'm still a bit new to Arduino, and I fear that I may have a simple lack of understanding as to how the serial monitor/communication works. I would appreciate any help I can get.

So you're opening the serial monitor to receive data from the Arduino after sending data to it from Matlab? That's not going to work for two reasons: 1. opening the serial monitor auto-resets the Arduino, so your program won't even remember what it received previously (unless you either disable the auto-reset in hardware or store the data in non-volatile memory to send it after the Arduino resets). 2. your program already sent its data to Matlab (even if Matlab doesn't read the data) before the serial monitor started.