Go Down

Topic: Matlab Arduino serial comminucation (Read 531 times) previous topic - next topic

Sidi

Hello, i need my arduino Mega 2560 to read a value from matlab by serial communication.
I use these codes :

for the arduino IDE

int f;
boolean Communication =1;
 
void setup()
{
  Serial.begin(9600);
  pinMode (11, OUTPUT) ;
  pinMode (12, OUTPUT) ;
  pinMode (5, OUTPUT) ;
  pinMode (2, OUTPUT) ;
  pinMode (6, OUTPUT) ;
  pinMode (7, OUTPUT) ;
  Serial.begin(9600);
 
 if (Serial.available()>0)
  {
  freq = Serial.parseInt() ;
 
    }

}
 
void loop()
{
  if (Communication)
  {
    if (f>=1000)
        {
           float icr=(15989332/(1*f)) ;
           TCCR1A = 0xE2 ; 
           TCCR1B = 0b00011001 ;
           ICR1  = icr ;
           OCR1A = icr/2-1 ; 
           OCR1B = icr/2-1 ;
           TCNT1 = 0x0000 ;
 
           TCCR3A = 0xE2 ; 
           TCCR3B = 0b00011001 ; 
           ICR3  = icr ; 
           OCR3A = icr/2-1 ; 
           OCR3B = icr/2-1 ; 
           TCNT3 = 0x0000 ;

           TCCR4A = 0xE2 ; 
           TCCR4B = 0b00011001 ;
           ICR4  = icr ; 
           OCR4A = icr/2-1 ; 
           OCR4B = icr/2-1 ;
           TCNT4 = 0x0000 ;
   
         }
    else
         {
           float icr=(15989332/(8*f));
           TCCR1A = 0xE2 ; 
           TCCR1B = 0b00011010 ;
           ICR1  = icr ; 
           OCR1A = icr/2-1 ; 
           OCR1B = icr/2-1 ; 
           TCNT1 = 0x0000 ;
 
           TCCR3A = 0xE2 ; 
           TCCR3B = 0b00011010 ; 
           ICR3  = icr; 
           OCR3A = icr/2-1 ; 
           OCR3B = icr/2-1 ; 
           TCNT3 = 0x0000 ;

           TCCR4A = 0xE2 ;
           TCCR4B = 0b00011010 ; 
           ICR4  = icr ; 
           OCR4A = icr/2-1 ;
           OCR4B = icr/2-1 ;
           TCNT4 = 0x0000 ;
        }
        Communication =0 ;
  }

 
}

and for Matlab

clear all
clc
 
freq= 100; % frequency value
arduino=serial('COM8','Baud',9600); % create serial communication object on port COM8
 
fopen(arduino); % initiate arduino communication
fprintf(arduino,freq); % send  variable content to arduino
fclose(arduino); % end communication with arduino


but it doesn't work for me, i mean when i execute the programms, i don't get a PWM signal with the inputted frequency (freq).

i need help.
Thanks.

Robin2

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

Keep in mind that serial data arrives very slowly by Arduino standards even at 500,000 baud.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

Sidi

thank you, this was very helpful. Indeed, i have to consider the time that matlab takes to create the communication with arduion, it's about 1 second for open. Thanks again, i used your function, recvWithEndMarker.

Go Up