2

I am trying to get some basic serial communication up and running. My arduino code is shown below.

   void setup()
    {
      Serial.begin(9600);

      Serial.println('a');
      char a = 'b';
      while (a != 'a')
      {
        a = Serial.read();
      }
    }
    void loop()
    {
    }

and my matlab code:

delete(instrfindall);
s = serial('/dev/tty.usbmodem1421');
set(s, 'BaudRate', 9600);
set(s, 'DataBits', 8);
set(s, 'StopBits', 1);
set(s, 'Parity', 'none');
set(s, 'Terminator', 'LF');
fopen(s);

% VERIFY SERIAL COMMUNICATION HAS BEEN SETUP
a = 'b';
while (a~='a')
        a = fread(s,1,'uchar');
end
if (a == 'a')
    disp('Serial read')
end
fprintf(s,'%c','a');
mxbox = msgbox('Serial Communication Initialized'); uiwait(mxbox);

The matlab code executes and I get the message box telling me that it has initialised, however the variable a is not read successfully and the while loop exits prematurely, debugging I found that it actually only loops for one iteration and then continues. 'Serial read' is never displayed.

Any help would be appreciated, thanks in advance.

Note

adding disp(size(a));disp(double(a)); after the fread yielded output 1 0 and no output respectively

1
  • For debugging purposes, could you add disp(size(a));disp(double(a)); after the fread line and append the output to your question? Commented Mar 7, 2015 at 12:36

1 Answer 1

0

It looks like your conditions are a logical negation, but it is not. Both conditions are false for a=[] (or a=['a','b']). Reading nothing could explain the behaviour you observed. Try this code instead:

a = 'b';
while (~strcmpi(a,'a'))
        a = fread(s,1,'uchar');
end
if (strcmpi(a,'a'))
    disp('Serial read')
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply, when I add this code it gets stuck in the while loop, so I am not reading anything. I've also added the output as your previous comment suggested to the end of the question.
@TomPower: I can't give you any hint why it's not receiving anything, but just a comment on what you are doing. There is a Arduino support package (mathworks.com/hardware-support/arduino-matlab.html) for matlab and there is a java interface (arduino.cc/en/Main/Software) which could easily be used in matlab (mathworks.com/help/matlab/using-java-libraries-in-matlab.html). It might be an alternative if you fail to solve this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.