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.