/******************************************************************************
*       Copyright (C) 2005 Freescale Semiconductor, Inc.
*       All Rights Reserved
*
* Filename:     serial.c
* Author:       jgrand
* Revision:     1.0
*
* Notes:        Also serves as an example for the 9S08QG8 demo board.
*               Created using CodeWarrior 5.0 for HC(S)08.
******************************************************************************/

#include <hidef.h> /* for EnableInterrupts macro */
#include <string.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */

static char n_str[3];

/*                            
void TERMIO_PutChar(char s_char) {
  byte dummy;	   // dummy var for reading SCIS1
  
  SCIC2 = 0x08;    // enable Tx
  dummy = SCIS1;   // 1st half of TDRE clear procedure
  SCID = s_char;   // 2nd half of TDRE clear procedure
  while(!SCIS1_TDRE){
  };
  while(!SCIS1_TC){
  };
  SCIC2_TE = 0;
} //end SendChar

char RecChar() {
  byte rec_char;

  if (SCIS1_RDRF)  // 1st half of RDRF clear procedure
    rec_char = SCID;  // 2nd half of RDRF clear procedure
  SCIC2_RE = 1;    // enable Rx
  while(!SCIS1_RDRF){
  };
  rec_char = SCID; // get recieved character
  TERMIO_PutChar(rec_char); // echo received character
  return SCID;
} //end RecChar  

void SendMsg(char msg[]) {
  byte ix=0;	   // String pointer
  byte dummy;	   // dummy var for reading SCIS1
  byte nxt_char;
  
  SCIC2 = 0x08;    // enable Tx
  dummy = SCIS1;   // 1st half of TDRE clear procedure
  nxt_char = msg[ix++];
  while(nxt_char != 0x00) {
    SCID = nxt_char; // 2nd half of TDRE clear procedure
    nxt_char = msg[ix++];
    while(!SCIS1_TDRE){
    };
  } //end while((SCI1D
  while(!SCIS1_TC){
  };
  SCIC2_TE = 0;
} //end SendMsg
*/

char * num2asc(byte n) {
  n_str[0] = (n>>0x04)+0x30;  // convert MSN 'n' to ascii
  if(n_str[0]>0x39)           // if MSN is $a or larger...
    n_str[0]+=0x07;           // ...add $7 to correct
  n_str[1] = (n&0x0f)+0x30;   // convert LSN 'n' to ascii
  if(n_str[1]>0x39)           // if LSN is $a or larger...
    n_str[1]+=0x07;           // ...add $7 to correct
  n_str[2] = 0x00;            // add null
  return n_str;
} //end num2asc

byte asc2num(char n_asc) {
byte n;

  n = n_asc - 0x30;      //convert from ascii to int
  if(n > 0x09)           // if num is $a or larger...
    n -= 0x07;           // ...sub $7 to correct
  if(n > 0x0f)           // if lower case was used...
    n -= 0x20;           // ...sub $20 to correct
  if(n > 0x0f)           // if non-numeric character...
    n = 0x00;            // ...default to '0'
  return n;
} //end asc2num