0

I am learning Arduino and trying to understand how integers and strings are sent across the serial port. I tried a small program in arduino which reads a number as a string and tries to blink led 13 according to that number. Below is the arduino side of code.

const int ledpin = 13;
int value = 0;
int blinkrate;
void setup()
{
   Serial.begin(9600);
   pinMode(ledpin,OUTPUT);

}

void loop()
{
    if (Serial.available())
      {
         char ch = Serial.read();
         if (isDigit(ch))
            {
               value = (value*10) + (ch - '0');
            }
         else if (ch == 10)
            {
               blinkrate = value;
               Serial.println(blinkrate);
               value = 0;
            }
      }
    blinkled(blinkrate);
}

void blinkled(int blinkrate)
 {
   digitalWrite(ledpin,HIGH);
   delay(blinkrate);
   digitalWrite(ledpin,LOW);
   delay(blinkrate);
 }

When i try to send a string from MATLAB, the RX led blinks once indicating something is coming, but the LED on pin 13 is not behaving accordingly(it should blink according to the number i send). Here is the matlab side of code.

pre_open = instrfindall;
delete(pre_open);
serial_port = serial('COM3');
set(serial_port,'Terminator','CR');
set(serial_port,'BaudRate',9600);
set(serial_port,'DataBits',8);
set(serial_port,'StopBits',1);
set(serial_port,'Parity','none');
fopen(serial_port);
num = 200;
fwrite(serial_port,int2str(num));
data = fscanf(serial_port,'%d');
pause(2);
fclose(serial_port);

When i try to read the return string from arduino, MATLAB shows me a timeout error.

I would be grateful if anybody points me to the right solution. Thank you.

1

Got it, instead of depending on the Serial object, i sent the line feed to arduino. All this time it has been waiting for the Line feed that never arrived.

delete(instrfindall)
s = serial('COM3', 'BaudRate', 9600); %38400
fopen(s);
pause(0.1);
text = input('enter','s');
fprintf(s,'%s\n',text,'sync');
pause(0.1);
d = fscanf(s,'%s');
pause(0.1);
delete(instrfindall)
0

You're setting the terminator to be 'CR'. CR, or Carriage Return, is character 13. In your Arduino program you are looking for character 10. That is 'LF' or Line Feed.

Either are commonly used to denote a line ending, but both ends must agree on which it is.

For instance, Unix files use a single LF for a line ending. Windows files use the combination of both a CR and an LF. Many networking protocols use a single CR for the line ending. It really doesn't matter what is used as long as it is consistent.

  • Thanks for the answer,I also had the same doubt, i tried putting linefeed(LF) in the code, but its not working – the_parzival Nov 6 '15 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.