9.2 多任务的裸机实现(上)
多任务带来的时间问题
每个任务的执行间隔
每个任务的执行时间
任务的分类
有些任务需要频繁运行:数码管显示、按键扫描
有些任务不需要频繁运行:温度传感器、温度设置
例程1裸机多任务
/************************************************
* Filename: task.c
* Author: litao.wang
* Description:
* Create: 2018-07-11 10:26:13
* Last Modified: 2018-07-31 21:05:51
*************************************************/
#include<stdio.h>
void delay(int ms)
{
for(int i=0;i<5000000;i++)
for(int j=0;j<ms;j++)
;
}
int task_key_scan(void)
{
int key_value;
printf("keyboard scan...\n");
return key_value;
}
void task_led_show(void)
{
printf("led show...\n");
}
void task_temperature_get(void)
{
printf("DB18S20 init...\n");
}
void task_temperature_set(void)
{
printf("set temperature...\n");
}
int main(void)
{
while(1) //死循环
{
task_temperature_get();
delay(100);
task_led_show();
delay(100);
task_key_scan();
delay(100);
task_temperature_set();
delay(100);
printf("\n\n");
}
return 0;
}
例程2 多任务优化间隔
/************************************************
* Filename: task2.c
* Author: litao.wang
* Description:
* Create: 2018-07-11 10:26:13
* Last Modified: 2018-07-11 11:53:01
*************************************************/
#include<stdio.h>
unsigned int count;
void count_add(void)
{
for(int i=0;i<5000000;i++)
;
count++;
}
int task_key_scan(void)
{
int key_value;
printf("keyboard scan...\n");
return key_value;
}
void task_led_show(void)
{
printf("led show...\n");
}
void task_temperature_get(void)
{
printf("DB18S20 init...\n");
}
void task_temperature_set(void)
{
printf("set temperature...\n");
}
int main(void)
{
while(1)
{
count_add(); //软件延时计数器
if(count%1000==0)
task_temperature_get();
if(count%100==0)
task_led_show();
if(count%200==0)
task_key_scan();
if(count%2000==0)
task_temperature_set();
}
return 0;
}
例程2 多任务优化- 中断延时
/************************************************
* Filename: task3.c
* Author: litao.wang
* Description:
* Create: 2018-07-11 10:26:13
* Last Modified: 2018-07-11 11:50:50
*************************************************/
#include<stdio.h>
unsigned int count;
void rtc_interrupt(void)
{
count++;
}
int task_key_scan(void)
{
int key_value;
printf("keyboard scan...\n");
return key_value;
}
void task_led_show(void)
{
printf("led show...\n");
}
void task_temperature_get(void)
{
printf("DB18S20 init...\n");
}
void task_temperature_set(void)
{
printf("set temperature...\n");
}
int main(void)
{
while(1)
{
if(count%1000==0)
task_temperature_get();
if(count%100==0)
task_led_show();
if(count%200==0)
task_key_scan();
if(count%2000==0)
task_temperature_set();
}
return 0;
}