#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;
	
	Init((BYTE)MainCycle);
	InitSci3(CBR_115200, even, 1);
	
	led2_off();
	//センサ調整モード
	wait_space_key();
	ad_fg[0] = AdRead(0); //ラインの色として記憶
	bzr_beep(300, 40);      //高い音を鳴らす
	wait_space_key();
	ad_bg[0] = AdRead(0); //地の色として記憶
	bzr_beep(200, 40);      //低い音を鳴らす

	// 本来はこの下に走行プログラムを書く。
	// 今回はその代わりにシリアル送信プログラム。
	led2_on();
	while(1) {
		BYTE c;
		char buf[100];
		UINT i = AdRead(0);
		// 正規化したセンサ値の計算と送信
		float sval = ((float)i - ad_bg[0]) / (ad_fg[0] - ad_bg[0]);
		if(SciByteRx(&c) == 1) {
			sprintf(buf, "%4d % 5.3f\r\n", i, sval);
			SciStrTx(buf, strlen(buf));
		}
		if(sval > 0.5) {
			led1_on();
		} else {
			led1_off();
		}
		Wait(10);
	}
}


#ifdef __cplusplus
void abort(void)
{
}
#endif
