本帖最后由 Simon21ic 于 2017-1-23 02:50 编辑
乘着有空就多写一些,这里不像“回”字的N种写法,VSF种的多任务,可以有不同的实现方式,资源占用,开发复杂性,灵活性都不同。这里就用闪灯操作,简单的展现一下几种多任务的实现方式。
1. callback实现方式,这个是目前比较推荐的,也是最简单的
- static void usrapp_led_blink(void *p)
- {
- struct usrapp_t *app = (struct usrapp_t *)p;
- if (app->led_on)
- vsfhal_gpio_clear(LED_PORT, 1 << LED_PIN);
- else
- vsfhal_gpio_set(LED_PORT, 1 << LED_PIN);
- app->led_on = !app->led_on;
- }
- void usrapp_init(struct usrapp_t *app)
- {
- vsfhal_gpio_init(LED_PORT);
- vsfhal_gpio_config_pin(LED_PORT, LED_PIN, GPIO_OUTPP);
- vsfhal_gpio_clear(LED_PORT, 1 << LED_PIN);
- app->led_on = false;
- vsftimer_create_cb(1000, -1, usrapp_led_blink, app);
- }
2. evt_handler实现方式,直接处理各种事件
- static struct vsfsm_state_t *
- usrapp_led_evt_handler(struct vsfsm_t *sm, vsfsm_evt_t evt)
- {
- struct usrapp_t *app = (struct usrapp_t *)sm->user_data;
- switch (evt)
- {
- case VSFSM_EVT_INIT:
- vsftimer_create(sm, 1000, -1, VSFSM_EVT_USER);
- break;
- case VSFSM_EVT_USER:
- if (app->led_on)
- vsfhal_gpio_clear(LED_PORT, 1 << LED_PIN);
- else
- vsfhal_gpio_set(LED_PORT, 1 << LED_PIN);
- app->led_on = !app->led_on;
- break;
- }
- return NULL;
- }
- void usrapp_init(struct usrapp_t *app)
- {
- vsfhal_gpio_init(LED_PORT);
- vsfhal_gpio_config_pin(LED_PORT, LED_PIN, GPIO_OUTPP);
- vsfhal_gpio_clear(LED_PORT, 1 << LED_PIN);
- app->led_on = false;
- app->sm.init_state.evt_handler = usrapp_led_evt_handler;
- app->sm.user_data = app;
- vsfsm_init(&app->sm);
- }
3. pt实现方式,共享堆栈的协程
- static vsf_err_t usrapp_led_thread(struct vsfsm_pt_t *pt, vsfsm_evt_t evt)
- {
- struct usrapp_t *app = (struct usrapp_t *)pt->user_data;
- vsfsm_pt_begin(pt);
- while (1)
- {
- vsfsm_pt_delay(pt, 1000);
- vsfhal_gpio_clear(LED_PORT, 1 << LED_PIN);
- vsfsm_pt_delay(pt, 1000);
- vsfhal_gpio_set(LED_PORT, 1 << LED_PIN);
- }
- vsfsm_pt_end(pt);
- return VSFERR_NONE;
- }
- void usrapp_init(struct usrapp_t *app)
- {
- vsfhal_gpio_init(LED_PORT);
- vsfhal_gpio_config_pin(LED_PORT, LED_PIN, GPIO_OUTPP);
- vsfhal_gpio_clear(LED_PORT, 1 << LED_PIN);
- app->led_on = false;
- app->pt.thread = usrapp_led_thread;
- app->pt.user_data = app;
- vsfsm_pt_init(&app->sm, &app->pt);
- }
4. setjmp/longjmp,独立堆栈的协程
不推荐,就不写了
|