summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorScott Shawcroft <scott@tannewt.org>2018-08-17 16:51:45 -0700
committerGitHub <noreply@github.com>2018-08-17 16:51:45 -0700
commit4a4d84ba42fb84032b31344e14fc3bb1f9e8dce2 (patch)
treeed2e486dea85dd416975d30e6beca608ce5597bc
parent5dd420f7ff2c87a5412a55fea29eb21615a89e14 (diff)
parent11cbeb87adb10883fe46c46bd4e22e3ad3991ed3 (diff)
Merge pull request #1064 from notro/i2cslave
Add busio.I2CSlave
-rw-r--r--lib/utils/interrupt_char.c5
-rw-r--r--lib/utils/interrupt_char.h3
-rw-r--r--[-rwxr-xr-x]ports/atmel-samd/Makefile2
-rw-r--r--ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h2
-rw-r--r--ports/atmel-samd/boards/feather_m4_express/mpconfigboard.h2
-rw-r--r--ports/atmel-samd/boards/metro_m0_express/mpconfigboard.h2
-rw-r--r--ports/atmel-samd/boards/metro_m4_express/mpconfigboard.h2
-rw-r--r--ports/atmel-samd/common-hal/busio/I2C.c44
-rw-r--r--ports/atmel-samd/common-hal/busio/I2C.h3
-rw-r--r--ports/atmel-samd/common-hal/i2cslave/I2CSlave.c252
-rw-r--r--ports/atmel-samd/common-hal/i2cslave/I2CSlave.h45
-rw-r--r--ports/atmel-samd/common-hal/i2cslave/__init__.c1
-rw-r--r--ports/atmel-samd/mpconfigport.h8
-rw-r--r--py/obj.h7
-rw-r--r--shared-bindings/i2cslave/I2CSlave.c450
-rw-r--r--shared-bindings/i2cslave/I2CSlave.h60
-rw-r--r--shared-bindings/i2cslave/__init__.c117
-rw-r--r--shared-bindings/index.rst1
18 files changed, 985 insertions, 21 deletions
diff --git a/lib/utils/interrupt_char.c b/lib/utils/interrupt_char.c
index fca0f95b5..91ee5c80e 100644
--- a/lib/utils/interrupt_char.c
+++ b/lib/utils/interrupt_char.c
@@ -47,4 +47,9 @@ void mp_keyboard_interrupt(void) {
#endif
}
+// Check to see if we've been CTRL-C'ed by autoreload or the user.
+bool mp_hal_is_interrupted(void) {
+ return MP_STATE_VM(mp_pending_exception) == MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception));
+}
+
#endif
diff --git a/lib/utils/interrupt_char.h b/lib/utils/interrupt_char.h
index ca50d4d56..e0b1db529 100644
--- a/lib/utils/interrupt_char.h
+++ b/lib/utils/interrupt_char.h
@@ -26,8 +26,11 @@
#ifndef MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H
#define MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H
+#include <stdbool.h>
+
extern int mp_interrupt_char;
void mp_hal_set_interrupt_char(int c);
void mp_keyboard_interrupt(void);
+bool mp_hal_is_interrupted(void);
#endif // MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H
diff --git a/ports/atmel-samd/Makefile b/ports/atmel-samd/Makefile
index 20f3ea46c..e1634a1b9 100755..100644
--- a/ports/atmel-samd/Makefile
+++ b/ports/atmel-samd/Makefile
@@ -308,6 +308,8 @@ SRC_COMMON_HAL = \
busio/UART.c \
digitalio/__init__.c \
digitalio/DigitalInOut.c \
+ i2cslave/__init__.c \
+ i2cslave/I2CSlave.c \
microcontroller/__init__.c \
microcontroller/Pin.c \
microcontroller/Processor.c \
diff --git a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h
index 108d67d9f..03d0ba9bd 100644
--- a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h
+++ b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h
@@ -62,3 +62,5 @@
// USB is always used internally so skip the pin objects for it.
#define IGNORE_PIN_PA24 1
#define IGNORE_PIN_PA25 1
+
+#define CIRCUITPY_I2CSLAVE
diff --git a/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.h b/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.h
index c82395baf..e9e921b4d 100644
--- a/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.h
+++ b/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.h
@@ -47,3 +47,5 @@
// USB is always used internally so skip the pin objects for it.
#define IGNORE_PIN_PA24 1
#define IGNORE_PIN_PA25 1
+
+#define CIRCUITPY_I2CSLAVE
diff --git a/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.h b/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.h
index 135d6ae92..40ef3ce78 100644
--- a/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.h
+++ b/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.h
@@ -63,3 +63,5 @@
// USB is always used internally so skip the pin objects for it.
#define IGNORE_PIN_PA24 1
#define IGNORE_PIN_PA25 1
+
+#define CIRCUITPY_I2CSLAVE
diff --git a/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.h b/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.h
index 050f678dd..f1201c8a0 100644
--- a/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.h
+++ b/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.h
@@ -48,3 +48,5 @@
// USB is always used internally so skip the pin objects for it.
#define IGNORE_PIN_PA24 1
#define IGNORE_PIN_PA25 1
+
+#define CIRCUITPY_I2CSLAVE
diff --git a/ports/atmel-samd/common-hal/busio/I2C.c b/ports/atmel-samd/common-hal/busio/I2C.c
index 8bfa8ddd2..c0643865d 100644
--- a/ports/atmel-samd/common-hal/busio/I2C.c
+++ b/ports/atmel-samd/common-hal/busio/I2C.c
@@ -39,39 +39,41 @@
// Number of times to try to send packet if failed.
#define ATTEMPTS 2
-void common_hal_busio_i2c_construct(busio_i2c_obj_t *self,
- const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) {
- #ifdef PIRKEY_M0
- mp_raise_NotImplementedError(translate("Not enough pins available"));
- return;
- #endif
- Sercom* sercom = NULL;
- uint8_t sercom_index;
- uint32_t sda_pinmux = 0;
- uint32_t scl_pinmux = 0;
+Sercom *samd_i2c_get_sercom(const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda,
+ uint8_t *sercom_index, uint32_t *sda_pinmux, uint32_t *scl_pinmux) {
+ *sda_pinmux = 0;
+ *scl_pinmux = 0;
for (int i = 0; i < NUM_SERCOMS_PER_PIN; i++) {
- sercom_index = sda->sercom[i].index;
- if (sercom_index >= SERCOM_INST_NUM) {
+ *sercom_index = sda->sercom[i].index;
+ if (*sercom_index >= SERCOM_INST_NUM) {
continue;
}
- Sercom* potential_sercom = sercom_insts[sercom_index];
+ Sercom* potential_sercom = sercom_insts[*sercom_index];
if (potential_sercom->I2CM.CTRLA.bit.ENABLE != 0 ||
sda->sercom[i].pad != 0) {
continue;
}
- sda_pinmux = PINMUX(sda->number, (i == 0) ? MUX_C : MUX_D);
+ *sda_pinmux = PINMUX(sda->number, (i == 0) ? MUX_C : MUX_D);
for (int j = 0; j < NUM_SERCOMS_PER_PIN; j++) {
- if (sercom_index == scl->sercom[j].index &&
+ if (*sercom_index == scl->sercom[j].index &&
scl->sercom[j].pad == 1) {
- scl_pinmux = PINMUX(scl->number, (j == 0) ? MUX_C : MUX_D);
- sercom = potential_sercom;
- break;
+ *scl_pinmux = PINMUX(scl->number, (j == 0) ? MUX_C : MUX_D);
+ return potential_sercom;
}
}
- if (sercom != NULL) {
- break;
- }
}
+ return NULL;
+}
+
+void common_hal_busio_i2c_construct(busio_i2c_obj_t *self,
+ const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) {
+ #ifdef PIRKEY_M0
+ mp_raise_NotImplementedError(translate("Not enough pins available"));
+ return;
+ #endif
+ uint8_t sercom_index;
+ uint32_t sda_pinmux, scl_pinmux;
+ Sercom* sercom = samd_i2c_get_sercom(scl, sda, &sercom_index, &sda_pinmux, &scl_pinmux);
if (sercom == NULL) {
mp_raise_ValueError(translate("Invalid pins"));
}
diff --git a/ports/atmel-samd/common-hal/busio/I2C.h b/ports/atmel-samd/common-hal/busio/I2C.h
index 2401d9247..366c6c469 100644
--- a/ports/atmel-samd/common-hal/busio/I2C.h
+++ b/ports/atmel-samd/common-hal/busio/I2C.h
@@ -41,4 +41,7 @@ typedef struct {
uint8_t sda_pin;
} busio_i2c_obj_t;
+extern Sercom *samd_i2c_get_sercom(const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda,
+ uint8_t *sercom_index, uint32_t *sda_pinmux, uint32_t *scl_pinmux);
+
#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_BUSIO_I2C_H
diff --git a/ports/atmel-samd/common-hal/i2cslave/I2CSlave.c b/ports/atmel-samd/common-hal/i2cslave/I2CSlave.c
new file mode 100644
index 000000000..0e68453df
--- /dev/null
+++ b/ports/atmel-samd/common-hal/i2cslave/I2CSlave.c
@@ -0,0 +1,252 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Noralf Trønnes
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "shared-bindings/i2cslave/I2CSlave.h"
+#include "common-hal/busio/I2C.h"
+
+#include "lib/utils/interrupt_char.h"
+#include "py/mperrno.h"
+#include "py/mphal.h"
+#include "py/runtime.h"
+
+#include "hal/include/hal_gpio.h"
+#include "peripherals/samd/sercom.h"
+
+void common_hal_i2cslave_i2c_slave_construct(i2cslave_i2c_slave_obj_t *self,
+ const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda,
+ uint8_t *addresses, unsigned int num_addresses, bool smbus) {
+ uint8_t sercom_index;
+ uint32_t sda_pinmux, scl_pinmux;
+ Sercom *sercom = samd_i2c_get_sercom(scl, sda, &sercom_index, &sda_pinmux, &scl_pinmux);
+ if (sercom == NULL) {
+ mp_raise_ValueError("Invalid pins");
+ }
+ self->sercom = sercom;
+
+ gpio_set_pin_function(sda->number, GPIO_PIN_FUNCTION_OFF);
+ gpio_set_pin_function(scl->number, GPIO_PIN_FUNCTION_OFF);
+ gpio_set_pin_function(sda->number, sda_pinmux);
+ gpio_set_pin_function(scl->number, scl_pinmux);
+
+ self->sda_pin = sda->number;
+ self->scl_pin = scl->number;
+ claim_pin(sda);
+ claim_pin(scl);
+
+ samd_peripherals_sercom_clock_init(sercom, sercom_index);
+
+ sercom->I2CS.CTRLA.bit.SWRST = 1;
+ while (sercom->I2CS.CTRLA.bit.SWRST || sercom->I2CS.SYNCBUSY.bit.SWRST) {}
+
+ sercom->I2CS.CTRLB.bit.AACKEN = 0; // Automatic acknowledge is disabled.
+
+ if (num_addresses == 1) {
+ sercom->I2CS.CTRLB.bit.AMODE = 0x0; // MASK
+ sercom->I2CS.ADDR.bit.ADDR = addresses[0];
+ sercom->I2CS.ADDR.bit.ADDRMASK = 0x00; // Match exact address
+ } else if (num_addresses == 2) {
+ sercom->I2CS.CTRLB.bit.AMODE = 0x1; // 2_ADDRS
+ sercom->I2CS.ADDR.bit.ADDR = addresses[0];
+ sercom->I2CS.ADDR.bit.ADDRMASK = addresses[1];
+ } else {
+ uint32_t combined = 0; // all addresses OR'ed
+ uint32_t differ = 0; // bits that differ between addresses
+ for (unsigned int i = 0; i < num_addresses; i++) {
+ combined |= addresses[i];
+ differ |= addresses[0] ^ addresses[i];
+ }
+ sercom->I2CS.CTRLB.bit.AMODE = 0x0; // MASK
+ sercom->I2CS.ADDR.bit.ADDR = combined;
+ sercom->I2CS.ADDR.bit.ADDRMASK = differ;
+ }
+ self->addresses = addresses;
+ self->num_addresses = num_addresses;
+
+ if (smbus) {
+ sercom->I2CS.CTRLA.bit.LOWTOUTEN = 1; // Errata 12003
+ sercom->I2CS.CTRLA.bit.SEXTTOEN = 1; // Slave SCL Low Extend/Cumulative Time-Out 25ms
+ }
+ sercom->I2CS.CTRLA.bit.SCLSM = 0; // Clock stretch before ack
+ sercom->I2CS.CTRLA.bit.MODE = 0x04; // Slave mode
+ sercom->I2CS.CTRLA.bit.ENABLE = 1;
+}
+
+bool common_hal_i2cslave_i2c_slave_deinited(i2cslave_i2c_slave_obj_t *self) {
+ return self->sda_pin == NO_PIN;
+}
+
+void common_hal_i2cslave_i2c_slave_deinit(i2cslave_i2c_slave_obj_t *self) {
+ if (common_hal_i2cslave_i2c_slave_deinited(self)) {
+ return;
+ }
+
+ self->sercom->I2CS.CTRLA.bit.ENABLE = 0;
+
+ reset_pin(self->sda_pin);
+ reset_pin(self->scl_pin);
+ self->sda_pin = NO_PIN;
+ self->scl_pin = NO_PIN;
+}
+
+static int i2c_slave_check_error(i2cslave_i2c_slave_obj_t *self, bool raise) {
+ if (!self->sercom->I2CS.INTFLAG.bit.ERROR) {
+ return 0;
+ }
+
+ int err = MP_EIO;
+
+ if (self->sercom->I2CS.STATUS.bit.LOWTOUT || self->sercom->I2CS.STATUS.bit.SEXTTOUT) {
+ err = MP_ETIMEDOUT;
+ }
+
+ self->sercom->I2CS.INTFLAG.reg = SERCOM_I2CS_INTFLAG_ERROR; // Clear flag
+
+ if (raise) {
+ mp_raise_OSError(err);
+ }
+ return -err;
+}
+
+int common_hal_i2cslave_i2c_slave_is_addressed(i2cslave_i2c_slave_obj_t *self, uint8_t *address, bool *is_read, bool *is_restart)
+{
+ int err = i2c_slave_check_error(self, false);
+ if (err) {
+ return err;
+ }
+
+ if (!self->sercom->I2CS.INTFLAG.bit.AMATCH) {
+ return 0;
+ }
+
+ self->writing = false;
+
+ *address = self->sercom->I2CS.DATA.reg >> 1;
+ *is_read = self->sercom->I2CS.STATUS.bit.DIR;
+ *is_restart = self->sercom->I2CS.STATUS.bit.SR;
+
+ for (unsigned int i = 0; i < self->num_addresses; i++) {
+ if (*address == self->addresses[i]) {
+ common_hal_i2cslave_i2c_slave_ack(self, true);
+ return 1;
+ }
+ }
+
+ // This should clear AMATCH, but it doesn't...
+ common_hal_i2cslave_i2c_slave_ack(self, false);
+ return 0;
+}
+
+int common_hal_i2cslave_i2c_slave_read_byte(i2cslave_i2c_slave_obj_t *self, uint8_t *data) {
+ for (int t = 0; t < 100 && !self->sercom->I2CS.INTFLAG.reg; t++) {
+ mp_hal_delay_us(10);
+ }
+
+ i2c_slave_check_error(self, true);
+
+ if (!self->sercom->I2CS.INTFLAG.bit.DRDY ||
+ self->sercom->I2CS.INTFLAG.bit.PREC ||
+ self->sercom->I2CS.INTFLAG.bit.AMATCH) {
+ return 0;
+ }
+
+ *data = self->sercom->I2CS.DATA.reg;
+ return 1;
+}
+
+int common_hal_i2cslave_i2c_slave_write_byte(i2cslave_i2c_slave_obj_t *self, uint8_t data) {
+ for (int t = 0; !self->sercom->I2CS.INTFLAG.reg && t < 100; t++) {
+ mp_hal_delay_us(10);
+ }
+
+ i2c_slave_check_error(self, true);
+
+ if (self->sercom->I2CS.INTFLAG.bit.PREC) {
+ return 0;
+ }
+
+ // RXNACK can carry over from the previous transfer
+ if (self->writing && self->sercom->I2CS.STATUS.bit.RXNACK) {
+ return 0;
+ }
+
+ self->writing = true;
+
+ if (!self->sercom->I2CS.INTFLAG.bit.DRDY) {
+ return 0;
+ }
+
+ self->sercom->I2CS.DATA.bit.DATA = data; // Send data
+
+ return 1;
+}
+
+void common_hal_i2cslave_i2c_slave_ack(i2cslave_i2c_slave_obj_t *self, bool ack) {
+ self->sercom->I2CS.CTRLB.bit.ACKACT = !ack;
+ self->sercom->I2CS.CTRLB.bit.CMD = 0x03;
+}
+
+void common_hal_i2cslave_i2c_slave_close(i2cslave_i2c_slave_obj_t *self) {
+ for (int t = 0; !self->sercom->I2CS.INTFLAG.reg && t < 100; t++) {
+ mp_hal_delay_us(10);
+ }
+
+ if (self->sercom->I2CS.INTFLAG.bit.AMATCH || !self->sercom->I2CS.STATUS.bit.CLKHOLD) {
+ return;
+ }
+
+ if (!self->sercom->I2CS.STATUS.bit.DIR) {
+ common_hal_i2cslave_i2c_slave_ack(self, false);
+ } else {
+ int i = 0;
+ while (self->sercom->I2CS.INTFLAG.reg == SERCOM_I2CS_INTFLAG_DRDY) {
+ if (mp_hal_is_interrupted()) {
+ return;
+ }
+
+ self->sercom->I2CS.DATA.bit.DATA = 0xff; // Send dummy byte
+
+ // Wait for a result (if any).
+ // test_byte_word.py::TestWord::test_write_seq leaves us with no INTFLAGs set in some of the tests
+ for (int t = 0; !self->sercom->I2CS.INTFLAG.reg && t < 100; t++) {
+ mp_hal_delay_us(10);
+ }
+
+ if (++i > 1000) { // Avoid getting stuck "forever"
+ mp_raise_OSError(MP_EIO);
+ }
+ }
+ }
+
+ if (self->sercom->I2CS.INTFLAG.bit.AMATCH) {
+ return;
+ }
+
+ if (self->sercom->I2CS.STATUS.bit.CLKHOLD) {
+ // Unable to release the clock.
+ // The slave might have to be re-initialized to get unstuck.
+ mp_raise_OSError(MP_EIO);
+ }
+}
diff --git a/ports/atmel-samd/common-hal/i2cslave/I2CSlave.h b/ports/atmel-samd/common-hal/i2cslave/I2CSlave.h
new file mode 100644
index 000000000..bf4f877bd
--- /dev/null
+++ b/ports/atmel-samd/common-hal/i2cslave/I2CSlave.h
@@ -0,0 +1,45 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Noralf Trønnes
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_BUSIO_I2C_SLAVE_H
+#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_BUSIO_I2C_SLAVE_H
+
+#include "common-hal/microcontroller/Pin.h"
+#include "py/obj.h"
+
+typedef struct {
+ mp_obj_base_t base;
+
+ uint8_t *addresses;
+ unsigned int num_addresses;
+
+ Sercom *sercom;
+ uint8_t scl_pin;
+ uint8_t sda_pin;
+ bool writing;
+} i2cslave_i2c_slave_obj_t;
+
+#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_BUSIO_I2C_SLAVE_H
diff --git a/ports/atmel-samd/common-hal/i2cslave/__init__.c b/ports/atmel-samd/common-hal/i2cslave/__init__.c
new file mode 100644
index 000000000..f289bbc0e
--- /dev/null
+++ b/ports/atmel-samd/common-hal/i2cslave/__init__.c
@@ -0,0 +1 @@
+// No i2cslave module functions.
diff --git a/ports/atmel-samd/mpconfigport.h b/ports/atmel-samd/mpconfigport.h
index 8b921c2a9..576325461 100644
--- a/ports/atmel-samd/mpconfigport.h
+++ b/ports/atmel-samd/mpconfigport.h
@@ -174,6 +174,7 @@ extern const struct _mp_obj_module_t digitalio_module;
extern const struct _mp_obj_module_t pulseio_module;
extern const struct _mp_obj_module_t busio_module;
extern const struct _mp_obj_module_t board_module;
+extern const struct _mp_obj_module_t i2cslave_module;
extern const struct _mp_obj_module_t math_module;
extern const struct _mp_obj_module_t os_module;
extern const struct _mp_obj_module_t random_module;
@@ -225,11 +226,18 @@ extern const struct _mp_obj_module_t usb_hid_module;
#define AUDIOIO_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_audioio), (mp_obj_t)&audioio_module },
#endif
+ #ifdef CIRCUITPY_I2CSLAVE
+ #define I2CSLAVE_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_i2cslave), (mp_obj_t)&i2cslave_module },
+ #else
+ #define I2CSLAVE_MODULE
+ #endif
+
#ifndef EXTRA_BUILTIN_MODULES
#define EXTRA_BUILTIN_MODULES \
AUDIOIO_MODULE \
AUDIOBUSIO_MODULE \
{ MP_OBJ_NEW_QSTR(MP_QSTR_bitbangio), (mp_obj_t)&bitbangio_module }, \
+ I2CSLAVE_MODULE \
{ MP_OBJ_NEW_QSTR(MP_QSTR_rotaryio), (mp_obj_t)&rotaryio_module }, \
{ MP_OBJ_NEW_QSTR(MP_QSTR_gamepad),(mp_obj_t)&gamepad_module }
#endif
diff --git a/py/obj.h b/py/obj.h
index 143751cbf..59cce0836 100644
--- a/py/obj.h
+++ b/py/obj.h
@@ -295,6 +295,13 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t;
#define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, n_args_min, fun_name) \
const mp_obj_fun_builtin_var_t obj_name = \
{{&mp_type_fun_builtin_var}, true, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.kw = fun_name}
+#define MP_DEFINE_CONST_PROP_GET(obj_name, fun_name) \
+ const mp_obj_fun_builtin_fixed_t fun_name##_obj = {{&mp_type_fun_builtin_1}, .fun._1 = fun_name}; \
+ const mp_obj_property_t obj_name = { \
+ .base.type = &mp_type_property, \
+ .proxy = {(mp_obj_t)&fun_name##_obj, \
+ (mp_obj_t)&mp_const_none_obj, \
+ (mp_obj_t)&mp_const_none_obj}, }
// These macros are used to define constant map/dict objects
// You can put "static" in front of the definition to make it local
diff --git a/shared-bindings/i2cslave/I2CSlave.c b/shared-bindings/i2cslave/I2CSlave.c
new file mode 100644
index 000000000..2f3646d57
--- /dev/null
+++ b/shared-bindings/i2cslave/I2CSlave.c
@@ -0,0 +1,450 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Noralf Trønnes
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "shared-bindings/microcontroller/Pin.h"
+#include "shared-bindings/i2cslave/I2CSlave.h"
+#include "shared-bindings/time/__init__.h"
+#include "shared-bindings/util.h"
+
+#include "lib/utils/buffer_helper.h"
+#include "lib/utils/context_manager_helpers.h"
+#include "lib/utils/interrupt_char.h"
+
+#include "py/mperrno.h"
+#include "py/mphal.h"
+#include "py/obj.h"
+#include "py/objproperty.h"
+#include "py/runtime.h"
+
+STATIC mp_obj_t mp_obj_new_i2cslave_i2c_slave_request(i2cslave_i2c_slave_obj_t *slave, uint8_t address, bool is_read, bool is_restart) {
+ i2cslave_i2c_slave_request_obj_t *self = m_new_obj(i2cslave_i2c_slave_request_obj_t);
+ self->base.type = &i2cslave_i2c_slave_request_type;
+ self->slave = slave;
+ self->address = address;
+ self->is_read = is_read;
+ self->is_restart = is_restart;
+ return (mp_obj_t)self;
+}
+
+//| .. currentmodule:: i2cslave
+//|
+//| :class:`I2CSlave` --- Two wire serial protocol slave
+//| ----------------------------------------------------
+//|
+//| .. class:: I2CSlave(scl, sda, addresses, smbus=False)
+//|
+//| I2C is a two-wire protocol for communicating between devices.
+//| This implements the slave side.
+//|
+//| :param ~microcontroller.Pin scl: The clock pin
+//| :param ~microcontroller.Pin sda: The data pin
+//| :param tuple addresses: The I2C addresses to respond to (how many is hw dependent).
+//| :param bool smbus: Use SMBUS timings if the hardware supports it
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *pos_args) {
+ mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, true);
+ i2cslave_i2c_slave_obj_t *self = m_new_obj(i2cslave_i2c_slave_obj_t);
+ self->base.type = &i2cslave_i2c_slave_type;
+ mp_map_t kw_args;
+ mp_map_init_fixed_table(&kw_args, n_kw, pos_args + n_args);
+ enum { ARG_scl, ARG_sda, ARG_addresses, ARG_smbus };
+ static const mp_arg_t allowed_args[] = {
+ { MP_QSTR_scl, MP_ARG_REQUIRED | MP_ARG_OBJ },
+ { MP_QSTR_sda, MP_ARG_REQUIRED | MP_ARG_OBJ },
+ { MP_QSTR_addresses, MP_ARG_REQUIRED | MP_ARG_OBJ },
+ { MP_QSTR_smbus, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
+ };
+ mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
+ mp_arg_parse_all(n_args, pos_args, &kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
+
+ assert_pin(args[ARG_scl].u_obj, false);
+ assert_pin(args[ARG_sda].u_obj, false);
+ const mcu_pin_obj_t* scl = MP_OBJ_TO_PTR(args[ARG_scl].u_obj);
+ assert_pin_free(scl);
+ const mcu_pin_obj_t* sda = MP_OBJ_TO_PTR(args[ARG_sda].u_obj);
+ assert_pin_free(sda);
+
+ mp_obj_iter_buf_t iter_buf;
+ mp_obj_t iterable = mp_getiter(args[ARG_addresses].u_obj, &iter_buf);
+ mp_obj_t item;
+ uint8_t *addresses = NULL;
+ unsigned int i = 0;
+ while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
+ mp_int_t value;
+ if (!mp_obj_get_int_maybe(item, &value)) {
+ mp_raise_TypeError("can't convert address to int");
+ }
+ if (value < 0x00 || value > 0x7f) {
+ mp_raise_ValueError("address out of bounds");
+ }
+ addresses = m_renew(uint8_t, addresses, i, i + 1);
+ addresses[i++] = value;
+ }
+ if (i == 0) {
+ mp_raise_ValueError("addresses is empty");
+ }
+
+ common_hal_i2cslave_i2c_slave_construct(self, scl, sda, addresses, i, args[ARG_smbus].u_bool);
+ return (mp_obj_t)self;
+}
+
+//| .. method:: deinit()
+//|
+//| Releases control of the underlying hardware so other classes can use it.
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_obj_deinit(mp_obj_t self_in) {
+ mp_check_self(MP_OBJ_IS_TYPE(self_in, &i2cslave_i2c_slave_type));
+ i2cslave_i2c_slave_obj_t *self = MP_OBJ_TO_PTR(self_in);
+ common_hal_i2cslave_i2c_slave_deinit(self);
+ return mp_const_none;
+}
+MP_DEFINE_CONST_FUN_OBJ_1(i2cslave_i2c_slave_deinit_obj, i2cslave_i2c_slave_obj_deinit);
+
+//| .. method:: __enter__()
+//|
+//| No-op used in Context Managers.
+//|
+// Provided by context manager helper.
+
+//| .. method:: __exit__()
+//|
+//| Automatically deinitializes the hardware on context exit. See
+//| :ref:`lifetime-and-contextmanagers` for more info.
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_obj___exit__(size_t n_args, const mp_obj_t *args) {
+ mp_check_self(MP_OBJ_IS_TYPE(args[0], &i2cslave_i2c_slave_type));
+ i2cslave_i2c_slave_obj_t *self = MP_OBJ_TO_PTR(args[0]);
+ common_hal_i2cslave_i2c_slave_deinit(self);
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(i2cslave_i2c_slave___exit___obj, 4, 4, i2cslave_i2c_slave_obj___exit__);
+
+//| .. method:: request(timeout=-1)
+//|
+//| Wait for an I2C request from a master.
+//|
+//| :param float timeout: Timeout in seconds. Zero means wait forever, a negative value means check once
+//| :return: I2C Slave Request or None if timeout=-1 and there's no request
+//| :rtype: ~i2cslave.I2CSlaveRequest
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
+ mp_check_self(MP_OBJ_IS_TYPE(pos_args[0], &i2cslave_i2c_slave_type));
+ i2cslave_i2c_slave_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
+ raise_error_if_deinited(common_hal_i2cslave_i2c_slave_deinited(self));
+ enum { ARG_timeout };
+ static const mp_arg_t allowed_args[] = {
+ { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_SMALL_INT(-1)} },
+ };
+ mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
+ mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
+
+ #if MICROPY_PY_BUILTINS_FLOAT
+ float f = mp_obj_get_float(args[ARG_timeout].u_obj) * 1000;
+ int timeout_ms = (int)f;
+ #else
+ int timeout_ms = mp_obj_get_int(args[ARG_timeout].u_obj) * 1000;
+ #endif
+
+ bool forever = false;
+ uint64_t timeout_end = 0;
+ if (timeout_ms == 0) {
+ forever = true;
+ } else if (timeout_ms > 0) {
+ timeout_end = common_hal_time_monotonic() + timeout_ms;
+ }
+
+ int last_error = 0;
+
+ do {
+ uint8_t address;
+ bool is_read;
+ bool is_restart;
+
+ MICROPY_VM_HOOK_LOOP
+ if (mp_hal_is_interrupted()) {
+ return mp_const_none;
+ }
+
+ int status = common_hal_i2cslave_i2c_slave_is_addressed(self, &address, &is_read, &is_restart);
+ if (status < 0) {
+ // On error try one more time before bailing out
+ if (last_error) {
+ mp_raise_OSError(last_error);
+ }
+ last_error = -status;
+ mp_hal_delay_ms(10);
+ continue;
+ }
+
+ last_error = 0;
+
+ if (status == 0) {
+ mp_hal_delay_us(10);
+ continue;
+ }
+
+ return mp_obj_new_i2cslave_i2c_slave_request(self, address, is_read, is_restart);
+ } while (forever || common_hal_time_monotonic() < timeout_end);
+
+ if (timeout_ms > 0) {
+ mp_raise_OSError(MP_ETIMEDOUT);
+ }
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_KW(i2cslave_i2c_slave_request_obj, 1, i2cslave_i2c_slave_request);
+
+STATIC const mp_rom_map_elem_t i2cslave_i2c_slave_locals_dict_table[] = {
+ { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&i2cslave_i2c_slave_deinit_obj) },
+ { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) },
+ { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&i2cslave_i2c_slave___exit___obj) },
+ { MP_ROM_QSTR(MP_QSTR_request), MP_ROM_PTR(&i2cslave_i2c_slave_request_obj) },
+
+};
+
+STATIC MP_DEFINE_CONST_DICT(i2cslave_i2c_slave_locals_dict, i2cslave_i2c_slave_locals_dict_table);
+
+const mp_obj_type_t i2cslave_i2c_slave_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_I2CSlave,
+ .make_new = i2cslave_i2c_slave_make_new,
+ .locals_dict = (mp_obj_dict_t*)&i2cslave_i2c_slave_locals_dict,
+};
+
+
+//| :class:`I2CSlaveRequest` --- I2C Slave Request
+//| ----------------------------------------------
+//|
+//| .. class:: I2CSlaveRequest(slave, address, is_read, is_restart)
+//|
+//| I2C transfer request from a master.
+//| This cannot be instantiated directly, but is returned by :py:meth:`I2CSlave.request`.
+//|
+//| :param ~i2cslave.I2CSlave slave: The I2C Slave receiving this request
+//| :param int address: I2C address
+//| :param bool is_read: I2C Master read request
+//| :param bool is_restart: Repeated Start Condition
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
+ mp_arg_check_num(n_args, n_kw, 4, 4, false);
+ return mp_obj_new_i2cslave_i2c_slave_request(args[0], mp_obj_get_int(args[1]), mp_obj_is_true(args[2]), mp_obj_is_true(args[3]));
+}
+
+//| .. method:: __enter__()
+//|
+//| No-op used in Context Managers.
+//|
+// Provided by context manager helper.
+
+//| .. method:: __exit__()
+//|
+//| Close the request.
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_obj___exit__(size_t n_args, const mp_obj_t *args) {
+ mp_check_self(MP_OBJ_IS_TYPE(args[0], &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(args[0]);
+ common_hal_i2cslave_i2c_slave_close(self->slave);
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(i2cslave_i2c_slave_request___exit___obj, 4, 4, i2cslave_i2c_slave_request_obj___exit__);
+
+//| .. attribute:: address
+//|
+//| The I2C address of the request.
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_get_address(mp_obj_t self_in) {
+ mp_check_self(MP_OBJ_IS_TYPE(self_in, &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(self_in);
+ return mp_obj_new_int(self->address);
+}
+MP_DEFINE_CONST_PROP_GET(i2cslave_i2c_slave_request_address_obj, i2cslave_i2c_slave_request_get_address);
+
+//| .. attribute:: is_read
+//|
+//| The I2C master is reading from the device.
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_get_is_read(mp_obj_t self_in) {
+ mp_check_self(MP_OBJ_IS_TYPE(self_in, &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(self_in);
+ return mp_obj_new_bool(self->is_read);
+}
+MP_DEFINE_CONST_PROP_GET(i2cslave_i2c_slave_request_is_read_obj, i2cslave_i2c_slave_request_get_is_read);
+
+//| .. attribute:: is_restart
+//|
+//| Is Repeated Start Condition.
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_get_is_restart(mp_obj_t self_in) {
+ mp_check_self(MP_OBJ_IS_TYPE(self_in, &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(self_in);
+ return mp_obj_new_bool(self->is_restart);
+}
+MP_DEFINE_CONST_PROP_GET(i2cslave_i2c_slave_request_is_restart_obj, i2cslave_i2c_slave_request_get_is_restart);
+
+//| .. method:: read(n=-1, ack=True)
+//|
+//| Read data.
+//| If ack=False, the caller is responsible for calling :py:meth:`I2CSlaveRequest.ack`.
+//|
+//| :param int n: Number of bytes to read (negative means all)
+//| :param bool ack: Whether or not to send an ACK after the n'th byte
+//| :return: Bytes read
+//| :rtype: bytearray
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
+ mp_check_self(MP_OBJ_IS_TYPE(pos_args[0], &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
+ enum { ARG_n, ARG_ack };
+ static const mp_arg_t allowed_args[] = {
+ { MP_QSTR_n, MP_ARG_INT, {.u_int = -1} },
+ { MP_QSTR_ack, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} },
+ };
+ mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
+ mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
+
+ if (self->is_read) {
+ mp_raise_OSError(MP_EACCES);
+ }
+
+ int n = args[ARG_n].u_int;
+ if (n == 0) {
+ return mp_obj_new_bytearray(0, NULL);
+ }
+ bool ack = args[ARG_ack].u_bool;
+
+ int i = 0;
+ uint8_t *buffer = NULL;
+ uint64_t timeout_end = common_hal_time_monotonic() + 10 * 1000;
+ while (common_hal_time_monotonic() < timeout_end) {
+ MICROPY_VM_HOOK_LOOP
+ if (mp_hal_is_interrupted()) {
+ break;
+ }
+
+ uint8_t data;
+ int num = common_hal_i2cslave_i2c_slave_read_byte(self->slave, &data);
+ if (num == 0) {
+ break;
+ }
+
+ buffer = m_renew(uint8_t, buffer, i, i + 1);
+ buffer[i++] = data;
+ if (i == n) {
+ if (ack) {
+ common_hal_i2cslave_i2c_slave_ack(self->slave, true);
+ }
+ break;
+ }
+ common_hal_i2cslave_i2c_slave_ack(self->slave, true);
+ }
+
+ return mp_obj_new_bytearray(i, buffer);
+}
+MP_DEFINE_CONST_FUN_OBJ_KW(i2cslave_i2c_slave_request_read_obj, 1, i2cslave_i2c_slave_request_read);
+
+//| .. method:: write(buffer)
+//|
+//| Write the data contained in buffer.
+//|
+//| :param bytearray buffer: Write out the data in this buffer
+//| :return: Number of bytes written
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_write(mp_obj_t self_in, mp_obj_t buf_in) {
+ mp_check_self(MP_OBJ_IS_TYPE(self_in, &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(self_in);
+
+ if (!self->is_read) {
+ mp_raise_OSError(MP_EACCES);
+ }
+
+ mp_buffer_info_t bufinfo;
+ mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ);
+
+ for (size_t i = 0; i < bufinfo.len; i++) {
+ MICROPY_VM_HOOK_LOOP
+ if (mp_hal_is_interrupted()) {
+ break;
+ }
+
+ int num = common_hal_i2cslave_i2c_slave_write_byte(self->slave, ((uint8_t *)(bufinfo.buf))[i]);
+ if (num == 0) {
+ return mp_obj_new_int(i);
+ }
+ }
+
+ return mp_obj_new_int(bufinfo.len);
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_2(i2cslave_i2c_slave_request_write_obj, i2cslave_i2c_slave_request_write);
+
+//| .. method:: ack(ack=True)
+//|
+//| Acknowledge or Not Acknowledge last byte received.
+//| Use together with :py:meth:`I2CSlaveRequest.read` ack=False.
+//|
+//| :param bool ack: Whether to send an ACK or NACK
+//|
+STATIC mp_obj_t i2cslave_i2c_slave_request_ack(uint n_args, const mp_obj_t *args) {
+ mp_check_self(MP_OBJ_IS_TYPE(args[0], &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(args[0]);
+ bool ack = (n_args == 1) ? true : mp_obj_is_true(args[1]);
+
+ if (self->is_read) {
+ mp_raise_OSError(MP_EACCES);
+ }
+
+ common_hal_i2cslave_i2c_slave_ack(self->slave, ack);
+ return mp_const_none;
+}
+MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(i2cslave_i2c_slave_request_ack_obj, 1, 2, i2cslave_i2c_slave_request_ack);
+
+STATIC mp_obj_t i2cslave_i2c_slave_request_close(mp_obj_t self_in) {
+ mp_check_self(MP_OBJ_IS_TYPE(self_in, &i2cslave_i2c_slave_request_type));
+ i2cslave_i2c_slave_request_obj_t *self = MP_OBJ_TO_PTR(self_in);
+
+ common_hal_i2cslave_i2c_slave_close(self->slave);
+ return mp_const_none;
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(i2cslave_i2c_slave_request_close_obj, i2cslave_i2c_slave_request_close);
+
+STATIC const mp_rom_map_elem_t i2cslave_i2c_slave_request_locals_dict_table[] = {
+ { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) },
+ { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&i2cslave_i2c_slave_request___exit___obj) },
+ { MP_ROM_QSTR(MP_QSTR_address), MP_ROM_PTR(&i2cslave_i2c_slave_request_address_obj) },
+ { MP_ROM_QSTR(MP_QSTR_is_read), MP_ROM_PTR(&i2cslave_i2c_slave_request_is_read_obj) },
+ { MP_ROM_QSTR(MP_QSTR_is_restart), MP_ROM_PTR(&i2cslave_i2c_slave_request_is_restart_obj) },
+ { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&i2cslave_i2c_slave_request_read_obj) },
+ { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&i2cslave_i2c_slave_request_write_obj) },
+ { MP_ROM_QSTR(MP_QSTR_ack), MP_ROM_PTR(&i2cslave_i2c_slave_request_ack_obj) },
+ { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&i2cslave_i2c_slave_request_close_obj) },
+};
+
+STATIC MP_DEFINE_CONST_DICT(i2cslave_i2c_slave_request_locals_dict, i2cslave_i2c_slave_request_locals_dict_table);
+
+const mp_obj_type_t i2cslave_i2c_slave_request_type = {
+ { &mp_type_type },
+ .name = MP_QSTR_I2CSlaveRequest,
+ .make_new = i2cslave_i2c_slave_request_make_new,
+ .locals_dict = (mp_obj_dict_t*)&i2cslave_i2c_slave_request_locals_dict,
+};
diff --git a/shared-bindings/i2cslave/I2CSlave.h b/shared-bindings/i2cslave/I2CSlave.h
new file mode 100644
index 000000000..abb761416
--- /dev/null
+++ b/shared-bindings/i2cslave/I2CSlave.h
@@ -0,0 +1,60 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Noralf Trønnes
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_BUSIO_I2C_SLAVE_H
+#define MICROPY_INCLUDED_SHARED_BINDINGS_BUSIO_I2C_SLAVE_H
+
+#include "py/obj.h"
+
+#include "common-hal/microcontroller/Pin.h"
+#include "common-hal/i2cslave/I2CSlave.h"
+
+typedef struct {
+ mp_obj_base_t base;
+ i2cslave_i2c_slave_obj_t *slave;
+ uint16_t address;
+ bool is_read;
+ bool is_restart;
+} i2cslave_i2c_slave_request_obj_t;
+
+extern const mp_obj_type_t i2cslave_i2c_slave_request_type;
+
+extern const mp_obj_type_t i2cslave_i2c_slave_type;
+
+extern void common_hal_i2cslave_i2c_slave_construct(i2cslave_i2c_slave_obj_t *self,
+ const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda,
+ uint8_t *addresses, unsigned int num_addresses, bool smbus);
+extern void common_hal_i2cslave_i2c_slave_deinit(i2cslave_i2c_slave_obj_t *self);
+extern bool common_hal_i2cslave_i2c_slave_deinited(i2cslave_i2c_slave_obj_t *self);
+
+extern int common_hal_i2cslave_i2c_slave_is_addressed(i2cslave_i2c_slave_obj_t *self,
+ uint8_t *address, bool *is_read, bool *is_restart);
+extern int common_hal_i2cslave_i2c_slave_read_byte(i2cslave_i2c_slave_obj_t *self, uint8_t *data);
+extern int common_hal_i2cslave_i2c_slave_write_byte(i2cslave_i2c_slave_obj_t *self, uint8_t data);
+extern void common_hal_i2cslave_i2c_slave_ack(i2cslave_i2c_slave_obj_t *self, bool ack);
+extern void common_hal_i2cslave_i2c_slave_close(i2cslave_i2c_slave_obj_t *self);
+
+#endif // MICROPY_INCLUDED_SHARED_BINDINGS_BUSIO_I2C_SLAVE_H
diff --git a/shared-bindings/i2cslave/__init__.c b/shared-bindings/i2cslave/__init__.c
new file mode 100644
index 000000000..1c692e54e
--- /dev/null
+++ b/shared-bindings/i2cslave/__init__.c
@@ -0,0 +1,117 @@
+/*
+ * This file is part of the MicroPython project, http://micropython.org/
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2018 Noralf Trønnes
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <stdint.h>
+
+#include "py/obj.h"
+#include "py/runtime.h"
+
+#include "shared-bindings/microcontroller/Pin.h"
+//#include "shared-bindings/i2cslave/__init__.h"
+#include "shared-bindings/i2cslave/I2CSlave.h"
+
+#include "py/runtime.h"
+
+//| :mod:`i2cslave` --- Two wire serial protocol slave
+//| ==================================================
+//|
+//| .. module:: i2cslave
+//| :synopsis: Two wire serial protocol slave
+//| :platform: SAMD21, SAMD51
+//|
+//| The `i2cslave` module contains classes to support a I2C slave.
+//|
+//| Classes
+//|
+//| .. toctree::
+//| :maxdepth: 3
+//|
+//| I2CSlave
+//|
+//| Example emulating 2 devices::
+//|
+//| import board
+//| from i2cslave import I2CSlave
+//|
+//| regs = [0] * 16
+//| index = 0
+//|
+//| with I2CSlave(board.SCL, board.SDA, (0x40, 0x41)) as slave:
+//| while True:
+//| r = slave.request()
+//| if not r:
+//| # Maybe do some housekeeping
+//| continue
+//| with r: # Closes the transfer if necessary by sending a NACK or feeding the master dummy bytes
+//| if r.address == 0x40:
+//| if not r.is_read: # Master write which is Slave read
+//| b = r.read(1)
+//| if not b or b[0] > 15:
+//| break
+//| index = b[0]
+//| b = r.read(1)
+//| if b:
+//| regs[index] = b[0]
+//| elif r.is_restart: # Combined transfer: This is the Master read message
+//| n = r.write(bytes([regs[index]]))
+//| #else:
+//| # A read transfer is not supported in this example
+//| # If the Master tries, it will get 0xff byte(s) by the ctx manager (r.close())
+//| elif r.address == 0x41:
+//| if not r.is_read:
+//| b = r.read(1)
+//| if b and b[0] == 0xde:
+//| # do something
+//| pass
+//|
+//| This example sets up an I2C slave that can be accessed from Linux like this::
+//|
+//| $ i2cget -y 1 0x40 0x01
+//| 0x00
+//| $ i2cset -y 1 0x40 0x01 0xaa
+//| $ i2cget -y 1 0x40 0x01
+//| 0xaa
+//|
+//| .. warning::
+//| I2CSlave makes use of clock stretching in order to slow down the master.
+//| Make sure the I2C master supports this.
+//|
+//| Raspberry Pi in particular does not support this with its I2C hw block.
+//| This can be worked around by using the ``i2c-gpio`` bit banging driver.
+//| Since the RPi firmware uses the hw i2c, it's not possible to emulate a HAT eeprom.
+//|
+
+STATIC const mp_rom_map_elem_t i2cslave_module_globals_table[] = {
+ { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_i2cslave) },
+ { MP_ROM_QSTR(MP_QSTR_I2CSlave), MP_ROM_PTR(&i2cslave_i2c_slave_type) },
+};
+
+STATIC MP_DEFINE_CONST_DICT(i2cslave_module_globals, i2cslave_module_globals_table);
+
+const mp_obj_module_t i2cslave_module = {
+ .base = { &mp_type_module },
+ .globals = (mp_obj_dict_t*)&i2cslave_module_globals,
+};
diff --git a/shared-bindings/index.rst b/shared-bindings/index.rst
index bcd6e1d1e..ec7f89f03 100644
--- a/shared-bindings/index.rst
+++ b/shared-bindings/index.rst
@@ -34,6 +34,7 @@ Module Supported Ports
`digitalio` **All Supported**
`gamepad` **SAMD Express, nRF**
`hashlib` **ESP8266**
+`i2cslave` **SAMD Express**
`math` **All Supported**
`microcontroller` **All Supported**
`multiterminal` **ESP8266**