STC12 -定时器0 定时 1s LED0翻转1次

1. main.c

#include<reg52.h> 
#include<intrins.h>
#include<Timer0_Init.h>
#define uchar unsigned char
#define uint unsigned int

sbit LED0 = P2^0;

void main()
{
    uchar count = 0;  //用来看看 Timer0溢出的 次数
 Timer0_Init(); while(1) { if(TF0==1) { TF0 = 0; TH0 = (65535-10000+1)/256; //重新 赋初值 计数 TL0 = (65535-10000+1)%256; count++; if(count >= 100) //100个溢出是100*10ms=1s  { count = 0; LED0 = ~LED0; } } } }

2. 定时器0 初始化 

(1)Timer0_Init.c

#include<Timer0_Init.h>
#include<reg52.h>
void Timer0_Init()
{
    TMOD = 0x01;
    TH0 = (65535-10000+1)/256; //公式:计数初值=(2^16-要计数的计数值)/2^8     ;10000指10000个机器周期 12MHz的机器周期是1us,所以10000个为10ms
    TL0 = (65535-10000+1)%256; // 2^16指定时器是16位的,2^8指所得的数 取高8位放入TH0中,%是取低8位    
    TR0 = 1;      //    =1 ->     open the Timer0
}

(2)Timer0_Init.h

#ifndef __Timer0_Init_H
#define __Timer0_Init_H     
#include "reg52.h" 
void Timer0_Init(); #endif

PS:记得在 魔术棒里c51栏加入引用过的 .h 文件的PATH 地址

猜你喜欢

转载自www.cnblogs.com/oneme1world/p/12735297.html