I want to transmit data from MatLab to the arduino. I am troubleshooting using a code for the arduino from another thread as follows:
int pLED = 7;
int val= 0;
char inData[10];
int index;
boolean started = false;
boolean ended = false;
void setup()
{
Serial.begin(9600);
pinMode(pLED, OUTPUT);
}
void loop()
{
}
void serialEvent()
{
while(Serial.available())
{
char aChar = Serial.read();
if(aChar == '<')
{
started = true;
index = 0;
inData[index] = '\0';
}
else if(aChar == '>')
{
ended = true;
}
else if(started)
{
inData[index] = aChar;
index++;
inData[index] = '\0';
}
}
if(started && ended)
{
// Convert the string to an integer
int inInt = atoi(inData);
// Use the value
// Get ready for the next time
started = false;
ended = false;
index = 0;
inData[index] = '\0';
for (int i=0; i<inInt; i++)
{
digitalWrite(pLED, HIGH);
delay(100);
digitalWrite(pLED, LOW);
delay(100);
}
}
}
My MatLab code is
%% ARDUINO INTERFACING
% Connect to Arduino the specified port
Port = '/dev/tty.usbmodem1421';
BaudRate = 9600;
DataBits = 8;
% Create the serial connection and open communication with the Arduino.
ser = serial(Port);
set(ser, 'BaudRate', BaudRate);
set(ser, 'DataBits', DataBits);
pause(0.02);
fopen(ser);
pause(0.5);
pause(0.02);
value = 10;
fprintf(ser, '>');
fprintf(ser, '6');
fprintf(ser, '<');
pause(0.02);
fclose(ser);
delete(ser);
clear ser;
delete(instrfindall);
This will only work after opening the serial monitor in the arduino window. If it hasn't been opened, the RX light on the arduino will flash but my output LED doesn't flash. Once the serial monitor has been opened it will work once, but afterwards throws up an error that the serial port is being used by another application. I am assuming there is some sort of initialising issue that opening the serial monitor in the arduino fixes?
Thanks in advance