模拟信号量实现传感器的定时采集

/*
13点41分,2017年8月18日
需求:传感器的采集频率可以设置,单位是秒。通过滴答定时器实现。
      使用一个二值信号量。
平台:stm32f042,无操作系统,模拟信号量。使用信号量实现两个线程的同步
**/


struct sensor
{
	int sampl_frequen;       /* 采样周期 */
    int sampl_frequen_shdow; /* 采样周期的影子 */
	volatile  uint16_t semaphore_frequen; /* 信号量,1:有资源,0没有资源 */
	int read_data;  /* 温度值 */
};


/** 
   背景介绍:
   将主函数里循环调用的函数理解为线程1
   将滴答定时器中断函数理解为线程2.
   初始化时没有资源,sensor1.semaphore_frequen = 0;
   sensor1.sampl_frequen = sensor1.sampl_frequen_shdow = 5;采样频率设置为 5s .
**/

void thread1_sensor(void)
{		
	if(sensor1.init.semaphore_frequen == 1)
	{
	    /* 消费者将资源取走 */
	    sensor1.init.semaphore_frequen = 0;
	
	    /* 读温度值 */
	}
	else
	{
		goto out;
	}
}

void thread2_systick(void)
{
	static uint16_t time_ms = 0;
	if(time_ms>=1000)
	{
		/* 生产者开始生产 */
	    if( sensor1.init.semaphore_frequen ==0 )
		{
			sensor1.init.sampl_frequen--;
			
			if(sensor1.init.sampl_frequen <= 0)
			{
				/* 时间到了,生产者生产好了一个产品 */
				sensor1.init.semaphore_frequen = 1;
				sensor1.init.sampl_frequen = sensor1.init.sampl_frequen_shdow;
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值