title: C program example for Read and Write to SPI eeprom on linux
body: <p>I am trying to write 4 bytes to spi eeprom on linux and then read 4 bytes (the last is the important one, I'm working with zybo board), I did all for spi eeprom detection and now I have: </p>
  
  <pre><code>/sys/bus/spi/devices/spi32766.0/eeprom
  </code></pre>
  
  <p>In this link: <a href="https://stackoverflow.com/questions/26100105/read-and-write-to-spi-eeprom-on-linux">Read and write to spi eeprom...</a> Klaus says that is possible to do this using eeprom as a character file, but in this link: <a href="https://stackoverflow.com/questions/13807471/how-to-read-data-from-a-serial-spi-connection-in-c">How to read data...</a> Sawdust says that this is no possible because this kind of driver are platform driver.</p>
  
  <p>I tried treating eeprom as a character file in C, but the obtained data are incoherent (I did a test in bare-metal code and the SPI device works), maybe because I don't know how data has to be send, Could somebody explain me with a piece of code, how should I read/write to SPI EEPROM?.</p>
  
  <p>Thanks a lot :)</p>
  
  <p>A summary of my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  
  int readData(FILE* fp);
  
  int main(int argc, char *argv[]) {
      FILE* fp;
      char ch = 'a';
      while (1) {
          fp = fopen("/sys/bus/spi/devices/spi32766.0/eeprom", "r+");
          if (fp == NULL) {
              printf("Cannot open /sys/bus/spi/devices/spi32766.0/eeprom for write\n");
              return -1;
          }
          printf("Sending data\n");
          fputs("\x01\x02\x03\x04", fp);//or fputs(four bytes, fp) 
          while (readData(fp) == 0) {
              sleep(1);
          }
          printf("End\n");
          fclose(fp);
          sleep(5);
      }
      return EXIT_SUCCESS;
  }
  
  int readData(FILE* fp) {
      int c = fgetc(fp);
      int retorno = (feof(fp) == NULL);
      printf("Char: %c\n", c);
      printf("Int: %d\n", c);
      return retorno;
  }
  </code></pre>