Go Down

Topic: Communication between Arduino and Matlab (Read 80 times) previous topic - next topic

alaj

Hi !
I want to send a value from Matlab to Arduino.
I succeed it but when I want to test my value on Arduino, this is not the good one. (Always 0).
Someone can help me?

Matlab code :


Code: [Select]
clear all;
close all;
clc;


comPort = '/dev/cu.usbmodem1421';
flag=1;
current='l';
s= serial(comPort);
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate',9600);
set(s,'Parity','none');
fopen(s); %connecte ‡ arduino

%% Matlab is waiting a char of Arduino
a='b';
while (a~='a')
    a=fread(s,1,'uchar');
end

%% After it finds the char, it sends a char at Aduino and display 'serial read'
if(a=='a')
    fprintf(s,'%c','a');
    display('serial read');
end
fwrite(s,'r1x');
l=fgets(s);
display(l);


Arduino code :

Code: [Select]

#define LED 4
#define LED2 6
float num;
void setup() {
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  pinMode(LED2, OUTPUT);
  Serial.print('a');
  char a='b';
  while(a!='a')
  {
    a=Serial.read();
  }

 

  char test = Serial.read();
  if (test == 'r');
  {

     float num = Serial.parseFloat();
     Serial.println(num);
     
  }


}

void loop() {

if ((float)num == 1)
{
  digitalWrite(LED,1);
  digitalWrite(LED2,0);
}
else
{
  digitalWrite(LED,0);
  digitalWrite(LED2,1);
}
}[\code]

horace

#1
Jul 07, 2017, 06:55 pm Last Edit: Jul 07, 2017, 08:32 pm by horace
in the statement
Code: [Select]
fwrite(s,'r1x');
the Arduino receives the 'r' then attempts to parse '1x' as a float?

if I run your Matlab code I get
Code: [Select]

ans =
serial read
l =
1.00
>>

the Arduino parses the '1' and stops parsing at 'x' ?



Go Up