2024-03-16 19:00:23 +00:00
|
|
|
//
|
|
|
|
// I2C.hpp
|
|
|
|
// Clock Signal
|
|
|
|
//
|
|
|
|
// Created by Thomas Harte on 16/03/2024.
|
|
|
|
// Copyright © 2024 Thomas Harte. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2024-03-17 02:02:16 +00:00
|
|
|
#include <cstdint>
|
2024-03-26 16:24:24 +00:00
|
|
|
#include <optional>
|
2024-03-16 19:00:23 +00:00
|
|
|
#include <unordered_map>
|
|
|
|
|
|
|
|
namespace I2C {
|
|
|
|
|
|
|
|
/// Provides the virtual interface for an I2C peripheral; attaching this to a bus
|
|
|
|
/// provides automatic protocol handling.
|
2024-03-26 16:24:24 +00:00
|
|
|
struct Peripheral {
|
|
|
|
virtual void start([[maybe_unused]] bool is_read) {}
|
|
|
|
virtual void stop() {}
|
|
|
|
virtual std::optional<uint8_t> read() { return std::nullopt; }
|
|
|
|
virtual void write(uint8_t) {}
|
2024-03-16 19:00:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
class Bus {
|
|
|
|
public:
|
|
|
|
void set_data(bool pulled);
|
|
|
|
bool data();
|
|
|
|
|
|
|
|
void set_clock(bool pulled);
|
|
|
|
bool clock();
|
|
|
|
|
|
|
|
void set_clock_data(bool clock_pulled, bool data_pulled);
|
|
|
|
|
|
|
|
void add_peripheral(Peripheral *, int address);
|
|
|
|
|
|
|
|
private:
|
|
|
|
bool data_ = false;
|
|
|
|
bool clock_ = false;
|
|
|
|
std::unordered_map<int, Peripheral *> peripherals_;
|
2024-03-17 02:02:16 +00:00
|
|
|
|
|
|
|
uint16_t input_ = 0xffff;
|
|
|
|
int input_count_ = -1;
|
|
|
|
|
|
|
|
Peripheral *active_peripheral_ = nullptr;
|
2024-03-18 01:55:19 +00:00
|
|
|
uint16_t peripheral_response_ = 0xffff;
|
|
|
|
int peripheral_bits_ = 0;
|
2024-03-17 02:02:16 +00:00
|
|
|
|
2024-03-26 02:10:52 +00:00
|
|
|
enum class Event {
|
|
|
|
Zero, One, Start, Stop,
|
|
|
|
};
|
|
|
|
void signal(Event);
|
|
|
|
|
2024-03-26 16:24:24 +00:00
|
|
|
enum class State {
|
|
|
|
AwaitingAddress,
|
2024-03-18 01:55:19 +00:00
|
|
|
CollectingAddress,
|
2024-03-26 16:24:24 +00:00
|
|
|
|
|
|
|
PostingByte,
|
|
|
|
ReceivingByte,
|
|
|
|
} state_ = State::AwaitingAddress;
|
2024-03-16 19:00:23 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
}
|