Skip to content

Commit 7bc83af

Browse files
committed
esp32/machine_i2c_target: Implement I2CTarget class.
Only soft IRQs are supported. Signed-off-by: Damien George <[email protected]>
1 parent ac5b1bc commit 7bc83af

File tree

4 files changed

+238
-0
lines changed

4 files changed

+238
-0
lines changed

ports/esp32/boards/sdkconfig.base

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,7 @@ CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=n
139139
# Further limit total sockets in TIME-WAIT when there are many short-lived
140140
# connections.
141141
CONFIG_LWIP_MAX_ACTIVE_TCP=12
142+
143+
# Enable new I2C slave API, and disable conflict check.
144+
CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK=y
145+
CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2=y

ports/esp32/machine_i2c_target.c

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
/*
2+
* This file is part of the MicroPython project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* Copyright (c) 2025 Damien P. George
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
// This file is never compiled standalone, it's included directly from
28+
// extmod/machine_i2c_target.c via MICROPY_PY_MACHINE_I2C_TARGET_INCLUDEFILE.
29+
30+
#include "machine_i2c.h"
31+
#include "driver/i2c_slave.h"
32+
33+
// These headers are needed to call i2c_ll_txfifo_rst().
34+
#include "hal/i2c_ll.h"
35+
#include "../i2c_private.h"
36+
37+
typedef struct _machine_i2c_target_obj_t {
38+
mp_obj_base_t base;
39+
i2c_slave_dev_handle_t handle;
40+
i2c_slave_config_t config;
41+
uint8_t state;
42+
bool stop_pending;
43+
bool irq_active;
44+
int index;
45+
const i2c_slave_rx_done_event_data_t *rx_done_event_data;
46+
} machine_i2c_target_obj_t;
47+
48+
static machine_i2c_target_obj_t machine_i2c_target_obj[I2C_NUM_MAX];
49+
50+
/******************************************************************************/
51+
// ESP-IDF hardware bindings
52+
53+
// Called when the controller is about to read from the TX/send buffer.
54+
static bool i2c_slave_request_cb(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_request_event_data_t *evt_data, void *arg) {
55+
machine_i2c_target_obj_t *self = arg;
56+
machine_i2c_target_data_t *data = &machine_i2c_target_data[self->config.i2c_port];
57+
58+
// Flush hardware TX FIFO to get rid of any data from a previous read.
59+
i2c_ll_txfifo_rst(self->handle->base->hal.dev);
60+
61+
// Perform an entire read transaction, including start, read and stop events.
62+
// We don't know how much data the controller will read, so write the entire
63+
// memory buffer to the TX FIFO.
64+
machine_i2c_target_data_addr_match(data, true);
65+
for (uint32_t i = 0; i < data->mem_len; ++i) {
66+
machine_i2c_target_data_read_request(self, data);
67+
}
68+
machine_i2c_target_data_restart_or_stop(data);
69+
70+
// A higher priority task was not woken up.
71+
return false;
72+
}
73+
74+
// Called when the controller has written into the RX/receive buffer.
75+
static bool i2c_slave_receive_cb(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_rx_done_event_data_t *evt_data, void *arg) {
76+
machine_i2c_target_obj_t *self = arg;
77+
machine_i2c_target_data_t *data = &machine_i2c_target_data[self->config.i2c_port];
78+
79+
// Perform an entire write transaction, including start, read and stop events.
80+
machine_i2c_target_data_addr_match(data, false);
81+
self->index = 0;
82+
self->rx_done_event_data = evt_data;
83+
while (self->index < self->rx_done_event_data->length) {
84+
machine_i2c_target_data_write_request(self, data);
85+
}
86+
machine_i2c_target_data_restart_or_stop(data);
87+
88+
// A higher priority task was not woken up.
89+
return false;
90+
}
91+
92+
static void i2c_target_init(machine_i2c_target_obj_t *self, machine_i2c_target_data_t *data, uint32_t addr, uint32_t addrsize, bool first_init) {
93+
if (!first_init && self->handle != NULL) {
94+
i2c_del_slave_device(self->handle);
95+
self->handle = NULL;
96+
}
97+
98+
self->config.clk_source = I2C_CLK_SRC_DEFAULT;
99+
self->config.slave_addr = addr;
100+
self->config.send_buf_depth = data->mem_len;
101+
self->config.receive_buf_depth = data->mem_len;
102+
if (addrsize == 7) {
103+
self->config.addr_bit_len = I2C_ADDR_BIT_LEN_7;
104+
} else {
105+
#if SOC_I2C_SUPPORT_10BIT_ADDR
106+
self->config.addr_bit_len = I2C_ADDR_BIT_LEN_10;
107+
#else
108+
mp_raise_ValueError(MP_ERROR_TEXT("10-bit address unsupported"));
109+
#endif
110+
}
111+
self->config.intr_priority = 0; // 0 selects the default
112+
self->config.flags.allow_pd = 0;
113+
self->config.flags.enable_internal_pullup = 1;
114+
115+
ESP_ERROR_CHECK(i2c_new_slave_device(&self->config, &self->handle));
116+
i2c_slave_event_callbacks_t cbs = {
117+
.on_receive = i2c_slave_receive_cb,
118+
.on_request = i2c_slave_request_cb,
119+
};
120+
ESP_ERROR_CHECK(i2c_slave_register_event_callbacks(self->handle, &cbs, self));
121+
}
122+
123+
/******************************************************************************/
124+
// I2CTarget port implementation
125+
126+
static inline size_t mp_machine_i2c_target_get_index(machine_i2c_target_obj_t *self) {
127+
return self->config.i2c_port;
128+
}
129+
130+
static void mp_machine_i2c_target_event_callback(machine_i2c_target_irq_obj_t *irq) {
131+
mp_irq_handler(&irq->base);
132+
}
133+
134+
static size_t mp_machine_i2c_target_read_bytes(machine_i2c_target_obj_t *self, size_t len, uint8_t *buf) {
135+
size_t i = 0;
136+
while (i < len && self->index < self->rx_done_event_data->length) {
137+
buf[i++] = self->rx_done_event_data->buffer[self->index++];
138+
}
139+
return i;
140+
}
141+
142+
static size_t mp_machine_i2c_target_write_bytes(machine_i2c_target_obj_t *self, size_t len, const uint8_t *buf) {
143+
uint32_t write_len;
144+
i2c_slave_write(self->handle, buf, len, &write_len, 1000);
145+
return write_len;
146+
}
147+
148+
static void mp_machine_i2c_target_irq_config(machine_i2c_target_obj_t *self, unsigned int trigger) {
149+
}
150+
151+
static mp_obj_t mp_machine_i2c_target_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
152+
enum { ARG_id, ARG_addr, ARG_addrsize, ARG_mem, ARG_mem_addrsize, ARG_scl, ARG_sda };
153+
static const mp_arg_t allowed_args[] = {
154+
{ MP_QSTR_id, MP_ARG_INT, {.u_int = 0} },
155+
{ MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT },
156+
{ MP_QSTR_addrsize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 7} },
157+
{ MP_QSTR_mem, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
158+
{ MP_QSTR_mem_addrsize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} },
159+
{ MP_QSTR_scl, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
160+
{ MP_QSTR_sda, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
161+
};
162+
163+
// Parse args.
164+
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
165+
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
166+
167+
int i2c_id = args[ARG_id].u_int;
168+
169+
// Check if the I2C bus is valid
170+
if (i2c_id < 0 || i2c_id >= MP_ARRAY_SIZE(machine_i2c_target_obj)) {
171+
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("I2CTarget(%d) doesn't exist"), i2c_id);
172+
}
173+
174+
// Get static peripheral object.
175+
machine_i2c_target_obj_t *self = &machine_i2c_target_obj[i2c_id];
176+
177+
bool first_init = false;
178+
if (self->base.type == NULL) {
179+
// Created for the first time, set default pins
180+
self->base.type = &machine_i2c_target_type;
181+
self->config.i2c_port = i2c_id;
182+
if (self->config.i2c_port == 0) {
183+
self->config.scl_io_num = MICROPY_HW_I2C0_SCL;
184+
self->config.sda_io_num = MICROPY_HW_I2C0_SDA;
185+
} else {
186+
self->config.scl_io_num = MICROPY_HW_I2C1_SCL;
187+
self->config.sda_io_num = MICROPY_HW_I2C1_SDA;
188+
}
189+
first_init = true;
190+
}
191+
192+
// Initialise data.
193+
self->state = STATE_IDLE;
194+
self->stop_pending = false;
195+
self->irq_active = false;
196+
MP_STATE_PORT(machine_i2c_target_mem_obj)[i2c_id] = args[ARG_mem].u_obj;
197+
machine_i2c_target_data_t *data = &machine_i2c_target_data[i2c_id];
198+
machine_i2c_target_data_init(data, args[ARG_mem].u_obj, args[ARG_mem_addrsize].u_int);
199+
200+
// Set SCL/SDA pins if configured.
201+
if (args[ARG_scl].u_obj != mp_const_none) {
202+
self->config.scl_io_num = mp_hal_get_pin_obj(args[ARG_scl].u_obj);
203+
}
204+
if (args[ARG_sda].u_obj != mp_const_none) {
205+
self->config.sda_io_num = mp_hal_get_pin_obj(args[ARG_sda].u_obj);
206+
}
207+
208+
// Initialise the I2C target.
209+
i2c_target_init(self, data, args[ARG_addr].u_int, args[ARG_addrsize].u_int, first_init);
210+
211+
return MP_OBJ_FROM_PTR(self);
212+
}
213+
214+
static void mp_machine_i2c_target_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
215+
machine_i2c_target_obj_t *self = MP_OBJ_TO_PTR(self_in);
216+
mp_printf(print, "I2CTarget(%u, addr=%u, scl=%u, sda=%u)",
217+
self->config.i2c_port, self->config.slave_addr, self->config.scl_io_num, self->config.sda_io_num);
218+
}
219+
220+
static void mp_machine_i2c_target_deinit(machine_i2c_target_obj_t *self) {
221+
if (self->handle != NULL) {
222+
i2c_del_slave_device(self->handle);
223+
self->handle = NULL;
224+
}
225+
}

ports/esp32/main.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
#include "py/repl.h"
5252
#include "py/gc.h"
5353
#include "py/mphal.h"
54+
#include "extmod/modmachine.h"
5455
#include "shared/readline/readline.h"
5556
#include "shared/runtime/pyexec.h"
5657
#include "shared/timeutils/timeutils.h"
@@ -199,7 +200,11 @@ void mp_task(void *pvParameter) {
199200
machine_pwm_deinit_all();
200201
// TODO: machine_rmt_deinit_all();
201202
machine_pins_deinit();
203+
#if MICROPY_PY_MACHINE_I2C_TARGET
204+
mp_machine_i2c_target_deinit_all();
205+
#endif
202206
machine_deinit();
207+
203208
#if MICROPY_PY_SOCKET_EVENTS
204209
socket_events_deinit();
205210
#endif

ports/esp32/mpconfigport.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,10 @@
138138
#define MICROPY_PY_MACHINE_PWM_INCLUDEFILE "ports/esp32/machine_pwm.c"
139139
#define MICROPY_PY_MACHINE_I2C (1)
140140
#define MICROPY_PY_MACHINE_I2C_TRANSFER_WRITE1 (1)
141+
// I2C target hardware is limited on ESP32 (eg read event comes after the read) so we only support newer SoCs.
142+
#define MICROPY_PY_MACHINE_I2C_TARGET (SOC_I2C_SUPPORT_SLAVE && !CONFIG_IDF_TARGET_ESP32)
143+
#define MICROPY_PY_MACHINE_I2C_TARGET_INCLUDEFILE "ports/esp32/machine_i2c_target.c"
144+
#define MICROPY_PY_MACHINE_I2C_TARGET_MAX (2)
141145
#define MICROPY_PY_MACHINE_SOFTI2C (1)
142146
#define MICROPY_PY_MACHINE_SPI (1)
143147
#define MICROPY_PY_MACHINE_SOFTSPI (1)

0 commit comments

Comments
 (0)