Subversion Repositories group.electronics

Rev

Rev 128 | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include <avr/io.h>
#include <stdlib.h>
#include "wire.h"
#include "avrutil.h"
#include <util/delay.h>

#include "e2p.h"

void e2p_init() {
  e2p.i2c_addr = 0x50;
}

void e2p_init_addr(uint8_t i2c_addr) {
  e2p.i2c_addr = i2c_addr;
}

uint8_t e2p_readByte(uint16_t address) {
  if (!e2p.i2c_addr) return 0xFF;
  
  uint8_t buffer = 0xFF;
  e2p_readBytes(address, &buffer, 1);
  return buffer;
}

uint8_t e2p_busy() {
  i2c_beginTransmission(e2p.i2c_addr);
  return i2c_endTransmission(1);
}

void e2p_flush() {
 while (e2p_busy()) {
    _delay_us(500);
 }
}

void e2p_readBytes(uint16_t address, uint8_t* buffer, uint8_t length) {
  if (!e2p.i2c_addr) return;
         
  i2c_beginTransmission(e2p.i2c_addr);
  i2c_writeByte((int) address >> 8);    // MSB
  i2c_writeByte((int) address & 0xFF);  // LSB
  i2c_endTransmission(0);

  
  i2c_requestFrom(e2p.i2c_addr, length, 1);
  uint8_t c;
  for ( c = 0; c < length; c++)
    if (i2c_available()) buffer[c] = i2c_read();
}

void e2p_writeByte(uint16_t address, uint8_t data) {
    if (!e2p.i2c_addr) return;
  
    i2c_beginTransmission(e2p.i2c_addr);
    i2c_writeByte((int) address >> 8);  // MSB
    i2c_writeByte((int) address & 0xFF);        // LSB
    i2c_writeByte(data);
    i2c_endTransmission(1);
}

void e2p_writeBytes(uint16_t address, uint8_t* data, uint8_t length) {
    if (!e2p.i2c_addr) return;
  
    i2c_beginTransmission(e2p.i2c_addr);
    i2c_writeByte((int) address >> 8);  // MSB
    i2c_writeByte((int) address & 0xFF);        // LSB
    uint8_t c;
    for ( c = 0; c < length; c++)
      i2c_writeByte(data[c]);
    i2c_endTransmission(1);  
}