//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <stdio.h>

#include <kernel.h>
#include <t_syslog.h>
#include <t_stdlib.h>
#include "syssvc/serial.h"
#include "syssvc/syslog.h"
#include "kernel_cfg.h"
#include "iodefine.h"

#include "adc.h"
#include "bt.h"
#include "i2c.h"

int sensor_g[3] = {0, 0, 0};

void task_sensor(intptr_t exinf)
{
	syslog(LOG_NOTICE, "task_sensor wakeup");

	init_i2c(I2C_GSENSOR_CH, I2C_GSENSOR_PORT);
	init_adc(ADC_CDS_CH, ADC_CDS_PORT);

	while(1)
	{
		int h, l;
		int i;

		for(i = 0; i < 3; i++)
		{
			i2c_send_start(I2C_GSENSOR_CH, 0x30);
			i2c_send_stop(I2C_GSENSOR_CH, i*2+0);

			i2c_send_restart(I2C_GSENSOR_CH, 0x31);
			h = i2c_recv(I2C_GSENSOR_CH);

			i2c_send_start(I2C_GSENSOR_CH, 0x30);
			i2c_send_stop(I2C_GSENSOR_CH, i*2+1);

			i2c_send_restart(I2C_GSENSOR_CH, 0x31);
			l = i2c_recv(I2C_GSENSOR_CH);

			sensor_g[i] = (((h<<4)|(l>>4))-2048)*1000/819;
		}

		int val = adc_get12bit(ADC_CDS_CH);
		int duty = (val < 1024) ? 60 : 100;
		pwm_set_duty(duty);

#if 1
		char buf[32];
		sprintf(buf, "adc = %d, duty = %d", val, duty);
		syslog(LOG_NOTICE, buf);
#endif

		dly_tsk(100);
	}
}
