#include <stdio.h>
#include <string.h>

/* 非依存ヘッダ */
#include "common.h"
#include "ultra_sonic.h"

/* 依存ヘッダ */
#include <AKI3694.h>

#define US_CHANNEL 3

/* 処理ルーチン */
#define select_low(ch)  (IO.PDR1.BYTE &= ~(0x40 >> ch))
#define select_high(ch) (IO.PDR1.BYTE |=  (0x40 >> ch))
#define clk_low()       (IO.PDR5.BIT.B7 = 0)
#define clk_high()      (IO.PDR5.BIT.B7 = 1)
#define is_data_high()  (IO.PDR5.BIT.B6)

/**
 * 超音波センサユニットとの接続部の初期化
 * 
 */
void us_init(){
  
  /*
   * 接続は3チャンネル分で
   * 
   * P16〜P14  => SELECT(OUT)
   * P56/SDA   => DATA(IN)
   * P57/SCL   => CLK(OUT)
   */
  
  /* P14〜P16の処理 */
  IO.PCR1 |= 0x70;
  
  /* P56,P57の処理 */
  IO.PCR5 |= 0x80;
  IO.PCR5 &= ~(0x40);
  
  /* SELECTとCLKはHighにしておく */
  IO.PDR1.BYTE |= 0x70;
  IO.PDR5.BYTE |= 0x80;
}

/**
 * 超音波センサユニットから値を読み取る
 * 
 */
unsigned char us_read(unsigned char ch){
  
  unsigned char mask = 0x80;
  unsigned char result = 0x00;
  
  select_low(ch);
  do{
    clk_low();
    clk_high();
    if(is_data_high()){result |= mask;}
  }while(mask >>= 1);
  select_high(ch);
  
  return result;
}
