i2c.c 23 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * 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.
 */

27
28
29
#include <stdio.h>
#include <string.h>

30
31
#include "py/nlr.h"
#include "py/runtime.h"
32
33
#include "pin.h"
#include "genhdr/pins.h"
34
#include "bufhelper.h"
35
#include "i2c.h"
36
#include MICROPY_HAL_H
37

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/// \moduleref pyb
/// \class I2C - a two-wire serial protocol
///
/// I2C is a two-wire protocol for communicating between devices.  At the physical
/// level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
///
/// I2C objects are created attached to a specific bus.  They can be initialised
/// when created, or initialised later on:
///
///     from pyb import I2C
///
///     i2c = I2C(1)                         # create on bus 1
///     i2c = I2C(1, I2C.MASTER)             # create and init as a master
///     i2c.init(I2C.MASTER, baudrate=20000) # init as a master
///     i2c.init(I2C.SLAVE, addr=0x42)       # init as a slave with given address
///     i2c.deinit()                         # turn off the peripheral
///
/// Printing the i2c object gives you information about its configuration.
///
/// Basic methods for slave are send and recv:
///
///     i2c.send('abc')      # send 3 bytes
///     i2c.send(0x42)       # send a single byte, given by the number
///     data = i2c.recv(3)   # receive 3 bytes
///
/// To receive inplace, first create a bytearray:
///
///     data = bytearray(3)  # create a buffer
///     i2c.recv(data)       # receive 3 bytes, writing them into data
///
/// You can specify a timeout (in ms):
///
///     i2c.send(b'123', timeout=2000)   # timout after 2 seconds
///
/// A master must specify the recipient's address:
///
///     i2c.init(I2C.MASTER)
///     i2c.send('123', 0x42)        # send 3 bytes to slave with address 0x42
///     i2c.send(b'456', addr=0x42)  # keyword for address
///
/// Master also has other methods:
///
///     i2c.is_ready(0x42)           # check if slave 0x42 is ready
///     i2c.scan()                   # scan for slaves on the bus, returning
///                                  #   a list of valid addresses
///     i2c.mem_read(3, 0x42, 2)     # read 3 bytes from memory of slave 0x42,
///                                  #   starting at address 2 in the slave
///     i2c.mem_write('abc', 0x42, 2, timeout=1000)
86

87
88
89
#define PYB_I2C_MASTER (0)
#define PYB_I2C_SLAVE  (1)

90
#if defined(MICROPY_HW_I2C1_SCL)
91
I2C_HandleTypeDef I2CHandle1 = {.Instance = NULL};
92
#endif
93
#if defined(MICROPY_HW_I2C2_SCL)
94
I2C_HandleTypeDef I2CHandle2 = {.Instance = NULL};
95
96
97
98
#endif
#if defined(MICROPY_HW_I2C3_SCL)
I2C_HandleTypeDef I2CHandle3 = {.Instance = NULL};
#endif
99

100
101
void i2c_init0(void) {
    // reset the I2C1 handles
102
    #if defined(MICROPY_HW_I2C1_SCL)
103
104
    memset(&I2CHandle1, 0, sizeof(I2C_HandleTypeDef));
    I2CHandle1.Instance = I2C1;
105
106
    #endif
    #if defined(MICROPY_HW_I2C2_SCL)
107
108
    memset(&I2CHandle2, 0, sizeof(I2C_HandleTypeDef));
    I2CHandle2.Instance = I2C2;
109
110
111
112
113
    #endif
    #if defined(MICROPY_HW_I2C3_SCL)
    memset(&I2CHandle3, 0, sizeof(I2C_HandleTypeDef));
    I2CHandle3.Instance = I2C3;
    #endif
114
115
}

116
void i2c_init(I2C_HandleTypeDef *i2c) {
117
    // init the GPIO lines
118
    GPIO_InitTypeDef GPIO_InitStructure;
119
120
121
122
    GPIO_InitStructure.Mode = GPIO_MODE_AF_OD;
    GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
    GPIO_InitStructure.Pull = GPIO_NOPULL; // have external pull-up resistors on both lines

123
    const pin_obj_t *pins[2];
124
    if (0) {
125
    #if defined(MICROPY_HW_I2C1_SCL)
126
    } else if (i2c == &I2CHandle1) {
127
128
        pins[0] = &MICROPY_HW_I2C1_SCL;
        pins[1] = &MICROPY_HW_I2C1_SDA;
129
130
        GPIO_InitStructure.Alternate = GPIO_AF4_I2C1;
        __I2C1_CLK_ENABLE();
131
132
    #endif
    #if defined(MICROPY_HW_I2C2_SCL)
133
    } else if (i2c == &I2CHandle2) {
134
135
        pins[0] = &MICROPY_HW_I2C2_SCL;
        pins[1] = &MICROPY_HW_I2C2_SDA;
136
137
        GPIO_InitStructure.Alternate = GPIO_AF4_I2C2;
        __I2C2_CLK_ENABLE();
138
139
140
141
142
143
144
145
    #endif
    #if defined(MICROPY_HW_I2C3_SCL)
    } else if (i2c == &I2CHandle3) {
        pins[0] = &MICROPY_HW_I2C3_SCL;
        pins[1] = &MICROPY_HW_I2C3_SDA;
        GPIO_InitStructure.Alternate = GPIO_AF4_I2C3;
        __I2C3_CLK_ENABLE();
    #endif
146
147
148
    } else {
        // I2C does not exist for this board (shouldn't get here, should be checked by caller)
        return;
149
150
    }

151
152
153
154
155
156
    // init the GPIO lines
    for (uint i = 0; i < 2; i++) {
        GPIO_InitStructure.Pin = pins[i]->pin_mask;
        HAL_GPIO_Init(pins[i]->gpio, &GPIO_InitStructure);
    }

157
    // init the I2C device
158
    if (HAL_I2C_Init(i2c) != HAL_OK) {
159
        // init error
160
161
        // TODO should raise an exception, but this function is not necessarily going to be
        // called via Python, so may not be properly wrapped in an NLR handler
162
        printf("OSError: HAL_I2C_Init failed\n");
163
164
165
166
        return;
    }
}

167
168
169
void i2c_deinit(I2C_HandleTypeDef *i2c) {
    HAL_I2C_DeInit(i2c);
    if (0) {
170
    #if defined(MICROPY_HW_I2C1_SCL)
171
172
173
174
    } else if (i2c->Instance == I2C1) {
        __I2C1_FORCE_RESET();
        __I2C1_RELEASE_RESET();
        __I2C1_CLK_DISABLE();
175
176
    #endif
    #if defined(MICROPY_HW_I2C2_SCL)
177
178
179
180
    } else if (i2c->Instance == I2C2) {
        __I2C2_FORCE_RESET();
        __I2C2_RELEASE_RESET();
        __I2C2_CLK_DISABLE();
181
182
183
184
185
186
187
    #endif
    #if defined(MICROPY_HW_I2C3_SCL)
    } else if (i2c->Instance == I2C3) {
        __I2C3_FORCE_RESET();
        __I2C3_RELEASE_RESET();
        __I2C3_CLK_DISABLE();
    #endif
188
189
190
    }
}

191
192
193
194
195
/******************************************************************************/
/* Micro Python bindings                                                      */

typedef struct _pyb_i2c_obj_t {
    mp_obj_base_t base;
196
    I2C_HandleTypeDef *i2c;
197
198
} pyb_i2c_obj_t;

199
200
STATIC inline bool in_master_mode(pyb_i2c_obj_t *self) { return self->i2c->Init.OwnAddress1 == PYB_I2C_MASTER_ADDRESS; }

201
STATIC const pyb_i2c_obj_t pyb_i2c_obj[] = {
202
    #if defined(MICROPY_HW_I2C1_SCL)
203
    {{&pyb_i2c_type}, &I2CHandle1},
204
205
    #else
    {{&pyb_i2c_type}, NULL},
206
207
208
    #endif
    #if defined(MICROPY_HW_I2C2_SCL)
    {{&pyb_i2c_type}, &I2CHandle2},
209
210
    #else
    {{&pyb_i2c_type}, NULL},
211
212
213
    #endif
    #if defined(MICROPY_HW_I2C3_SCL)
    {{&pyb_i2c_type}, &I2CHandle3},
214
215
    #else
    {{&pyb_i2c_type}, NULL},
216
    #endif
217
};
218

219
STATIC void pyb_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
220
221
    pyb_i2c_obj_t *self = self_in;

222
223
224
225
226
227
228
229
230
231
232
    uint i2c_num = 0;
    if (0) { }
    #if defined(MICROPY_HW_I2C1_SCL)
    else if (self->i2c->Instance == I2C1) { i2c_num = 1; }
    #endif
    #if defined(MICROPY_HW_I2C2_SCL)
    else if (self->i2c->Instance == I2C2) { i2c_num = 2; }
    #endif
    #if defined(MICROPY_HW_I2C3_SCL)
    else if (self->i2c->Instance == I2C3) { i2c_num = 3; }
    #endif
233
234

    if (self->i2c->State == HAL_I2C_STATE_RESET) {
235
        mp_printf(print, "I2C(%u)", i2c_num);
236
237
    } else {
        if (in_master_mode(self)) {
238
            mp_printf(print, "I2C(%u, I2C.MASTER, baudrate=%u)", i2c_num, self->i2c->Init.ClockSpeed);
239
        } else {
240
            mp_printf(print, "I2C(%u, I2C.SLAVE, addr=0x%02x)", i2c_num, (self->i2c->Instance->OAR1 >> 1) & 0x7f);
241
242
243
244
        }
    }
}

245
246
247
248
249
250
251
252
/// \method init(mode, *, addr=0x12, baudrate=400000, gencall=False)
///
/// Initialise the I2C bus with the given parameters:
///
///   - `mode` must be either `I2C.MASTER` or `I2C.SLAVE`
///   - `addr` is the 7-bit address (only sensible for a slave)
///   - `baudrate` is the SCL clock rate (only sensible for a master)
///   - `gencall` is whether to support general call mode
253
254
255
256
257
STATIC const mp_arg_t pyb_i2c_init_args[] = {
    { MP_QSTR_mode,     MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
    { MP_QSTR_addr,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0x12} },
    { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 400000} },
    { MP_QSTR_gencall,  MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
258
};
259
#define PYB_I2C_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_init_args)
260

261
STATIC mp_obj_t pyb_i2c_init_helper(const pyb_i2c_obj_t *self, mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
262
    // parse args
263
264
    mp_arg_val_t vals[PYB_I2C_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args, args, kw_args, PYB_I2C_INIT_NUM_ARGS, pyb_i2c_init_args, vals);
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

    // set the I2C configuration values
    I2C_InitTypeDef *init = &self->i2c->Init;

    if (vals[0].u_int == PYB_I2C_MASTER) {
        // use a special address to indicate we are a master
        init->OwnAddress1 = PYB_I2C_MASTER_ADDRESS;
    } else {
        init->OwnAddress1 = (vals[1].u_int << 1) & 0xfe;
    }

    init->AddressingMode  = I2C_ADDRESSINGMODE_7BIT;
    init->ClockSpeed      = MIN(vals[2].u_int, 400000);
    init->DualAddressMode = I2C_DUALADDRESS_DISABLED;
    init->DutyCycle       = I2C_DUTYCYCLE_16_9;
    init->GeneralCallMode = vals[3].u_bool ? I2C_GENERALCALL_ENABLED : I2C_GENERALCALL_DISABLED;
    init->NoStretchMode   = I2C_NOSTRETCH_DISABLED;
    init->OwnAddress2     = 0xfe; // unused

    // init the I2C bus
    i2c_init(self->i2c);

    return mp_const_none;
}

290
291
292
293
294
295
296
/// \classmethod \constructor(bus, ...)
///
/// Construct an I2C object on the given bus.  `bus` can be 1 or 2.
/// With no additional parameters, the I2C object is created but not
/// initialised (it has the settings from the last initialisation of
/// the bus, if any).  If extra arguments are given, the bus is initialised.
/// See `init` for parameters of initialisation.
297
298
299
300
301
///
/// The physical pins of the I2C busses are:
///
///   - `I2C(1)` is on the X position: `(SCL, SDA) = (X9, X10) = (PB6, PB7)`
///   - `I2C(2)` is on the Y position: `(SCL, SDA) = (Y9, Y10) = (PB10, PB11)`
302
STATIC mp_obj_t pyb_i2c_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
303
    // check arguments
304
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
305

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    // work out i2c bus
    int i2c_id = 0;
    if (MP_OBJ_IS_STR(args[0])) {
        const char *port = mp_obj_str_get_str(args[0]);
        if (0) {
        #ifdef MICROPY_HW_I2C1_NAME
        } else if (strcmp(port, MICROPY_HW_I2C1_NAME) == 0) {
            i2c_id = 1;
        #endif
        #ifdef MICROPY_HW_I2C2_NAME
        } else if (strcmp(port, MICROPY_HW_I2C2_NAME) == 0) {
            i2c_id = 2;
        #endif
        #ifdef MICROPY_HW_I2C3_NAME
        } else if (strcmp(port, MICROPY_HW_I2C3_NAME) == 0) {
            i2c_id = 3;
        #endif
        } else {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
                "I2C(%s) does not exist", port));
        }
    } else {
        i2c_id = mp_obj_get_int(args[0]);
        if (i2c_id < 1 || i2c_id > MP_ARRAY_SIZE(pyb_i2c_obj)
330
            || pyb_i2c_obj[i2c_id - 1].i2c == NULL) {
331
332
333
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
                "I2C(%d) does not exist", i2c_id));
        }
334
335
    }

336
    // get I2C object
337
    const pyb_i2c_obj_t *i2c_obj = &pyb_i2c_obj[i2c_id - 1];
338

339
340
341
342
343
344
    if (n_args > 1 || n_kw > 0) {
        // start the peripheral
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        pyb_i2c_init_helper(i2c_obj, n_args - 1, args + 1, &kw_args);
    }
345

346
    return (mp_obj_t)i2c_obj;
347
348
}

349
STATIC mp_obj_t pyb_i2c_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
350
351
352
353
    return pyb_i2c_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_init_obj, 1, pyb_i2c_init);

354
355
/// \method deinit()
/// Turn off the I2C bus.
356
357
358
359
360
361
362
STATIC mp_obj_t pyb_i2c_deinit(mp_obj_t self_in) {
    pyb_i2c_obj_t *self = self_in;
    i2c_deinit(self->i2c);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_deinit_obj, pyb_i2c_deinit);

363
364
/// \method is_ready(addr)
/// Check if an I2C device responds to the given address.  Only valid when in master mode.
365
366
STATIC mp_obj_t pyb_i2c_is_ready(mp_obj_t self_in, mp_obj_t i2c_addr_o) {
    pyb_i2c_obj_t *self = self_in;
367
368
369
370
371

    if (!in_master_mode(self)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "I2C must be a master"));
    }

372
    mp_uint_t i2c_addr = mp_obj_get_int(i2c_addr_o) << 1;
373
374

    for (int i = 0; i < 10; i++) {
375
        HAL_StatusTypeDef status = HAL_I2C_IsDeviceReady(self->i2c, i2c_addr, 10, 200);
376
377
378
379
380
381
382
383
384
        if (status == HAL_OK) {
            return mp_const_true;
        }
    }

    return mp_const_false;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_i2c_is_ready_obj, pyb_i2c_is_ready);

385
386
387
/// \method scan()
/// Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond.
/// Only valid when in master mode.
388
389
390
STATIC mp_obj_t pyb_i2c_scan(mp_obj_t self_in) {
    pyb_i2c_obj_t *self = self_in;

391
392
393
394
    if (!in_master_mode(self)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "I2C must be a master"));
    }

395
396
397
398
    mp_obj_t list = mp_obj_new_list(0, NULL);

    for (uint addr = 1; addr <= 127; addr++) {
        for (int i = 0; i < 10; i++) {
399
            HAL_StatusTypeDef status = HAL_I2C_IsDeviceReady(self->i2c, addr << 1, 10, 200);
400
401
402
403
404
405
406
407
408
409
410
            if (status == HAL_OK) {
                mp_obj_list_append(list, mp_obj_new_int(addr));
                break;
            }
        }
    }

    return list;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_scan_obj, pyb_i2c_scan);

411
412
413
414
415
416
417
418
/// \method send(send, addr=0x00, timeout=5000)
/// Send data on the bus:
///
///   - `send` is the data to send (an integer to send, or a buffer object)
///   - `addr` is the address to send to (only required in master mode)
///   - `timeout` is the timeout in milliseconds to wait for the send
///
/// Return value: `None`.
419
420
421
422
STATIC const mp_arg_t pyb_i2c_send_args[] = {
    { MP_QSTR_send,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_addr,    MP_ARG_INT, {.u_int = PYB_I2C_MASTER_ADDRESS} },
    { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
423
};
424
#define PYB_I2C_SEND_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_send_args)
425

426
STATIC mp_obj_t pyb_i2c_send(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
427
428
429
    pyb_i2c_obj_t *self = args[0];

    // parse args
430
431
    mp_arg_val_t vals[PYB_I2C_SEND_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_SEND_NUM_ARGS, pyb_i2c_send_args, vals);
432
433
434
435
436
437
438
439
440
441
442
443

    // get the buffer to send from
    mp_buffer_info_t bufinfo;
    uint8_t data[1];
    pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);

    // send the data
    HAL_StatusTypeDef status;
    if (in_master_mode(self)) {
        if (vals[1].u_int == PYB_I2C_MASTER_ADDRESS) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "addr argument required"));
        }
444
        mp_uint_t i2c_addr = vals[1].u_int << 1;
445
446
447
448
        status = HAL_I2C_Master_Transmit(self->i2c, i2c_addr, bufinfo.buf, bufinfo.len, vals[2].u_int);
    } else {
        status = HAL_I2C_Slave_Transmit(self->i2c, bufinfo.buf, bufinfo.len, vals[2].u_int);
    }
449
450

    if (status != HAL_OK) {
451
        mp_hal_raise(status);
452
453
    }

454
    return mp_const_none;
455
}
456
457
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_send_obj, 1, pyb_i2c_send);

458
/// \method recv(recv, addr=0x00, timeout=5000)
459
460
461
462
463
464
465
466
467
468
///
/// Receive data on the bus:
///
///   - `recv` can be an integer, which is the number of bytes to receive,
///     or a mutable buffer, which will be filled with received bytes
///   - `addr` is the address to receive from (only required in master mode)
///   - `timeout` is the timeout in milliseconds to wait for the receive
///
/// Return value: if `recv` is an integer then a new buffer of the bytes received,
/// otherwise the same buffer that was passed in to `recv`.
469
470
471
472
STATIC const mp_arg_t pyb_i2c_recv_args[] = {
    { MP_QSTR_recv,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_addr,    MP_ARG_INT, {.u_int = PYB_I2C_MASTER_ADDRESS} },
    { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
473
};
474
#define PYB_I2C_RECV_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_recv_args)
475

476
STATIC mp_obj_t pyb_i2c_recv(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
477
    pyb_i2c_obj_t *self = args[0];
478

479
    // parse args
480
481
    mp_arg_val_t vals[PYB_I2C_RECV_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_RECV_NUM_ARGS, pyb_i2c_recv_args, vals);
482
483

    // get the buffer to receive into
484
485
    vstr_t vstr;
    mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr);
486
487

    // receive the data
488
    HAL_StatusTypeDef status;
489
490
491
492
    if (in_master_mode(self)) {
        if (vals[1].u_int == PYB_I2C_MASTER_ADDRESS) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "addr argument required"));
        }
493
        mp_uint_t i2c_addr = vals[1].u_int << 1;
494
        status = HAL_I2C_Master_Receive(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len, vals[2].u_int);
495
    } else {
496
        status = HAL_I2C_Slave_Receive(self->i2c, (uint8_t*)vstr.buf, vstr.len, vals[2].u_int);
497
498
499
    }

    if (status != HAL_OK) {
500
        mp_hal_raise(status);
501
502
    }

503
    // return the received data
504
505
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
506
    } else {
507
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
508
    }
509
}
510
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_recv_obj, 1, pyb_i2c_recv);
511

512
/// \method mem_read(data, addr, memaddr, timeout=5000, addr_size=8)
513
514
515
516
517
518
519
///
/// Read from the memory of an I2C device:
///
///   - `data` can be an integer or a buffer to read into
///   - `addr` is the I2C device address
///   - `memaddr` is the memory location within the I2C device
///   - `timeout` is the timeout in milliseconds to wait for the read
520
///   - `addr_size` selects width of memaddr: 8 or 16 bits
521
522
523
///
/// Returns the read data.
/// This is only valid in master mode.
524
525
526
527
528
STATIC const mp_arg_t pyb_i2c_mem_read_args[] = {
    { MP_QSTR_data,    MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
    { MP_QSTR_addr,    MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
    { MP_QSTR_memaddr, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
    { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 5000} },
529
    { MP_QSTR_addr_size, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} },
530
};
531
#define PYB_I2C_MEM_READ_NUM_ARGS MP_ARRAY_SIZE(pyb_i2c_mem_read_args)
532

533
STATIC mp_obj_t pyb_i2c_mem_read(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
534
535
    pyb_i2c_obj_t *self = args[0];

536
537
538
539
540
    if (!in_master_mode(self)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "I2C must be a master"));
    }

    // parse args
541
542
    mp_arg_val_t vals[PYB_I2C_MEM_READ_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_MEM_READ_NUM_ARGS, pyb_i2c_mem_read_args, vals);
543
544

    // get the buffer to read into
545
546
    vstr_t vstr;
    mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr);
547

548
    // get the addresses
549
550
    mp_uint_t i2c_addr = vals[1].u_int << 1;
    mp_uint_t mem_addr = vals[2].u_int;
551
    // determine width of mem_addr; default is 8 bits, entering any other value gives 16 bit width
552
    mp_uint_t mem_addr_size = I2C_MEMADD_SIZE_8BIT;
553
    if (vals[4].u_int != 8) {
554
        mem_addr_size = I2C_MEMADD_SIZE_16BIT;
555
    }
556

557
    HAL_StatusTypeDef status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len, vals[3].u_int);
558
559

    if (status != HAL_OK) {
560
        mp_hal_raise(status);
561
562
    }

563
    // return the read data
564
565
    if (o_ret != MP_OBJ_NULL) {
        return o_ret;
566
    } else {
567
        return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
568
    }
569
}
570
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_mem_read_obj, 1, pyb_i2c_mem_read);
571

572
/// \method mem_write(data, addr, memaddr, timeout=5000, addr_size=8)
573
574
575
576
577
578
579
///
/// Write to the memory of an I2C device:
///
///   - `data` can be an integer or a buffer to write from
///   - `addr` is the I2C device address
///   - `memaddr` is the memory location within the I2C device
///   - `timeout` is the timeout in milliseconds to wait for the write
580
///   - `addr_size` selects width of memaddr: 8 or 16 bits
581
582
583
///
/// Returns `None`.
/// This is only valid in master mode.
584
STATIC mp_obj_t pyb_i2c_mem_write(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
585
    pyb_i2c_obj_t *self = args[0];
586
587
588

    if (!in_master_mode(self)) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "I2C must be a master"));
589
590
    }

591
    // parse args (same as mem_read)
592
593
    mp_arg_val_t vals[PYB_I2C_MEM_READ_NUM_ARGS];
    mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_MEM_READ_NUM_ARGS, pyb_i2c_mem_read_args, vals);
594
595
596
597
598
599
600

    // get the buffer to write from
    mp_buffer_info_t bufinfo;
    uint8_t data[1];
    pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data);

    // get the addresses
601
602
    mp_uint_t i2c_addr = vals[1].u_int << 1;
    mp_uint_t mem_addr = vals[2].u_int;
603
    // determine width of mem_addr; default is 8 bits, entering any other value gives 16 bit width
604
    mp_uint_t mem_addr_size = I2C_MEMADD_SIZE_8BIT;
605
    if (vals[4].u_int != 8) {
606
        mem_addr_size = I2C_MEMADD_SIZE_16BIT;
607
    }
608

609
    HAL_StatusTypeDef status = HAL_I2C_Mem_Write(self->i2c, i2c_addr, mem_addr, mem_addr_size, bufinfo.buf, bufinfo.len, vals[3].u_int);
610
611

    if (status != HAL_OK) {
612
        mp_hal_raise(status);
613
614
615
616
    }

    return mp_const_none;
}
617
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_mem_write_obj, 1, pyb_i2c_mem_write);
618

619
STATIC const mp_map_elem_t pyb_i2c_locals_dict_table[] = {
620
621
622
    // instance methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_i2c_init_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_i2c_deinit_obj },
623
    { MP_OBJ_NEW_QSTR(MP_QSTR_is_ready), (mp_obj_t)&pyb_i2c_is_ready_obj },
624
    { MP_OBJ_NEW_QSTR(MP_QSTR_scan), (mp_obj_t)&pyb_i2c_scan_obj },
625
626
    { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&pyb_i2c_send_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&pyb_i2c_recv_obj },
627
628
    { MP_OBJ_NEW_QSTR(MP_QSTR_mem_read), (mp_obj_t)&pyb_i2c_mem_read_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_mem_write), (mp_obj_t)&pyb_i2c_mem_write_obj },
629
630

    // class constants
631
632
    /// \constant MASTER - for initialising the bus to master mode
    /// \constant SLAVE - for initialising the bus to slave mode
633
634
    { MP_OBJ_NEW_QSTR(MP_QSTR_MASTER),       MP_OBJ_NEW_SMALL_INT(PYB_I2C_MASTER) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_SLAVE),        MP_OBJ_NEW_SMALL_INT(PYB_I2C_SLAVE) },
635
636
};

637
638
STATIC MP_DEFINE_CONST_DICT(pyb_i2c_locals_dict, pyb_i2c_locals_dict_table);

639
640
641
const mp_obj_type_t pyb_i2c_type = {
    { &mp_type_type },
    .name = MP_QSTR_I2C,
642
    .print = pyb_i2c_print,
643
    .make_new = pyb_i2c_make_new,
644
    .locals_dict = (mp_obj_t)&pyb_i2c_locals_dict,
645
};