Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: problem using fscanf to continuously read serial data
Replies: 0

 Blair Posts: 4 Registered: 8/20/14
problem using fscanf to continuously read serial data
Posted: Aug 21, 2014 4:08 PM

I am using Matlab and programming an Arduino that communicates back and forth with Matlab by sending serial data via USB back and forth. Basic idea is:

1. Send a character, say "K" from the Arduino to Matlab every 1s.
2. Matlab is continuously reading via fscanf. When it finds a "K" it sends 2 bytes over to the Arduino.
3. Arduino reads the bytes, activates LEDs on shift registers, waits out the rest of the second, and then sends the next "K," etc. until it runs through the whole Asum matrix.

I am successful in sending bytes from Matlab to Arduino, BUT I cannot get the "K" to consistently be read by Matlab. It seems that fscanf is either too slow or randomly gets or doesn't get the value, can't figure out why. It will scan for ages and find nothing, even though Arduino is sending "K" every second!! Have been at this for weeks with extremely limited success, so any help would be appreciated!!!

Simplified versions of my code below:

Matlab:

s = serial('/dev/tty.usbmodem411','BaudRate',19200)
fopen(s)
kk=10; %length of Asum; Asum is previously defined as matrix of bytes...
timestep = 0;

while timestep < kk
rx = fscanf(s, '%s', 1) <------------- IMPORTANT
if rx == 'K'
fprintf('hooray!')
timestep = timestep + 1;
fprintf(s,'%d,',Asum(timestep,1));
fprintf(s,'%d ',Asum(timestep,2));
end
end

%%%%%%%%%%%%%%%%%%%%%

relevant parts of Arduino script:
void setup()
{
Serial.begin(19200);
delay(1000);
}

int seq1;
int seq2;

int timeElapsed = 2000;
int timeOld = 0;
int interval = 1000;

void loop()
{
if (timeElapsed > interval)
{
timeOld = millis();
Serial.flush();
Serial.println("K"); <------------- IMPORTANT
delay(30);

if (Serial.available() > 0)
{
int seq1 = Serial.parseInt();
Serial.println(seq1);
int seq2 = Serial.parseInt();
Serial.println(seq2);

digitalWrite(latchPin, HIGH);
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, seq1);
shiftOut(dataPin, clockPin, MSBFIRST, seq2);
//digitalWrite(latchPin, HIGH);
}

timeElapsed = millis() - timeOld;
}
else if (timeElapsed <=interval)
{
delay(5);
timeElapsed = millis() - timeOld;
}
}