MS51FB9AE – Một số hàm tạo delay

File Header delay.h

/* delay.h */
#ifndef DELAY_H_
#define DELAY_H_

#ifdef __C51__
#include "myIntType.h"
#else
#include <stdint.h>
#endif

void Delay_Init(void);
void Delay_Ms(uint16_t u16Delay);

#endif

File delay.c

Sử dụng Timer 0

/* delay.c */
#include <MS51.h>
#include "delay.h"

static void delay_1ms(void);

void Delay_Init(void)
{
	TMOD |= (1 << 0);
	TMOD &= ~(1 << 1);
	CKCON |= (1 << 3);
	TMOD &= ~(1 << 2);
	TMOD &= ~(1 << 3);
}

void Delay_Ms(uint16_t u16Delay)
{
	while (u16Delay) {
		--u16Delay;
		delay_1ms();
	}
}

void delay_1ms(void)
{
	TH0 = 0;
	TL0 = 0;
	TR0 = 1;
	while (TH0 * 256 + TL0 < 16000) {
	}
	TR0 = 0;
}

Sử dụng Timer 1

/* delay.c */
#include <MS51.h>
#include "delay.h"

static void delay_1ms(void);

void Delay_Init(void)
{
	TMOD |= (1 << 4);
	TMOD &= ~(1 << 5);
	CKCON |= (1 << 4);
	TMOD &= ~(1 << 6);
	TMOD &= ~(1 << 7);
}

void Delay_Ms(uint16_t u16Delay)
{
	while (u16Delay) {
		--u16Delay;
		delay_1ms();
	}
}

void delay_1ms(void)
{
	TH1 = 0;
	TL1 = 0;
	TR1 = 1;
	while (TH1 * 256 + TL1 < 16000) {
	}
	TR1 = 0;
}

Sử dụng Timer 2

/* delay.c */
#include <MS51.h>
#include "delay.h"

static void delay_1ms(void);

void Delay_Init(void)
{
	CM_RL2 = 1;
	T2MOD &= ~0x70;
	T2MOD |= 0x00;
	T2MOD &= ~(1 << 2);
}

void Delay_Ms(uint16_t u16Delay)
{
	while (u16Delay) {
		--u16Delay;
		delay_1ms();
	}
}

void delay_1ms(void)
{
	TH2 = 0;
	TL2 = 0;
	TR2 = 1;
	while (TH2 * 256 + TL2 < 16000) {
	}
	TR2 = 0;
}

Sử dụng Timer 3

/* delay.c */
#include <MS51.h>
#include "delay.h"

static void delay_1ms(void);

void Delay_Init(void)
{
	T3CON &= ~(1 << 3);
	T3CON &= ~0x07;
	T3CON |= 0x04;
	RL3 = 0x18;
	RH3 = 0xFC;
	T3CON &= ~(1 << 4);
	T3CON |= (1 << 3);
	while ((T3CON & (1 << 4)) == 0) {
	}
	T3CON &= ~(1 << 3);
}

void Delay_Ms(uint16_t u16Delay)
{
	while (u16Delay) {
		--u16Delay;
		delay_1ms();
	}
}

void delay_1ms(void)
{
	T3CON &= ~(1 << 4);
	T3CON |= (1 << 3);
	while ((T3CON & (1 << 4)) == 0) {
	}
	T3CON &= ~(1 << 3);
}

Cách sử dụng (file main.c)

/* main.c */
#include <MS51.h>
#include "delay.h"

void main(void)
{

	Delay_Init();
	while (1) {
		Delay_Ms(100);
		/* your code here */
	}
}