The Math Forum

Search All of the Math Forum:

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

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

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  

Advanced Search

Back to Topic List Back to Topic List  

Posts: 4
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:


s = serial('/dev/tty.usbmodem411','BaudRate',19200)
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'
timestep = timestep + 1;
fprintf(s,'%d ',Asum(timestep,2));


relevant parts of Arduino script:
void setup()

int seq1;
int seq2;

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

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

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

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)
timeElapsed = millis() - timeOld;

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

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.