atmega8 例程:系统库函数的延迟

/***********************************************************
*  函数库说明:ATMEGE8 延迟库函数
*  版本:      v1.0									       
*  修改:      庞辉									       
*  修改日期:  2011年08月02日							   
*														   
*  说明:	   无										   
*                                                          
*  版本更新:                                              
*                                                                                          
************************************************************
*注意: LED  PC5                                            
***********************************************************/

#include <avr/io.h>

//定义外部晶振
#define F_CPU 6000000UL

//延迟包含头文件
#include <util/delay.h>

//函数声明
void Delay_s(int ss);


int main(void)
{
    //LED等PC5设置为输出
    DDRC |= (1 << DDC5);
    //起始PC5输出高电平,LED不亮
    PORTC |= (1 << PC5);
    
    while(1)
    {
        //取反
        PORTC ^= (1 << PC5);
        //延迟1s
        Delay_s(1);
    }    

    return 0;
}

/***********************************************************
** 名称:void Delay_s(int ss)
** 功能:精确1s延迟
** 入口参数:ss	需要延时的秒数
** 出口参数:无
** 使用说明:系统库函数延迟因晶振不同有大小限制
***********************************************************/
void Delay_s(int ss)
{
    int i = 0;

    while(ss--)
    {
        for(i = 0; i < 25; i++)
        {   
            _delay_ms(40);
        }
    }

}


 首先库文件<util/delay.h>里面不再定义F_CPU(即晶振频率),所以在main.c中自行定义。

且系统延迟函数因晶振的不同对延迟大小有限制,需要注意:

/**
   \ingroup util_delay

   Perform a delay of \c __us microseconds, using _delay_loop_1().

   The macro F_CPU is supposed to be defined to a
   constant defining the CPU clock frequency (in Hertz).

   The maximal possible delay is 768 us / F_CPU in MHz.
 */


 

/**
   \ingroup util_delay

   Perform a delay of \c __ms milliseconds, using _delay_loop_2().

   The macro F_CPU is supposed to be defined to a
   constant defining the CPU clock frequency (in Hertz).

   The maximal possible delay is 262.14 ms / F_CPU in MHz.
 */


故我的6M晶振,ms即延迟最多262.14 / 6 即43.69ms,注意系统延迟函数形参都是double类型的哦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值