// filename: common.c
// RealSYS KCO
#include "common.h"

void delay_us(u32 nCount){
int i;
  for(; nCount != 0; nCount--){
    for(i=0;i<11;i++) asm(" NOP ");
  }
}
void delay_ms(u32 nCount){
  for(; nCount != 0; nCount--) delay_us(1000);
}

BYTE	asc2hex(BYTE asc){
    if((asc >= '0') && (asc <= '9'))    return (asc - '0');
    else if((asc >= 'A') && (asc <= 'F'))   return (asc - 'A' + 0x0a);
    else if((asc >= 'a') && (asc <= 'f'))    return (asc - 'a' + 0x0a);
    else return 0xff;
}

BYTE	hex2asc(BYTE hex){
BYTE	da;
	da = hex & 0x0f;
    if(da <= 9)    return  ('0' + da);
    else    return  ('A' + da - 0x0a);
}

WORD	hex2_to_decimal(BYTE b){
BYTE	d100,d10,d1;
WORD	dec=0;
	d100 = b/100;
	d10 = (b - d100*100)/10;
	d1 = (b - d100*100 - d10*10); 
	dec = (d100<<8) | (d10<<4) | d1;
	return dec;
}

LONG hex4_to_decimal(WORD w){
LONG d10000,d1000,d100,d10,d1;
LONG dec,tmp;
	d10000 = w/10000;
	tmp = d10000 * 10000;
	d1000 = (w - tmp)/1000;
	tmp += d1000 * 1000;
	d100 = (w - tmp )/100;
	tmp += d100 * 100;
	d10 = (w - tmp)/10;
	tmp += d10 * 10;
	d1 = w - tmp;
	dec = (d10000<<16) | (d1000<<12) | (d100<<8) | (d10<<4) | d1;
	return dec;
}

long map(long x, long in_min, long in_max, long out_min, long out_max){
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

float map_f(float x, float in_min, float in_max, float out_min, float out_max){
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

BOOL flag_1ms=0,flag_2ms=0,flag_10ms=0,flag_100ms=0,flag_300ms=0;
void  check_period_flag(void){
static BYTE  cnt_100us=0,cnt_1ms=0,cnt_2ms=0,cnt_10ms=0,cnt_100ms=0;
  if(++cnt_100us>=10){
    cnt_100us = 0;    	flag_1ms = 1;
    if(++cnt_1ms>=2){
      cnt_1ms = 0;		flag_2ms = 1;
      if(++cnt_2ms>=5){
        cnt_2ms = 0;	flag_10ms = 1;
        if(++cnt_10ms>=10){
          cnt_10ms=0;	flag_100ms = 1;
          if(++cnt_100ms>=3){
            cnt_100ms=0;	flag_300ms = 1;
          }
        }
      }
    }
  }
}