Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List  
Blair

Posts: 2
Registered: 8/20/14
problem using fscanf to continuously read serial data
Posted: Aug 21, 2014 4:08 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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;
}
}



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.