/**
- @file Rath_I2C.h
- @date 2021-10-25
- @copyright Copyright (c) 2021
- This is a library for the I2C peripheral.
*/
pragma once
include "Rath_core.h"
include "Wire.h"
namespace Rath {
class I2C {
public:
void init() {
Wire.begin();
}
void masterReceive(uint16_t device_addr, uint8_t *buffer, uint16_t size, uint32_t timeout) {
Wire.requestFrom((int)device_addr, size);
while (Wire.available() < size) {}
for (int i=0; i<size; i+=1) {
buffer[i] = Wire.read();
}
//twi_readFrom(device_addr, buffer, size, 1);
}
void masterTransmit(uint16_t device_addr, uint8_t *buffer, uint16_t size, uint32_t timeout) {
Wire.beginTransmission((int)device_addr);
for (int i=0; i<size; i+=1) {
Wire.write(buffer[i]);
}
Wire.endTransmission();
//twi_writeTo(device_addr, buffer, size, 1, 1);
}
void readMemory(uint16_t device_addr, uint8_t mem_addr, uint8_t *buffer, uint16_t size, uint32_t timeout) {
masterTransmit(device_addr, &mem_addr, 1, timeout);
masterReceive(device_addr, buffer, size, timeout);
}
void writeMemory(uint16_t device_addr, uint8_t mem_addr, uint8_t *buffer, uint16_t size, uint32_t timeout) {
uint8_t buf[size+1];
buf[0] = mem_addr;
for (int i=0; i<size; i+=1) {
buf[i+1] = buffer[i];
}
masterTransmit(device_addr, buf, size + 1, timeout);
}
};
};