YAHAL
Yet Another Hardware Abstraction Library
Loading...
Searching...
No Matches
soft_i2c_slave.cpp
1// ---------------------------------------------
2// This file is part of
3// _ _ __ _ _ __ __
4// ( \/ ) /__\ ( )_( ) /__\ ( )
5// \ / /(__)\ ) _ ( /(__)\ )(__
6// (__)(__)(__)(_) (_)(__)(__)(____)
7//
8// Yet Another HW Abstraction Library
9// Copyright (C) Andreas Terstegge
10// BSD Licensed (see file LICENSE)
11//
12// ---------------------------------------------
13//
14
15#include "soft_i2c_slave.h"
16
17soft_i2c_slave::soft_i2c_slave(gpio_interface & sda, gpio_interface & scl,
18 bool pullup)
19 : _sda(sda), _scl(scl), _init(false), _pullup(pullup),
20 _i2c_address(0),
21 _state (nullptr),
22 _idle (*this), _read_addr (*this), _write_ack (*this),
23 _read_data (*this), _write_data(*this), _read_ack (*this)
24{
25 // Set start state
26 setState(&_idle);
27}
28
29soft_i2c_slave::~soft_i2c_slave() {
30 // Check if we need to de-configure
31 if (!_init) return;
32 _sda.gpioMode(GPIO::INPUT);
33 _scl.gpioMode(GPIO::INPUT);
34 _sda.gpioDetachIrq();
35 _scl.gpioDetachIrq();
36}
37
38void soft_i2c_slave::set_callbacks(
39 std::function<bool(uint16_t index, uint8_t data)> receive,
40 std::function<uint8_t(uint16_t index)> transmit,
41 std::function<void()> stop) {
42 _receive = receive;
43 _transmit = transmit;
44 _stop = stop;
45}
46
47void soft_i2c_slave::init() {
48 uint16_t mode = GPIO::INPUT |
49 GPIO::OUTPUT_OPEN_DRAIN |
50 GPIO::INIT_HIGH;
51 if (_pullup) {
52 mode |= GPIO::PULLUP;
53 }
54 _sda.gpioMode(mode);
55 _scl.gpioMode(mode);
56
57 // The event-generating interrupt handlers //
58 _sda.gpioAttachIrq(GPIO::FALLING | GPIO::RISING, [this]() {
59 // SDA interrupt handler
60 if (!_scl.gpioRead()) return;
61 _sda.gpioRead() ? _state->stop() : _state->start();
62 });
63
64 _scl.gpioAttachIrq(GPIO::FALLING | GPIO::RISING, [this]() {
65 // SCL interrupt handler
66 if (_scl.gpioRead()) {
67 _sda.gpioRead() ? _state->high() : _state->low();
68 } else {
69 _state->scl_falling();
70 }
71 });
72 _init = true;
73}
74