Send data from Matlab to Arduino Mega 2560

9 views (last 30 days)
Gabriele Casay
Gabriele Casay on 20 Jun 2013
Edited: Walter Roberson on 7 Apr 2016
Please I need help.
My program in Matlab sends 8 double values to the arduino. This values are voltages from 0 to 10 V. The values are sent by the serial USB Port.
In Matlab:
clear all
clc
%Creates a serial connection
serialPort=serial('COM4','BaudRate',9600);
%Change the Terminator property of the serial port to make it faster
%set(serialPort,'Terminator','CR');
%Informs about errors
warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
%Opens the serial port
fopen(serialPort);
volt=[10,10,10,101,10,10,10,10];
%Voltages are mapped from 0-10 to 0-100000
for i=1:length(volt)
voltmapped(i)=map2(volt(i),0,10,0,100000);
end
display('Press any button to continue.');
pause
for i=1:length(voltmapped)
fprintf(serialPort,'%d',voltmapped(i));
end
fclose(serialPort);
Matlab map the values to get all integers. The micro-controller convert again this values in double.
Arduino: float data_rec; float data_conv1,data_conv2; float volt; int portNum;
void setup(){
portNum=6;
Serial.begin(9600);//A serial communication is defined
for(int i=6;i<14;i++){
analogWrite(i,0);
}
}
void loop(){
//If there is data to read at the serial port
if(Serial.available() > 0){
if(portNum>13){
portNum=6; //All ports have a voltage, then start again to set
//values from port 2
}
data_rec=Serial.parseInt(); //Converts the string received into an integer
//it is also converted into a double by implicit conversion
data_conv1=(data_rec)/10000; //Voltage value sent from Matlab through the serial port
volt=convert(data_conv1,0,10,0,255); //Voltage value converted, to set the voltage value
//into the analog port
analogWrite(portNum,volt); //Sets the output port with the desired voltage value
portNum++;
}
delay(10);
}
/* Function responsible for expressing the voltage values within the interval [0,255] */
float convert(double val,double fromLow,double fromHigh, double toLow, double toHigh){
double aux1,aux2;
aux1=val/(fromHigh-fromLow);
aux2=aux1*(toHigh-toLow);
return aux2;
}
Using this code does not fix the analog ports with the values. But using this other code it works.
Matlab:
clear all
clc
%Creates a serial connection
serialPort=serial('COM4','BaudRate',9600);
%Change the Terminator property of the serial port to make it faster
%set(serialPort,'Terminator','CR');
%Informs about errors
warning('off','MATLAB:serial:fscanf:unsuccessfulRead');
%Opens the serial port
fopen(serialPort);
volt=[10,10,10,101,10,10,10,10];
%Voltages are mapped from 0-10 to 0-100000
for i=1:length(volt)
voltmapped(i)=map2(volt(i),0,10,0,100000);
end
display('Press any button to continue.');
pause
for i=1:length(voltmapped)
fprintf(serialPort,'%d',voltmapped(i));
a(i)=fscanf(serialPort,'%d');
end if true
% code
end
fclose(serialPort);
Arduino:
float data_rec;
float data_conv1,data_conv2;
float volt;
int portNum;
void setup(){
portNum=6;
Serial.begin(9600);//A serial communication is defined
for(int i=6;i<14;i++){
analogWrite(i,0);
}
}
void loop(){
//If there is data to read at the serial port
if(Serial.available() > 0){
if(portNum>13){
portNum=6; //All ports have a voltage, then start again to set
//values from port 2
}
data_rec=Serial.parseInt(); //Converts the string received into an integer
//it is also converted into a double by implicit conversion
data_conv1=(data_rec)/10000; //Voltage value sent from Matlab through the serial port
volt=convert(data_conv1,0,10,0,255); //Voltage value converted, to set the voltage value
//into the analog port
analogWrite(portNum,volt); //Sets the output port with the desired voltage value
Serial.println(volt);
portNum++;
}
delay(10);
}
/* Function responsible for expressing the voltage values within the interval [0,255] */
float convert(double val,double fromLow,double fromHigh, double toLow, double toHigh){
double aux1,aux2;
aux1=val/(fromHigh-fromLow);
aux2=aux1*(toHigh-toLow);
return aux2;
}
The difference are just two lines and i don't know why it does not work in the two first codes.
  1 Comment
Ella
Ella on 22 Nov 2015
Matlab 2015 no longer has analogWrite function Please let us know how we can do it ?

Sign in to comment.

Answers (5)

David Sanchez
David Sanchez on 20 Jun 2013
The two lines you talk about are these: On matlab:
a(i)=fscanf(serialPort,'%d');
on arduino:
Serial.println(volt);
On the matlab part, you are reading from the serial port, in the first version you do not do it, and consequently, you can not retrieve data sent by arduino.
On the arduino part, you send data through serial port, if you do not do it as in the first version, it can not be read.

Sita Drost
Sita Drost on 7 Apr 2016
Edited: Walter Roberson on 7 Apr 2016
Sorry, I know this question is quite old, but I had the same problem with my Arduino, and this question kept coming up in my Google search results, so I thought I might as well post a link to the solution I found. I found the information here very helpful: https://forum.processing.org/one/topic/note-that-serial-now-resets-most-arduino-boards.html

Gabriele Casay
Gabriele Casay on 20 Jun 2013
Hi David,
I forgot to mention that the output ports are connected to a non-inverted amplifers with gain 2. So they can reach values from 0 to 10V. When I take measures with the voltimeter at the outputs, only the two second codes work. The lines: a(i)=fscanf(serialPort,'%d'); and Serial.println(volt); are only useful if you are interested in sending back the to matlab the received values. Then when I send the values to the arduino and try to set the voltajes with the values received in arduino, they are not set in the second solution, but the first with these additional lines. Thank you for your answer

David Sanchez
David Sanchez on 20 Jun 2013
When you measure the signal, the voltmeter introduces a voltage drop in the line so that the signal does not arrive its destiny (the input pin on arduino). Does your code work when you do not measure the value in the communication line? What is the point of the amplifier in the signal/communication line?

Gabriele Casay
Gabriele Casay on 20 Jun 2013
Creo que me voy a explicar mejor en castellano. El programa lo utilizo para un sistema automático para un radar. La antena es un array de antenas. Y para cambiar la directividad hay que alimentar unos phase shifter con diferentes tensiones continuas. Estas tensiones se calculan en matlab. El rango es de 0 a 10V. Arduino solo puede proporcionar de 0 a 5 V por o que la salida va conectada a unos op amp de ganancia dos. Entonces, con la segunda que he colgado funciona. Lo que hace es establecer el voltaje necesario en cada puerto y además recibe en matlab los valores que se han establecido en cada puerto analógico del micro-controlador. Pero es muy lento porque envía y recibe valores. Para acelerar el programa solo quería enviar los voltajes de matlab a arduino y comprobar que efectivamente se establece el voltaje deseado en los puertos de salida. Pero no es asi, en la primera solución en que se he omitido las líneas que envían los datos de arduino a matlab no funciona nada. Al medir a la salida de los puertos y los amplificadores el valor en voltios es 0, tal y como he establecido en la función setup.

Categories

Find more on Simulink 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!