at24c.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036 #include <cfg/os.h>
00037 #include <cfg/memory.h>
00038
00039 #include <sys/timer.h>
00040
00041 #include <stdlib.h>
00042
00043 #include <dev/twif.h>
00044 #include <dev/at24c.h>
00045
00046 #define AT24C_AT91
00047
00048 #define AT24C_DEBUG
00049
00050 #ifdef AT24C_DEBUG
00051 #include <stdio.h>
00052 #endif
00053
00064 static int lld_at24_write( struct at24c *at24cs, uint8_t *buffer, uint32_t len, uint32_t addr)
00065 {
00066 uint8_t retry = at24cs->Timeout;
00067 int tme;
00068
00069 do {
00070 TwMasterRegWrite( at24cs->SlaveAddress, addr, at24cs->IAddrW, buffer, len, 500 );
00071
00072 tme = TwMasterError();
00073 if( tme == TWERR_OK)
00074 return 0;
00075
00076 #ifdef AT24C_DEBUG
00077 printf("MRW %lu: TME:%d t:%d\n", len, tme, TwMasterIndexes( 0));
00078 #endif
00079 if( tme >= TWERR_SLA_NACK) {
00080
00081 --retry;
00082
00083 #ifdef AT24C_DEBUG
00084 printf("RW %u\n", retry);
00085 #else
00086 NutSleep(1);
00087 #endif
00088 }
00089 else {
00090
00091 return -1;
00092 }
00093 }
00094 while( retry);
00095
00096 return -2;
00097 }
00098
00109 static int lld_at24_read( struct at24c *at24cs, uint8_t *buffer, uint32_t len, uint32_t addr)
00110 {
00111 uint8_t retry = at24cs->Timeout;
00112 int tme;
00113
00114 do {
00115 TwMasterRegRead( at24cs->SlaveAddress, addr, at24cs->IAddrW, buffer, len, 500 );
00116 tme = TwMasterError();
00117 #ifdef AT24C_DEBUG
00118 printf("MRD l=%lu: TME %d, mt %u, mr %u\n", len, tme, TwMasterIndexes( 0), TwMasterIndexes(1));
00119 #endif
00120 if( tme == TWERR_OK)
00121 return 0;
00122
00123
00124 if( tme == TWERR_SLA_NACK) {
00125 --retry;
00126 #ifdef AT24C_DEBUG
00127 printf("RR %u\n", retry);
00128 #else
00129 NutSleep(1);
00130 #endif
00131 }
00132 else
00133 return -2;
00134
00135 } while( retry);
00136
00137 return -1;
00138 }
00139
00150
00151 int At24cRead( struct at24c *at24cs, uint8_t *buffer, uint32_t len, uint32_t addr )
00152
00153 {
00154
00155 return lld_at24_read( at24cs, buffer, len, addr);
00156 }
00157
00168
00169 int At24cWrite( struct at24c *at24cs, uint8_t *buffer, uint32_t len, uint32_t addr)
00170
00171 {
00172 int rc = 0;
00173 uint8_t *ptr = buffer;
00174 uint32_t bulk;
00175
00176 while( (len>0) && (rc>=0))
00177 {
00178 bulk = at24cs->PageSize-(addr%at24cs->PageSize);
00179 if( bulk > len) bulk = len;
00180 rc = lld_at24_write( at24cs, ptr, bulk, addr );
00181 ptr+=bulk; addr+=bulk; len-=bulk;
00182 }
00183 return rc;
00184 }
00185