1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2021 Jim Mussared
7  * Copyright (c) 2021 Damien P. George
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "py/runtime.h"
29 #include "py/mphal.h"
30 #include "extmod/machine_bitstream.h"
31 
32 #if MICROPY_PY_MACHINE_BITSTREAM
33 
34 // Timing is a 4-tuple of (high_time_0, low_time_0, high_time_1, low_time_1)
35 // suitable for driving WS2812.
36 #define MICROPY_MACHINE_BITSTREAM_TYPE_HIGH_LOW (0)
37 
38 // machine.bitstream(pin, encoding, (timing), bytes)
machine_bitstream_(size_t n_args,const mp_obj_t * args)39 STATIC mp_obj_t machine_bitstream_(size_t n_args, const mp_obj_t *args) {
40     mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(args[0]);
41     int encoding = mp_obj_get_int(args[1]);
42 
43     mp_buffer_info_t bufinfo;
44     mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ);
45 
46     switch (encoding) {
47         case MICROPY_MACHINE_BITSTREAM_TYPE_HIGH_LOW: {
48             uint32_t timing_ns[4];
49             mp_obj_t *timing;
50             mp_obj_get_array_fixed_n(args[2], 4, &timing);
51             for (size_t i = 0; i < 4; ++i) {
52                 timing_ns[i] = mp_obj_get_int(timing[i]);
53             }
54             machine_bitstream_high_low(pin, timing_ns, bufinfo.buf, bufinfo.len);
55             break;
56         }
57         default:
58             mp_raise_ValueError(MP_ERROR_TEXT("encoding"));
59     }
60 
61     return mp_const_none;
62 }
63 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_bitstream_obj, 4, 4, machine_bitstream_);
64 
65 #endif // MICROPY_PY_MACHINE_BITSTREAM
66