EEPROM_STM_Arduino 0.9.0
EEPROM:M24C02 class driver
Loading...
Searching...
No Matches
M24C02.cpp
Go to the documentation of this file.
1#include <M24C02.h>
2
3M24C02::M24C02( uint8_t i2c_address ) : I2C_device( i2c_address )
4{
5}
6
7M24C02::M24C02( TwoWire& wire, uint8_t i2c_address ) : I2C_device( wire, i2c_address )
8{
9}
10
14
15void M24C02::begin( void )
16{
17}
18
19int M24C02::write( int byte_adr, uint8_t data )
20{
21 if ( !wait_write_complete( 10 ) )
22 return -10;
23
24 int r = reg_w( byte_adr, data );
25
26 if ( !wait_write_complete( 10 ) )
27 return -10;
28
29 return r;
30}
31
32int M24C02::write( int byte_adr, const uint8_t *dp, int length )
33{
34 int w_size;
35 int written = 0;
36
37 if ( (byte_adr % PAGE_WRITE_SIZE) && !within_a_page( byte_adr, length ) )
38 {
39 uint8_t data[ PAGE_WRITE_SIZE ];
40 int start = (byte_adr / PAGE_WRITE_SIZE) * PAGE_WRITE_SIZE;
41 int offset = byte_adr % PAGE_WRITE_SIZE;
42 int w_size = PAGE_WRITE_SIZE - offset;
43
44 read( start, data, PAGE_WRITE_SIZE );
45 memcpy( data + offset, dp, w_size );
46
47 if ( !wait_write_complete( 10 ) )
48 return -10;
49
50 reg_w( start, data, PAGE_WRITE_SIZE );
51
52 length -= w_size;
53 written += w_size;
54 byte_adr += w_size;
55 dp += w_size;
56 }
57
58 while ( length ) {
59 w_size = ( PAGE_WRITE_SIZE < length ) ? PAGE_WRITE_SIZE : length;
60
61 if ( !wait_write_complete( 10 ) )
62 return -10;
63
64 w_size = reg_w( byte_adr, dp, w_size ) - 1;
65
66 if ( w_size < 0 )
67 return w_size;
68
69 length -= w_size;
70 written += w_size;
71 byte_adr += w_size;
72 dp += w_size;
73 }
74
75 if ( !wait_write_complete( 10 ) )
76 return -10;
77
78 return written;
79}
80
82{
83 while ( !ping() && n-- )
84 delay( 1 );
85
86 if ( !n )
87 Serial.println("time out in M24C02::wait_write_complete()");
88
89 return n;
90}
91
92uint8_t M24C02::read( int byte_adr )
93{
94 return reg_r( byte_adr );
95}
96
97int M24C02::read( int byte_adr, uint8_t *dp, int length )
98{
99 int r_size;
100 int read_done = 0;
101
102 while ( length ) {
103 r_size = ( PAGE_READ_SIZE < length ) ? PAGE_READ_SIZE : length;
104
105 r_size = reg_r( byte_adr, dp, r_size );
106
107 length -= r_size;
108 read_done += r_size;
109 byte_adr += r_size;
110 dp += r_size;
111 }
112
113 return read_done;
114}
int wait_write_complete(int n)
Definition M24C02.cpp:81
uint8_t read(int byte_adr)
Definition M24C02.cpp:92
int within_a_page(int byte_adr, int length)
Definition M24C02.h:90
static constexpr int PAGE_WRITE_SIZE
Definition M24C02.h:87
void begin(void)
Definition M24C02.cpp:15
static constexpr int PAGE_READ_SIZE
Definition M24C02.h:88
virtual ~M24C02()
Definition M24C02.cpp:11
M24C02(uint8_t i2c_address=(0xA0 > > 1))
Definition M24C02.cpp:3
int write(int byte_adr, uint8_t data)
Definition M24C02.cpp:19