Hi guys, i am newbie in the arduino and this is my first time of using Arduino Board.
I would like to send an array from MATLAB to arduino. I successfully send an integer to the arduino but i failed to send the array. The following is my source code.
clear all
clc
MATLAB code
arduino=serial('COM7','BaudRate',9600); % create serial communication object on port COM7
fopen(arduino); % initiate arduino communication
answer=[0,1,2,3,4,5,6,7];
%fprintf(arduino,answer);
for f=1:8
fprintf(arduino,answer(1,f)); % send answer variable content to arduino
pause(1)
end
fclose(arduino); % end communication with arduino
Arduino Code
int ledPin=13;
int matlabData[8]={0,0,0,0,0,0,0,0};
void loop()
{
if(Serial.available()>0) // store the MATLAB data into the array
{
for (int i=0; i<8; i++)
{
matlabData*=Serial.read(); // read data* }
if (matlabData[4]==4)*
{* digitalWrite(ledPin,HIGH);
delay(1000);*
}* else{
digitalWrite(ledPin,LOW);*
}* } } Based on the Arduino code, the LED pin should light up when the matlabData[4]==4, however it does not light up, do anyone knows how to solve this problem?
Your incorrectly posted and poorly formatted code won't compile. You are missing an indexer to increment through the array as it is read.
for (int i=0; i<8; i++)
{
matlabData[i]=Serial.read(); // See where the array indexer goes?
}
Properly posted code. Read the "how to use the forum" stickies.
int ledPin=13;
int matlabData[8]={
0,0,0,0,0,0,0,0};
void setup()
{
pinMode(ledPin,OUTPUT);
Serial.begin(9600);
}
void loop()
{
if(Serial.available()>0) // store the MATLAB data into the array
{
for (int i=0; i<8; i++)
{
matlabData[i]=Serial.read(); // read data
}
if (matlabData[4]==4)
{
digitalWrite(ledPin,HIGH);
delay(1000);
}
else
{
digitalWrite(ledPin,LOW);
}
}
}
The index is missing because the code isn't in code tags and the [i] was interpreted as a tag which starts italic text.
@ cwhen4. This is why you need to read How to post code properly then edit your original post and put your code in code tags.
May i know what should i do in order to read 8 integers in array?
If you know that you need to do nothing until there is at least one byte to read, is it really that difficult to see that you should really do nothing until there is at least eight bytes?
if(Serial.available() >= 8) // useless comment removed because it was wrong
{
for (int i=0; i<8; i++)
{
matlabData[ i ]=Serial.read(); // read data
}