Using the read() function from Ethernet library

Hi all,

I just discovered Arduino and it really looks great !
I also have a ethernet shield to communicate with my PC.
In my little project, I am trying to send requests with a particular TCP frame.
I use a FSM and the read() function.

My problem is that when I receive data, I want to be able to count the number of bytes read.
Within a state, I tried :

while (i < length) {
  data[i] = client.read();
  i++;
}
// go back to initialization state
if (i == length) {
  i = 0;
  fsm_state = 0;
}

I used print function to debug it but I have the impression that this state is skipped. I guess it is because the read() function doesn't block the process. Thus, if there is nothing to read, the variable i is incremented and then my FSM goes back to the init state.
Hence my question : is there a trick to block the process until my FSM reads something ?

Cheers

Hence my question : is there a trick to block the process until my FSM reads something ?

The code snippet you posted is not sufficient to answer your question. Typically, one does not try to read unless one knows that the read will be successful. Thus, read() should not block.

The read() function should return a -1 if there was nothing to read, so you can make your own blocking function. Keep reading in a while loop, until read() returns other than -1.

However, there should be an available() method that goes with the read() method that tells you whether there is data to be read (as in how much data, not true/false).

From the snippet, we can not tell what the client object is, though one might reasonably assume that the object is an instance of the Client class, in which case the above comments DO apply. If it is not, then the above comments might not apply.

Thanks for the quick answer.
My code looks like that :

void loop() {
  Client client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        switch (fsm_state) {
        …
        case 4: // read data
          while (i < length) {
            data[i] = client.read();
            server.write(data[i]);
            i++;
          }
          if (i == length) {
            i = 0;
            fsm_state++;
            server.write(63);
          }
          break;
        …
        }
      }
    }
  }
}

In case 4, how is length defined?

You can easily use client.available() with while to create a do-nothing-until-there-is-data-to-read pause.

while(client.available() == 0) { // Do nothing }

Put that in the while(i < length) loop, before the client.read() call, and you will know that the read() call WILL get data, when it gets called.

length is defined with a client.read() (each state of the FSM is associated to a byte read).
Thanks for the trick, it seems to work !