Implemented basic hardware master i2c support

This commit is contained in:
BlackMark 2019-08-06 21:44:59 +02:00
parent 48012f73c6
commit 183919f905
2 changed files with 128 additions and 0 deletions

93
hardware.hpp Normal file
View File

@ -0,0 +1,93 @@
#pragma once
#include <stdint.h>
#include <util/twi.h>
namespace i2c {
#if defined(__AVR_ATmega1284P__)
enum class Prescaler {
PRESCALER_1 = 0b00,
PRESCALER_4 = 0b01,
PRESCALER_16 = 0b10,
PRESCALER_64 = 0b11,
};
template <Prescaler Pres, uint32_t Clock>
class Hardware {
public:
static void init()
{
TWSR = static_cast<uint8_t>(Pres);
TWBR = calcClock();
}
template <uint8_t Addr>
static bool start(bool read)
{
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)))
;
uint8_t status = TW_STATUS & 0xF8;
if (status != TW_START && status != TW_REP_START)
return false;
TWDR = (Addr << 1) | read;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)))
;
status = TW_STATUS & 0xF8;
if (status != TW_MT_SLA_ACK && status != TW_MR_SLA_ACK)
return false;
return true;
}
static bool write(uint8_t data)
{
TWDR = data;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)))
;
uint8_t status = TW_STATUS & 0xF8;
if (status != TW_MT_DATA_ACK)
return false;
return true;
}
template <bool LastByte = false>
static uint8_t read()
{
TWCR = (1 << TWINT) | (1 << TWEN) | (!LastByte << TWEA);
while (!(TWCR & (1 << TWINT)))
;
return TWDR;
}
static void stop()
{
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
while (TWCR & (1 << TWSTO))
;
}
private:
static constexpr uint8_t calcClock()
{
return ((F_CPU / Clock) - 16) / 2;
}
};
#endif
} // namespace i2c

35
i2c.hpp
View File

@ -1,4 +1,39 @@
#pragma once
#include <stdint.h>
#include "hardware.hpp"
namespace i2c {
template <class Driver>
struct I2c {
static void init()
{
Driver::init();
}
template <uint8_t Addr>
static bool start(bool read)
{
return Driver::template start<Addr>(read);
}
static bool write(uint8_t data)
{
return Driver::write(data);
}
template <bool LastByte = false>
static uint8_t read()
{
return Driver::template read<LastByte>();
}
static void stop()
{
Driver::stop();
}
};
} // namespace i2c