1 #include <stdint.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 
6 #include "py/lexer.h"
7 #include "py/runtime.h"
8 #include "py/stackctrl.h"
9 #include "py/gc.h"
10 #include "py/mphal.h"
11 #include "gccollect.h"
12 #include "shared/readline/readline.h"
13 #include "shared/runtime/gchelper.h"
14 #include "shared/runtime/pyexec.h"
15 #include "lexermemzip.h"
16 
17 #include "Arduino.h"
18 
19 #include "servo.h"
20 #include "led.h"
21 #include "uart.h"
22 #include "pin.h"
23 
24 extern uint32_t _heap_start;
25 
flash_error(int n)26 void flash_error(int n) {
27     for (int i = 0; i < n; i++) {
28         led_state(PYB_LED_BUILTIN, 1);
29         delay(250);
30         led_state(PYB_LED_BUILTIN, 0);
31         delay(250);
32     }
33 }
34 
__fatal_error(const char * msg)35 void NORETURN __fatal_error(const char *msg) {
36     for (volatile uint delay = 0; delay < 10000000; delay++) {
37     }
38     led_state(1, 1);
39     led_state(2, 1);
40     led_state(3, 1);
41     led_state(4, 1);
42     mp_hal_stdout_tx_strn("\nFATAL ERROR:\n", 14);
43     mp_hal_stdout_tx_strn(msg, strlen(msg));
44     for (uint i = 0;;) {
45         led_toggle(((i++) & 3) + 1);
46         for (volatile uint delay = 0; delay < 10000000; delay++) {
47         }
48         if (i >= 16) {
49             // to conserve power
50             __WFI();
51         }
52     }
53 }
54 
nlr_jump_fail(void * val)55 void nlr_jump_fail(void *val) {
56     printf("FATAL: uncaught exception %p\n", val);
57     __fatal_error("");
58 }
59 
__assert_func(const char * file,int line,const char * func,const char * expr)60 void __assert_func(const char *file, int line, const char *func, const char *expr) {
61 
62     printf("Assertion failed: %s, file %s, line %d\n", expr, file, line);
63     __fatal_error("");
64 }
65 
pyb_analog_read(mp_obj_t pin_obj)66 mp_obj_t pyb_analog_read(mp_obj_t pin_obj) {
67     uint pin = mp_obj_get_int(pin_obj);
68     int val = analogRead(pin);
69     return MP_OBJ_NEW_SMALL_INT(val);
70 }
71 
pyb_analog_write(mp_obj_t pin_obj,mp_obj_t val_obj)72 mp_obj_t pyb_analog_write(mp_obj_t pin_obj, mp_obj_t val_obj) {
73     uint pin = mp_obj_get_int(pin_obj);
74     int val = mp_obj_get_int(val_obj);
75     analogWrite(pin, val);
76     return mp_const_none;
77 }
78 
pyb_analog_write_resolution(mp_obj_t res_obj)79 mp_obj_t pyb_analog_write_resolution(mp_obj_t res_obj) {
80     int res = mp_obj_get_int(res_obj);
81     analogWriteResolution(res);
82     return mp_const_none;
83 }
84 
pyb_analog_write_frequency(mp_obj_t pin_obj,mp_obj_t freq_obj)85 mp_obj_t pyb_analog_write_frequency(mp_obj_t pin_obj, mp_obj_t freq_obj) {
86     uint pin = mp_obj_get_int(pin_obj);
87     int freq = mp_obj_get_int(freq_obj);
88     analogWriteFrequency(pin, freq);
89     return mp_const_none;
90 }
91 
92 #if 0
93 // get lots of info about the board
94 static mp_obj_t pyb_info(void) {
95     // get and print unique id; 96 bits
96     {
97         byte *id = (byte *)0x40048058;
98         printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]);
99     }
100 
101     // get and print clock speeds
102     printf("CPU=%u\nBUS=%u\nMEM=%u\n", F_CPU, F_BUS, F_MEM);
103 
104     // to print info about memory
105     {
106         printf("_sdata=%p\n", &_sdata);
107         printf("_edata=%p\n", &_edata);
108         printf("_sbss=%p\n", &_sbss);
109         printf("_ebss=%p\n", &_ebss);
110         printf("_estack=%p\n", &_estack);
111         printf("_etext=%p\n", &_etext);
112         printf("_heap_start=%p\n", &_heap_start);
113     }
114 
115     // GC info
116     {
117         gc_info_t info;
118         gc_info(&info);
119         printf("GC:\n");
120         printf("  %u total\n", info.total);
121         printf("  %u used %u free\n", info.used, info.free);
122         printf("  1=%u 2=%u m=%u\n", info.num_1block, info.num_2block, info.max_block);
123     }
124 
125     #if 0
126     // free space on flash
127     {
128         DWORD nclst;
129         FATFS *fatfs;
130         f_getfree("0:", &nclst, &fatfs);
131         printf("LFS free: %u bytes\n", (uint)(nclst * fatfs->csize * 512));
132     }
133     #endif
134 
135     return mp_const_none;
136 }
137 
138 #endif
139 
140 #define RAM_START (0x1FFF8000) // fixed for chip
141 #define HEAP_END  (0x20006000) // tunable
142 #define RAM_END   (0x20008000) // fixed for chip
143 
144 #if 0
145 
146 void gc_helper_get_regs_and_clean_stack(mp_uint_t *regs, mp_uint_t heap_end);
147 
148 mp_obj_t pyb_gc(void) {
149     gc_collect();
150     return mp_const_none;
151 }
152 
153 mp_obj_t pyb_gpio(int n_args, mp_obj_t *args) {
154     // assert(1 <= n_args && n_args <= 2);
155 
156     uint pin = mp_obj_get_int(args[0]);
157     if (pin > CORE_NUM_DIGITAL) {
158         goto pin_error;
159     }
160 
161     if (n_args == 1) {
162         // get pin
163         pinMode(pin, INPUT);
164         return MP_OBJ_NEW_SMALL_INT(digitalRead(pin));
165     }
166 
167     // set pin
168     pinMode(pin, OUTPUT);
169     digitalWrite(pin, mp_obj_is_true(args[1]));
170     return mp_const_none;
171 
172 pin_error:
173     mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("pin %d does not exist"), pin);
174 }
175 
176 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_gpio_obj, 1, 2, pyb_gpio);
177 
178 #if 0
179 mp_obj_t pyb_hid_send_report(mp_obj_t arg) {
180     mp_obj_t *items = mp_obj_get_array_fixed_n(arg, 4);
181     uint8_t data[4];
182     data[0] = mp_obj_get_int(items[0]);
183     data[1] = mp_obj_get_int(items[1]);
184     data[2] = mp_obj_get_int(items[2]);
185     data[3] = mp_obj_get_int(items[3]);
186     usb_hid_send_report(data);
187     return mp_const_none;
188 }
189 #endif
190 
191 #endif // 0
192 
193 STATIC mp_obj_t pyb_config_source_dir = MP_OBJ_NULL;
194 STATIC mp_obj_t pyb_config_main = MP_OBJ_NULL;
195 STATIC mp_obj_t pyb_config_usb_mode = MP_OBJ_NULL;
196 
pyb_source_dir(mp_obj_t source_dir)197 mp_obj_t pyb_source_dir(mp_obj_t source_dir) {
198     if (mp_obj_is_str(source_dir)) {
199         pyb_config_source_dir = source_dir;
200     }
201     return mp_const_none;
202 }
203 
204 MP_DEFINE_CONST_FUN_OBJ_1(pyb_source_dir_obj, pyb_source_dir);
205 
pyb_main(mp_obj_t main)206 mp_obj_t pyb_main(mp_obj_t main) {
207     if (mp_obj_is_str(main)) {
208         pyb_config_main = main;
209     }
210     return mp_const_none;
211 }
212 
213 MP_DEFINE_CONST_FUN_OBJ_1(pyb_main_obj, pyb_main);
214 
pyb_usb_mode(mp_obj_t usb_mode)215 STATIC mp_obj_t pyb_usb_mode(mp_obj_t usb_mode) {
216     if (mp_obj_is_str(usb_mode)) {
217         pyb_config_usb_mode = usb_mode;
218     }
219     return mp_const_none;
220 }
221 
222 MP_DEFINE_CONST_FUN_OBJ_1(pyb_usb_mode_obj, pyb_usb_mode);
223 
224 #if 0
225 
226 mp_obj_t pyb_delay(mp_obj_t count) {
227     delay(mp_obj_get_int(count));
228     return mp_const_none;
229 }
230 
231 mp_obj_t pyb_led(mp_obj_t state) {
232     led_state(PYB_LED_BUILTIN, mp_obj_is_true(state));
233     return state;
234 }
235 
236 #endif  // 0
237 
238 #if 0
239 char *strdup(const char *str) {
240     uint32_t len = strlen(str);
241     char *s2 = m_new(char, len + 1);
242     memcpy(s2, str, len);
243     s2[len] = 0;
244     return s2;
245 }
246 #endif
247 
main(void)248 int main(void) {
249     // TODO: Put this in a more common initialization function.
250     // Turn on STKALIGN which keeps the stack 8-byte aligned for interrupts
251     // (per EABI)
252     #define SCB_CCR_STKALIGN (1 << 9)
253     SCB_CCR |= SCB_CCR_STKALIGN;
254 
255     mp_stack_ctrl_init();
256     mp_stack_set_limit(10240);
257 
258     pinMode(LED_BUILTIN, OUTPUT);
259     led_init();
260 
261 //    int first_soft_reset = true;
262 
263 soft_reset:
264 
265     led_state(PYB_LED_BUILTIN, 1);
266 
267     // GC init
268     gc_init(&_heap_start, (void *)HEAP_END);
269 
270     // MicroPython init
271     mp_init();
272     mp_obj_list_init(mp_sys_path, 0);
273     mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script)
274     mp_obj_list_init(mp_sys_argv, 0);
275 
276     readline_init0();
277 
278     pin_init0();
279 
280     #if 0
281     // add some functions to the python namespace
282     {
283         mp_store_name(MP_QSTR_help, mp_make_function_n(0, pyb_help));
284         mp_obj_t m = mp_obj_new_module(MP_QSTR_pyb);
285         mp_store_attr(m, MP_QSTR_info, mp_make_function_n(0, pyb_info));
286         mp_store_attr(m, MP_QSTR_source_dir, mp_make_function_n(1, pyb_source_dir));
287         mp_store_attr(m, MP_QSTR_main, mp_make_function_n(1, pyb_main));
288         mp_store_attr(m, MP_QSTR_gc, mp_make_function_n(0, pyb_gc));
289         mp_store_attr(m, MP_QSTR_delay, mp_make_function_n(1, pyb_delay));
290         mp_store_attr(m, MP_QSTR_led, mp_make_function_n(1, pyb_led));
291         mp_store_attr(m, MP_QSTR_LED, (mp_obj_t)&pyb_led_type);
292         mp_store_attr(m, MP_QSTR_analogRead, mp_make_function_n(1, pyb_analog_read));
293         mp_store_attr(m, MP_QSTR_analogWrite, mp_make_function_n(2, pyb_analog_write));
294         mp_store_attr(m, MP_QSTR_analogWriteResolution, mp_make_function_n(1, pyb_analog_write_resolution));
295         mp_store_attr(m, MP_QSTR_analogWriteFrequency, mp_make_function_n(2, pyb_analog_write_frequency));
296 
297         mp_store_attr(m, MP_QSTR_gpio, (mp_obj_t)&pyb_gpio_obj);
298         mp_store_attr(m, MP_QSTR_Servo, mp_make_function_n(0, pyb_Servo));
299         mp_store_name(MP_QSTR_pyb, m);
300     }
301     #endif
302 
303     #if MICROPY_MODULE_FROZEN
304     pyexec_frozen_module("boot.py");
305     #else
306     if (!pyexec_file_if_exists("/boot.py")) {
307         flash_error(4);
308     }
309     #endif
310 
311     // Turn bootup LED off
312     led_state(PYB_LED_BUILTIN, 0);
313 
314     // run main script
315     #if MICROPY_MODULE_FROZEN
316     pyexec_frozen_module("main.py");
317     #else
318     {
319         vstr_t *vstr = vstr_new(16);
320         vstr_add_str(vstr, "/");
321         if (pyb_config_main == MP_OBJ_NULL) {
322             vstr_add_str(vstr, "main.py");
323         } else {
324             vstr_add_str(vstr, mp_obj_str_get_str(pyb_config_main));
325         }
326         if (!pyexec_file_if_exists(vstr_null_terminated_str(vstr))) {
327             flash_error(3);
328         }
329         vstr_free(vstr);
330     }
331     #endif
332 
333     // enter REPL
334     // REPL mode can change, or it can request a soft reset
335     for (;;) {
336         if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
337             if (pyexec_raw_repl() != 0) {
338                 break;
339             }
340         } else {
341             if (pyexec_friendly_repl() != 0) {
342                 break;
343             }
344         }
345     }
346 
347     printf("MPY: soft reboot\n");
348 
349 //    first_soft_reset = false;
350     goto soft_reset;
351 }
352 
gc_collect(void)353 void gc_collect(void) {
354     gc_collect_start();
355     gc_helper_collect_regs_and_stack();
356     gc_collect_end();
357 }
358 
359 // stub out __libc_init_array. It's called by mk20dx128.c and is used to call
360 // global C++ constructors. Since this is a C-only projects, we don't need to
361 // call constructors.
__libc_init_array(void)362 void __libc_init_array(void) {
363 }
364 
365 // ultoa is used by usb_init_serialnumber. Normally ultoa would be provided
366 // by nonstd.c from the teensy core, but it conflicts with some of the
367 // MicroPython functions in string0.c, so we provide ultoa here.
ultoa(unsigned long val,char * buf,int radix)368 char *ultoa(unsigned long val, char *buf, int radix) {
369     unsigned digit;
370     int i = 0, j;
371     char t;
372 
373     while (1) {
374         digit = val % radix;
375         buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10);
376         val /= radix;
377         if (val == 0) {
378             break;
379         }
380         i++;
381     }
382     buf[i + 1] = 0;
383     for (j = 0; j < i; j++, i--) {
384         t = buf[j];
385         buf[j] = buf[i];
386         buf[i] = t;
387     }
388     return buf;
389 }
390