/*
Beautoステップアップ講座2
ライン位置の計算サンプルプログラム(センサー2個用)

VS-WRC003のコネクタAN1とAN2に赤外線センサーを接続して使用する。
センサーの間隔は2個が同時にラインを検知できる程度まで狭くする。

T.Yamaguchi
*/


#ifdef __cplusplus
extern "C" {
void abort(void);
#endif
void main(void);
#ifdef __cplusplus
}
#endif

#include<36064s.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include "vs-wrc003.h"

#define led1_on() 			{IO.PDR6.BIT.B4 = 0;}
#define led1_off() 			{IO.PDR6.BIT.B4 = 1;}
#define led2_on() 			{IO.PDR6.BIT.B5 = 0;}
#define led2_off() 			{IO.PDR6.BIT.B5 = 1;}

//センサーの基準値を記憶しておくための変数
int ad_fg[4] = {100,100,100,100}; //ラインのとき
int ad_bg[4] = {0,0,0,0}; //地のとき

//音を指定された時間鳴らして止める関数
void bzr_beep(int freq, int duration) {
	BuzzerSet(freq, 50);
	BuzzerStart();
	Wait(duration);
	BuzzerStop();
}

void wait_space_key() {
	BYTE c = 0;
	do {
		Wait(10);
		SciByteRx(&c);
	} while(c != ' ');
}

void main(void)
{
	//制御周期の設定[単位：Hz　範囲：30.0~]
	const BYTE MainCycle = 60;
	int i;
	
	Init((BYTE)MainCycle);
	InitSci3(CBR_115200, even, 1);
	
	led2_off();
	//センサ調整モード
	wait_space_key();
	for(i = 0; i < 2; i++) {
		ad_fg[i] = AdRead(i); //ラインの色として記憶
	}
	bzr_beep(300, 40);      //高い音を鳴らす
	wait_space_key();
	for(i = 0; i < 2; i++) {
		ad_bg[i] = AdRead(i); //地の色として記憶
	}
	bzr_beep(200, 40);      //低い音を鳴らす

	// 本来はこの下に走行プログラムを書く。
	// 今回はその代わりにセンサーの状態表示プログラム。
	led2_on();
	while(1) {
		BYTE c; // シリアル通信から受信した文字
		char buf[100]; // シリアル通信で送信する文字列
		float sval[2]; // 正規化センサ値x2
		float sum; // 正規化センサ値の合計
		float line_pos; // センサーから見たラインの位置
		// 正規化したセンサ値の計算
		for(i = 0; i < 2; i++) {
			UINT ad = AdRead(i);
			sval[i] = ((float)ad - ad_bg[i]) / (ad_fg[i] - ad_bg[i]);
		}
		// ライン位置の計算と送信
		sum = 0;
		for(i = 0; i < 2; i++) {
			sum += sval[i];
		}
		line_pos = (sval[0] * (-1) + sval[1] * 1) / sum;
		
		if(SciByteRx(&c) == 1) {
			sprintf(buf, "% 4.2f % 4.2f : %4.2f\r\n", sval[0], sval[1], line_pos);
			SciStrTx(buf, strlen(buf));
		}
		Wait(10);
	}
}


#ifdef __cplusplus
void abort(void)
{
}
#endif
