第22章 系统时间(RTC编程)

取得当前系统时间的方法是直接访问RTC芯片。

RTC芯片可以通过0x70和0x71端口直接访问。0x70是选址寄存器,0x71是数据寄存器。

Addr Function

==== =========================================

** clock/calendar

00 current second for real-time clock

01 alarm second

02 current minute

04 current hour

05 alarm hour

06 current day of week (1=Sunday)

07 current date of month

08 current month

09 current year (final two digits; eg, 93)

rtc.h源代码如下所示

#ifndef _RTC_H_
#define _RTC_H_

#define RTC_REG_ADDR    0x70    //寻址寄存器
#define RTC_REG_VALUE    0x71    //内容寄存器

#define SECOND_REG    0x0
#define MINUTE_REG    0x2
#define HOUR_REG    0x4
#define DAY_WEEK_REG    0x6
#define DAY_MONTH_REG    0x7
#define MONTH_REG    0x8
#define YEAR_REG    0x9

void localtime();
#endif

rtc.c源代码如下所示

#include "io.h"
#include "rtc.h"
#include "video.h"

unsigned char get_second()
{
    outportb(RTC_REG_ADDR, SECOND_REG);
    return inportb(RTC_REG_VALUE);    
}

unsigned char get_minute()
{
    outportb(RTC_REG_ADDR, MINUTE_REG);
    return inportb(RTC_REG_VALUE);    
}

unsigned char get_hour()
{
    outportb(RTC_REG_ADDR, HOUR_REG);
    return inportb(RTC_REG_VALUE);    
}
unsigned char get_week_day()
{
    outportb(RTC_REG_ADDR, DAY_WEEK_REG);
    return inportb(RTC_REG_VALUE);    
}
unsigned char get_month_day()
{
    outportb(RTC_REG_ADDR, DAY_MONTH_REG);
    return inportb(RTC_REG_VALUE);    
}
unsigned char get_month()
{
    outportb(RTC_REG_ADDR, MONTH_REG);
    return inportb(RTC_REG_VALUE);    
}
unsigned char get_year()
{
    outportb(RTC_REG_ADDR, YEAR_REG);
    return inportb(RTC_REG_VALUE);    
}

void localtime()
{
    unsigned char s,m,h,dw,dm,mm,y;
    s = m = h = dw = dm = m = y = 0;

    s = get_second();
    m = get_minute();
    h = get_hour();
    dw = get_week_day();
    dm = get_month_day();
    mm = get_month();
    y = get_year();

    printf("20%x-%x-%x  %x  %x:%x:%x\n", y,mm,dm, dw, h,m,s);
}

Leave a Reply

Your email address will not be published. Required fields are marked *