tahamajs's picture
download
raw
2.41 kB
#ifndef I2CPROTOCOL_H
#define I2CPROTOCOL_H
#include <CPS4042/Protocols/Protocol.h>
#include <CPS4042/Wires/Pin.h>
#include <iostream>
#include <vector>
namespace Protocols {
template <typename BoardType>
class I2CProtocol : public AbstractI2C<BoardType, typename BoardType::Gpio> {
public:
using Gpio = typename BoardType::Gpio;
using Base = AbstractI2C<BoardType, Gpio>;
explicit I2CProtocol(BoardType* board)
: Base(board) {} // pass board to base
void init(Byte) override {} // master ignores address
void write(Byte data) override {
Base::m_board->gpio().sda.write(data);
}
Byte read() override {
if (Base::m_buffer.empty()) return Byte{0x00};
Byte b = Base::m_buffer.front();
Base::m_buffer.pop();
return b;
}
void startReadTransaction(uint8_t slaveAddress) {
m_state = State::SEND_ADDRESS;
m_slaveAddr = slaveAddress;
m_bytesToRead = 3;
m_receivedBytes.clear();
}
void run(Gpio& gpio) override {
switch (m_state) {
case State::IDLE: break;
case State::SEND_ADDRESS: {
uint8_t addrByte = (m_slaveAddr << 1) | 1;
gpio.sda.write(Byte(addrByte));
m_state = State::WAIT_ACK;
break;
}
case State::WAIT_ACK:
if (gpio.sda.hasData()) {
Byte ack = gpio.sda.read();
if (static_cast<uint8_t>(ack) == 0x00)
m_state = State::READ_DATA;
else {
std::cerr << "[I2C Master] NACK\n";
m_state = State::IDLE;
}
}
break;
case State::READ_DATA:
if (gpio.sda.hasData()) {
Byte b = gpio.sda.read();
m_receivedBytes.push_back(b);
if (m_receivedBytes.size() == m_bytesToRead) {
for (auto& byte : m_receivedBytes)
Base::m_buffer.push(byte);
m_state = State::IDLE;
}
}
break;
}
}
private:
enum class State { IDLE, SEND_ADDRESS, WAIT_ACK, READ_DATA };
State m_state = State::IDLE;
uint8_t m_slaveAddr = 0x29;
size_t m_bytesToRead = 3;
std::vector<Byte> m_receivedBytes;
};
} // namespace Protocols
#endif

Xet Storage Details

Size:
2.41 kB
·
Xet hash:
ce284095885b51b471919d0c8ec39adbbc0f3e03cc2f89b8a8bdcbedf2db38b5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.