main.c 12.9 KB
Newer Older
1
#include <stdio.h>
2
#include <string.h>
Damien's avatar
Damien committed
3
4
#include <stm32f4xx.h>
#include <stm32f4xx_rcc.h>
5
#include <stm32f4xx_syscfg.h>
6
#include <stm32f4xx_gpio.h>
7
#include <stm32f4xx_exti.h>
8
#include <stm32f4xx_tim.h>
Damien's avatar
Damien committed
9
#include <stm32f4xx_pwr.h>
10
#include <stm32f4xx_rtc.h>
11
#include <stm32f4xx_usart.h>
12
#include <stm32f4xx_rng.h>
13
#include <usbd_storage_msd.h>
14
#include <stm_misc.h>
Damien's avatar
Damien committed
15
16
#include "std.h"

17
#include "misc.h"
18
19
#include "ff.h"
#include "mpconfig.h"
20
#include "qstr.h"
21
22
23
#include "nlr.h"
#include "misc.h"
#include "lexer.h"
24
#include "lexerfatfs.h"
25
26
#include "parse.h"
#include "obj.h"
27
#include "parsehelper.h"
28
#include "compile.h"
29
30
#include "runtime0.h"
#include "runtime.h"
Damien's avatar
Damien committed
31
#include "gc.h"
32
#include "gccollect.h"
33
#include "systick.h"
34
#include "pendsv.h"
35
#include "pyexec.h"
36
#include "led.h"
37
#include "servo.h"
38
#include "lcd.h"
39
#include "storage.h"
40
#include "sdcard.h"
Damien George's avatar
Damien George committed
41
#include "accel.h"
Damien's avatar
Damien committed
42
#include "usb.h"
43
#include "timer.h"
44
#include "pybwlan.h"
45
#include "usrsw.h"
mux's avatar
mux committed
46
#include "rtc.h"
mux's avatar
mux committed
47
#include "file.h"
Dave Hylands's avatar
Dave Hylands committed
48
#include "pin.h"
Dave Hylands's avatar
Dave Hylands committed
49
#include "exti.h"
Damien George's avatar
Damien George committed
50
#include "pybmodule.h"
51
52

int errno;
Damien's avatar
Damien committed
53

54
static FATFS fatfs0;
55
#if MICROPY_HW_HAS_SDCARD
56
static FATFS fatfs1;
57
#endif
58

59
60
61
62
63
64
65
66
67
68
69
70
void flash_error(int n) {
    for (int i = 0; i < n; i++) {
        led_state(PYB_LED_R1, 1);
        led_state(PYB_LED_R2, 0);
        sys_tick_delay_ms(250);
        led_state(PYB_LED_R1, 0);
        led_state(PYB_LED_R2, 1);
        sys_tick_delay_ms(250);
    }
    led_state(PYB_LED_R2, 0);
}

Damien's avatar
Damien committed
71
void __fatal_error(const char *msg) {
mux's avatar
mux committed
72
#if MICROPY_HW_HAS_LCD
Damien's avatar
Damien committed
73
74
    lcd_print_strn("\nFATAL ERROR:\n", 14);
    lcd_print_strn(msg, strlen(msg));
mux's avatar
mux committed
75
#endif
Damien's avatar
Damien committed
76
    for (;;) {
77
        flash_error(1);
Damien's avatar
Damien committed
78
79
80
    }
}

Damien George's avatar
Damien George committed
81
82
STATIC mp_obj_t pyb_config_source_dir = MP_OBJ_NULL;
STATIC mp_obj_t pyb_config_main = MP_OBJ_NULL;
83

Damien George's avatar
Damien George committed
84
STATIC mp_obj_t pyb_source_dir(mp_obj_t source_dir) {
85
86
87
    if (MP_OBJ_IS_STR(source_dir)) {
        pyb_config_source_dir = source_dir;
    }
88
    return mp_const_none;
89
90
}

Damien George's avatar
Damien George committed
91
92
93
MP_DEFINE_CONST_FUN_OBJ_1(pyb_source_dir_obj, pyb_source_dir);

STATIC mp_obj_t pyb_main(mp_obj_t main) {
94
95
96
    if (MP_OBJ_IS_STR(main)) {
        pyb_config_main = main;
    }
97
    return mp_const_none;
98
99
}

Damien George's avatar
Damien George committed
100
MP_DEFINE_CONST_FUN_OBJ_1(pyb_main_obj, pyb_main);
101

102
void fatality(void) {
103
104
105
106
107
108
    led_state(PYB_LED_R1, 1);
    led_state(PYB_LED_G1, 1);
    led_state(PYB_LED_R2, 1);
    led_state(PYB_LED_G2, 1);
}

109
static const char fresh_boot_py[] =
110
111
112
113
114
115
116
117
118
119
120
"# boot.py -- run on boot-up\n"
"# can run arbitrary Python, but best to keep it minimal\n"
"\n"
"pyb.source_dir('/src')\n"
"pyb.main('main.py')\n"
"#pyb.usb_usr('VCP')\n"
"#pyb.usb_msd(True, 'dual partition')\n"
"#pyb.flush_cache(False)\n"
"#pyb.error_log('error.txt')\n"
;

121
122
123
124
125
126
127
128
129
130
static const char fresh_main_py[] =
"# main.py -- put your code here!\n"
;

static const char *help_text =
"Welcome to Micro Python!\n\n"
"This is a *very* early version of Micro Python and has minimal functionality.\n\n"
"Specific commands for the board:\n"
"    pyb.info()     -- print some general information\n"
"    pyb.gc()       -- run the garbage collector\n"
131
"    pyb.repl_info(<val>) -- enable/disable printing of info after each command\n"
132
"    pyb.delay(<n>) -- wait for n milliseconds\n"
Damien George's avatar
Damien George committed
133
"    pyb.udelay(<n>) -- wait for n microseconds\n"
134
135
136
137
138
139
140
"    pyb.Led(<n>)   -- create Led object for LED n (n=1,2)\n"
"                      Led methods: on(), off()\n"
"    pyb.Servo(<n>) -- create Servo object for servo n (n=1,2,3,4)\n"
"                      Servo methods: angle(<x>)\n"
"    pyb.switch()   -- return True/False if switch pressed or not\n"
"    pyb.accel()    -- get accelerometer values\n"
"    pyb.rand()     -- get a 16-bit random number\n"
141
"    pyb.gpio(<port>)           -- get port value (port='A4' for example)\n"
142
"    pyb.gpio(<port>, <val>)    -- set port value, True or False, 1 or 0\n"
143
144
"    pyb.ADC(<port>) -- make an analog port object (port='C0' for example)\n"
"                       ADC methods: read()\n"
145
146
147
;

// get some help about available functions
148
static mp_obj_t pyb_help(void) {
149
    printf("%s", help_text);
150
    return mp_const_none;
151
152
}

153
int main(void) {
154
    // TODO disable JTAG
Damien's avatar
Damien committed
155

156
157
158
    // update the SystemCoreClock variable
    SystemCoreClockUpdate();

159
160
161
162
    // set interrupt priority config to use all 4 bits for pre-empting
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);

    // enable the CCM RAM and the GPIO's
163
    RCC->AHB1ENR |= RCC_AHB1ENR_CCMDATARAMEN | RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN | RCC_AHB1ENR_GPIODEN;
164

mux's avatar
mux committed
165
#if MICROPY_HW_HAS_SDCARD
166
    {
167
168
169
170
171
172
173
174
175
176
177
178
179
        // configure SDIO pins to be high to start with (apparently makes it more robust)
        // FIXME this is not making them high, it just makes them outputs...
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
        GPIO_Init(GPIOC, &GPIO_InitStructure);

        // Configure PD.02 CMD line
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
        GPIO_Init(GPIOD, &GPIO_InitStructure);
180
    }
mux's avatar
mux committed
181
#endif
Dave Hylands's avatar
Dave Hylands committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#if defined(NETDUINO_PLUS_2)
    {
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

#if MICROPY_HW_HAS_SDCARD
        // Turn on the power enable for the sdcard (PB1)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_1, Bit_SET);
#endif

        // Turn on the power for the 5V on the expansion header (PB2)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_2, Bit_SET);
    }
#endif
203

204
205
    // basic sub-system init
    sys_tick_init();
206
    pendsv_init();
Damien's avatar
Damien committed
207
    led_init();
mux's avatar
mux committed
208
209

#if MICROPY_HW_ENABLE_RTC
210
    rtc_init();
mux's avatar
mux committed
211
#endif
212
213
214
215
216

    // turn on LED to indicate bootup
    led_state(PYB_LED_G1, 1);

    // more sub-system init
217
218
#if MICROPY_HW_HAS_SDCARD
    sdcard_init();
mux's avatar
mux committed
219
#endif
220
    storage_init();
221

222
    // uncomment these 2 lines if you want REPL on USART_6 (or another usart) as well as on USB VCP
223
    //pyb_usart_global_debug = PYB_USART_YA;
224
    //usart_init(pyb_usart_global_debug, 115200);
Damien's avatar
Damien committed
225

226
227
    int first_soft_reset = true;

228
229
soft_reset:

Damien's avatar
Damien committed
230
    // GC init
231
    gc_init(&_heap_start, &_heap_end);
Damien's avatar
Damien committed
232

233
    // Micro Python init
234
235
    qstr_init();
    rt_init();
236
237
238
239
240
    mp_obj_t def_path[3];
    def_path[0] = MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_);
    def_path[1] = MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_src);
    def_path[2] = MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_lib);
    sys_path = mp_obj_new_list(3, def_path);
241

Damien George's avatar
Damien George committed
242
243
    exti_init();

Dave Hylands's avatar
Dave Hylands committed
244
245
246
247
#if MICROPY_HW_HAS_SWITCH
    switch_init();
#endif

mux's avatar
mux committed
248
#if MICROPY_HW_HAS_LCD
249
    // LCD init (just creates class, init hardware by calling LCD())
250
    lcd_init();
mux's avatar
mux committed
251
#endif
252

mux's avatar
mux committed
253
#if MICROPY_HW_ENABLE_SERVO
254
255
    // servo
    servo_init();
mux's avatar
mux committed
256
#endif
257

mux's avatar
mux committed
258
#if MICROPY_HW_ENABLE_TIMER
259
260
    // timer
    timer_init();
mux's avatar
mux committed
261
#endif
262

mux's avatar
mux committed
263
#if MICROPY_HW_ENABLE_RNG
264
    // RNG
mux's avatar
mux committed
265
266
267
    RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
    RNG_Cmd(ENABLE);
#endif
268

Damien George's avatar
Damien George committed
269
    pin_map_init();
270

Damien George's avatar
Damien George committed
271
272
273
    // add some functions to the builtin Python namespace
    rt_store_name(MP_QSTR_help, rt_make_function_n(0, pyb_help));
    rt_store_name(MP_QSTR_open, rt_make_function_n(2, pyb_io_open));
274

mux's avatar
mux committed
275
276
    // load the pyb module
    mp_obj_module_register(MP_QSTR_pyb, (mp_obj_t)&pyb_module);
277

278
279
    // check if user switch held (initiates reset of filesystem)
    bool reset_filesystem = false;
mux's avatar
mux committed
280
#if MICROPY_HW_HAS_SWITCH
281
    if (switch_get()) {
282
283
        reset_filesystem = true;
        for (int i = 0; i < 50; i++) {
284
            if (!switch_get()) {
285
286
287
288
289
290
                reset_filesystem = false;
                break;
            }
            sys_tick_delay_ms(10);
        }
    }
mux's avatar
mux committed
291
#endif
292
293
294
295
    // local filesystem init
    {
        // try to mount the flash
        FRESULT res = f_mount(&fatfs0, "0:", 1);
296
        if (!reset_filesystem && res == FR_OK) {
297
            // mount sucessful
298
        } else if (reset_filesystem || res == FR_NO_FILESYSTEM) {
299
            // no filesystem, so create a fresh one
300
            // TODO doesn't seem to work correctly when reset_filesystem is true...
301
302
303
304
305
306
307
308
309
310
311
312

            // LED on to indicate creation of LFS
            led_state(PYB_LED_R2, 1);
            uint32_t stc = sys_tick_counter;

            res = f_mkfs("0:", 0, 0);
            if (res == FR_OK) {
                // success creating fresh LFS
            } else {
                __fatal_error("could not create LFS");
            }

313
314
315
316
317
318
319
320
321
322
323
324
            // create src directory
            res = f_mkdir("0:/src");
            // ignore result from mkdir

            // create empty main.py
            FIL fp;
            f_open(&fp, "0:/src/main.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_main_py, sizeof(fresh_main_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

325
326
            // keep LED on for at least 200ms
            sys_tick_wait_at_least(stc, 200);
327
328
329
330
            led_state(PYB_LED_R2, 0);
        } else {
            __fatal_error("could not access LFS");
        }
Damien's avatar
Damien committed
331
332
    }

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    // make sure we have a /boot.py
    {
        FILINFO fno;
        FRESULT res = f_stat("0:/boot.py", &fno);
        if (res == FR_OK) {
            if (fno.fattrib & AM_DIR) {
                // exists as a directory
                // TODO handle this case
                // see http://elm-chan.org/fsw/ff/img/app2.c for a "rm -rf" implementation
            } else {
                // exists as a file, good!
            }
        } else {
            // doesn't exist, create fresh file

            // LED on to indicate creation of boot.py
            led_state(PYB_LED_R2, 1);
            uint32_t stc = sys_tick_counter;

            FIL fp;
            f_open(&fp, "0:/boot.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
355
            f_write(&fp, fresh_boot_py, sizeof(fresh_boot_py) - 1 /* don't count null terminator */, &n);
356
357
358
            // TODO check we could write n bytes
            f_close(&fp);

359
360
            // keep LED on for at least 200ms
            sys_tick_wait_at_least(stc, 200);
361
362
363
364
            led_state(PYB_LED_R2, 0);
        }
    }

365
    // run /boot.py
366
    if (!pyexec_file("0:/boot.py")) {
367
368
369
        flash_error(4);
    }

370
    if (first_soft_reset) {
mux's avatar
mux committed
371
#if MICROPY_HW_HAS_MMA7660
Damien George's avatar
Damien George committed
372
373
        // MMA accel: init and reset address to zero
        accel_init();
374
#endif
Damien's avatar
Damien committed
375
376
    }

377
378
    // turn boot-up LED off
    led_state(PYB_LED_G1, 0);
379

380
381
382
383
384
385
#if MICROPY_HW_HAS_SDCARD
    // if an SD card is present then mount it on 1:/
    if (sdcard_is_present()) {
        FRESULT res = f_mount(&fatfs1, "1:", 1);
        if (res != FR_OK) {
            printf("[SD] could not mount SD card\n");
386
387
388
389
390
        } else {
            if (first_soft_reset) {
                // use SD card as medium for the USB MSD
                usbd_storage_select_medium(USBD_STORAGE_MEDIUM_SDCARD);
            }
391
392
393
394
        }
    }
#endif

395
396
397
398
399
#ifdef USE_HOST_MODE
    // USB host
    pyb_usb_host_init();
#elif defined(USE_DEVICE_MODE)
    // USB device
400
    pyb_usb_dev_init(PYB_USB_DEV_VCP_MSC);
401
402
#endif

403
404
405
406
    // run main script
    {
        vstr_t *vstr = vstr_new();
        vstr_add_str(vstr, "0:/");
407
        if (pyb_config_source_dir == MP_OBJ_NULL) {
408
409
            vstr_add_str(vstr, "src");
        } else {
410
            vstr_add_str(vstr, mp_obj_str_get_str(pyb_config_source_dir));
411
412
        }
        vstr_add_char(vstr, '/');
413
        if (pyb_config_main == MP_OBJ_NULL) {
414
415
            vstr_add_str(vstr, "main.py");
        } else {
416
            vstr_add_str(vstr, mp_obj_str_get_str(pyb_config_main));
417
        }
418
        if (!pyexec_file(vstr_str(vstr))) {
419
            flash_error(3);
420
        }
421
        vstr_free(vstr);
422
423
    }

Damien's avatar
Damien committed
424

mux's avatar
mux committed
425
#if MICROPY_HW_HAS_MMA7660
426
427
428
429
430
431
432
433
    // HID example
    if (0) {
        uint8_t data[4];
        data[0] = 0;
        data[1] = 1;
        data[2] = -2;
        data[3] = 0;
        for (;;) {
mux's avatar
mux committed
434
        #if MICROPY_HW_HAS_SWITCH
435
            if (switch_get()) {
436
437
438
439
                data[0] = 0x01; // 0x04 is middle, 0x02 is right
            } else {
                data[0] = 0x00;
            }
mux's avatar
mux committed
440
441
442
        #else
            data[0] = 0x00;
        #endif
Damien George's avatar
Damien George committed
443
444
445
            accel_start(0x4c /* ACCEL_ADDR */, 1);
            accel_send_byte(0);
            accel_restart(0x4c /* ACCEL_ADDR */, 0);
446
            for (int i = 0; i <= 1; i++) {
Damien George's avatar
Damien George committed
447
                int v = accel_read_ack() & 0x3f;
448
449
450
451
452
                if (v & 0x20) {
                    v |= ~0x1f;
                }
                data[1 + i] = v;
            }
Damien George's avatar
Damien George committed
453
            accel_read_nack();
454
455
456
457
            usb_hid_send_report(data);
            sys_tick_delay_ms(15);
        }
    }
458
#endif
459

mux's avatar
mux committed
460
#if MICROPY_HW_HAS_WLAN
461
    // wifi
mux's avatar
mux committed
462
463
464
    pyb_wlan_init();
    pyb_wlan_start();
#endif
465

466
    pyexec_repl();
467

468
    printf("PYB: sync filesystems\n");
Damien George's avatar
Damien George committed
469
    storage_flush();
470
471

    printf("PYB: soft reboot\n");
472
473

    first_soft_reset = false;
474
    goto soft_reset;
Damien's avatar
Damien committed
475
}