AnsweredAssumed Answered

fwrite, fread behavior in i2c communication

Question asked by Florian Engeler on Mar 30, 2011
Latest reply on Apr 1, 2011 by Petr MacHala

Hi there,

 

I got a question considering the usage of I/O drivers functions fwrite() and fread(). Specifically in the context of the i2c device. I considered the file "eeprom_int.h" in the mqx 3.6.2 example project  i2c_mcf52277evb.mcp.

 

Why are fwrite and fread calls implemented in a while loop?

Examples are:

 

/* Write address within memory block */
      mem = addr & 0xFF;
      printf ("  Write to address 0x%02x ... ", mem);
      do
      {
         result = fwrite (&mem, 1, 1, fd);
      } while (result < 1);
      if (1 == result)
      {
         printf ("OK\n");
      } else {
         printf ("ERROR\n");
      }

 


      /* Page write of data */
      printf ("  Page write %d bytes ... ", length);
      result = 0;
      do
      {
         result += fwrite (buffer + result, 1, length - result, fd);
      } while (result < length);
      if (result == length)
      {
         printf ("OK\n");
      } else {
         printf ("ERROR\n");
      }

 

 

/* Read all data */
   printf ("  Read %d bytes ... ", n);
   result = 0;
   do
   {
      result += fread (buffer + result, 1, n - result, fd);
   } while (result < n);
   if (result == n)
   {
      printf ("OK\n");
   } else {
      printf ("ERROR\n");
   }

 

Is there any chance fwrite and fread functions return a non-negative value different from the specified amount of bytes to write/read? And in this case, there will be multiple fread/fwrite calls in a while clause?

Supposing there are multiple calls, isn't the starting address for the write/read operations becoming a problem? Or is this address adjusted automatically?

 

In the general c++  function description of fwrite it says that a return value different from the specified amount indicates an error. For fread, it might also be that the end of file was reached. Therefore i do not see the purpose of the while loops in the example.

 

Would be great if somebody could clarify this for me!

 

Best,

Florian

Outcomes