/***********************************************************************
 * Copyright (c)  2017 - 2020, Unicmicro Co.,Ltd .
 * All rights reserved.
 * Filename    : system_um800x.c
 * Description : system config source file (for example: clock config.....)
 * Author(s)   : Dan
 * version     : V1.0
 * Modify date : 2020-07-16
 ***********************************************************************/
 
#include  "system_um800x.h"
#include  "config.h"

uint32_t SRCClock = 48000000;   //RCH源时钟 , (uint:Hz)

volatile uint32_t SystemCoreClock = 0;   			//core时钟 , (uint:Hz)
volatile uint32_t xdata rch24m = 0;

/************************************************************************
 * function   : clock_init
 * Description: clock init, initil several clock variables
 * input : 
 *		  uint32_t system_clk_hz
 * return: none
 ************************************************************************/
void clock_init(uint32_t system_clk_hz)
{
    uint32_t crystal_clk = 0;    
    
    CLKCON |= (0x1<<2);						//RCH时钟源打开
    while((CLKCON&0x20) != 0x20);  			//等待RC16M时钟稳定


    rch24m = ((uint32_t)(*(volatile uint8_t xdata*)(0x9037))<<24) |  \
         ((uint32_t)(*(volatile uint8_t xdata*)(0x9036))<<16) |  \
         ((uint32_t)(*(volatile uint8_t xdata*)(0x9035))<<8)  |  \
          (uint32_t)(*(volatile uint8_t xdata*)(0x9034));   
        
    if ((rch24m <= 24120000) && (rch24m >= 23880000))
    {
        crystal_clk = SRCClock;        
    }
    else if(rch24m == 0xffffffff)  
    {
        crystal_clk = SRCClock;   
    }
    else            //如果实际值在24M的千分之五以外，用实际值
    {
        crystal_clk = rch24m*2; 
    }  
    switch(system_clk_hz)
    {
        case 24000000:
            RCHDIV = 0x1;                		//RCH 2分频
            SystemCoreClock = crystal_clk/2;
			OPSET |=(0x1<<3);   //flash读等待时间为1
            break;
        case 16000000:
            RCHDIV = 0x2;                		//RCH 3分频
            SystemCoreClock = crystal_clk/3;
            break;
        case 12000000:
            RCHDIV = 0x3;                		//RCH 4分频
            SystemCoreClock = crystal_clk/4;
            break;
        default:
            RCHDIV = 0x2;                		//RCH 3分频
            SystemCoreClock = crystal_clk/3;
            break;
       
    }
                        
    CLKCON &= ~(0x1<<0);					//RCH为系统时钟
	SYSDIV &= ~(7<<0);						//系统时钟不分频	
}

/************************************************************************
 * function   : systeminit
 * Description: systeminit
 * input : none
 * return: none
 ************************************************************************/
void systeminit(void)
{
    clock_init(FCLK); 
}

