COSA
An Object-Oriented Platform for Arduino Programming
AT24CXX.cpp
Go to the documentation of this file.
1 
21 #include "AT24CXX.hh"
22 #include "Cosa/Power.hh"
23 
24 bool
25 AT24CXX::poll(const void* addr, const void* buf, size_t size)
26 {
27  uint8_t i = POLL_MAX;
28  int m;
29  do {
30  twi.acquire(this);
31  if (buf == 0) {
32  m = twi.write((uint16_t) addr);
33  if (m > 0) return (true);
34  twi.release();
35  }
36  else {
37  m = twi.write((uint16_t) addr, (void*) buf, size);
38  twi.release();
39  if (m > 0) return (true);
40  }
41  delay(16);
42  } while (--i);
43  return (false);
44 }
45 
46 bool
48 {
49  twi.acquire(this);
50  uint16_t addr = 0;
51  int m = twi.write(addr);
52  twi.release();
53  return (m != 0);
54 }
55 
56 int
57 AT24CXX::read(void* dest, const void* src, size_t size)
58 {
59  if (!poll(src)) return (EIO);
60  int n = twi.read(dest, size);
61  twi.release();
62  return (n);
63 }
64 
65 int
66 AT24CXX::write(void* dest, const void* src, size_t size)
67 {
68  size_t s = size;
69  uint8_t* q = (uint8_t*) dest;
70  uint8_t* p = (uint8_t*) src;
71  size_t n = WRITE_MAX - (((uint16_t) dest) & WRITE_MASK);
72  if (n > s) n = s;
73  if (!poll(q, p, n)) return (EIO);
74  s -= n;
75  while (s > 0) {
76  q += n;
77  p += n;
78  n = (s < WRITE_MAX ? s : WRITE_MAX);
79  if (!poll(q, p, n)) return (EIO);
80  s -= n;
81  }
82  return (size);
83 }
84 
#define EIO
Definition: Errno.h:32
TWI twi
Definition: TWI.cpp:27
virtual bool is_ready()
Definition: AT24CXX.cpp:47
void release()
Definition: TWI.cpp:58
void(* delay)(uint32_t ms)
int read(void *buf, size_t size)
Definition: TWI.hh:326
int write(void *buf, size_t size)
Definition: TWI.hh:282
virtual int write(void *dest, const void *src, size_t size)
Definition: AT24CXX.cpp:66
void acquire(TWI::Driver *dev)
Definition: TWI.cpp:36
virtual int read(void *dest, const void *src, size_t size)
Definition: AT24CXX.cpp:57