#include "HardwareInfo.c"
#include "JMLib.c"
#include <SetLCDBack.h>
#include <SetLCDString.h>
#include <SetLCDRectangle.h>
#include <GetButton1.h>
#include <GetButton2.h>
#include <SetColorSensor.h>
#include <SetInBeep.h>
#include <SetTenthS.h>
#include <GetColorSensor.h>
#include <SetLCD3Char.h>
#include <SetLCDFilledRectangle.h>
#include <SetCentiS.h>

int main(void)
{
    X4RCU_Init();
    unsigned long r = 0;
    unsigned long g = 0;
    unsigned long b = 0;
    unsigned int btn1 = 0;
    unsigned int btn2 = 0;
    unsigned long color = 0;
    unsigned long rgb888 = 0;
    unsigned long color1 = 0;
    unsigned int var0 = 0;
    SetLCDBack(1);
    //硬件接口
    SetLCDString(48, 0, "A1", YELLOW, BLACK);
    //R/G/B分量值
    SetLCDString(48, 32, "R:", YELLOW, BLACK);
    SetLCDString(48, 48, "G:", YELLOW, BLACK);
    SetLCDString(48, 64, "B:", YELLOW, BLACK);
    //原始颜色
    SetLCDString(52, 134, "Color", YELLOW, BLACK);
    SetLCDRectangle(51, 99, 85, 133, 1, YELLOW);
    //颜色识别结果
    SetLCDString(130, 134, "Result", YELLOW, BLACK);
    SetLCDRectangle(131, 99, 165, 133, 1, YELLOW);
    while (1)
    {
        //按键按下进行白平衡处理
        btn1 = GetButton1();
        //按键按下重设白平衡比例值
        btn2 = GetButton2();
        if ( btn1==1 )
        {
            //自动白平衡
            SetColorSensor(_COLOR_1_, 1, 31, 0);
            SetLCDString(0, 158, "White Balance              ", YELLOW, BLACK);
            SetInBeep(1);
            SetTenthS(2);
            SetInBeep(0);
        }
        if ( btn2==1 )
        {
            //重设自动白平衡系数，恢复出厂值
            SetColorSensor(_COLOR_1_, 1, 32, 0);
            SetLCDString(0, 158, "Reset White Balance", YELLOW, BLACK);
            SetInBeep(1);
            SetTenthS(2);
            SetInBeep(0);
        }
        //读红色分量值
        r = GetColorSensor(_COLOR_1_, 1, 1);
        //读绿色分量值
        g = GetColorSensor(_COLOR_1_, 1, 2);
        //读蓝色分量值
        b = GetColorSensor(_COLOR_1_, 1, 3);
        SetLCD3Char(64, 32, r, 63488, BLACK);
        SetLCD3Char(64, 48, g, 2016, BLACK);
        SetLCD3Char(64, 64, b, 31, BLACK);
        //读RGB888颜色数据
        rgb888 = GetColorSensor(_COLOR_1_, 1, 5);
        if(rgb888!=999)
        {
            r=rgb888/65536;
            g=(rgb888-r*65536)/256;
            b=rgb888-r*65536-g*256;
            color=(r/8)*2048+(g/4)*32+b/8;
        }
        else
        {
        color=0;
        }
        SetLCDFilledRectangle(52, 100, 84, 132, color);
        //读颜色识别结果
        var0 = GetColorSensor(_COLOR_1_, 1, 4);
        //将颜色识别结果转换成屏幕颜色
        switch(var0)
        {
        	case 1:		color1=RED;				break;
        	case 2:		color1=GREEN;		break;
        	case 3:		color1=BLUE;			break;
        	case 4:		color1=YELLOW;		break;
        	case 5:		color1=BLACK;			break;
        	case 6:		color1=WHITE;		break;	
        	default :		color1=MAGENTA;	break;//显示错误颜色
        }
        SetLCDFilledRectangle(132, 100, 164, 132, color1);
        SetCentiS(2);
    }
    while(1);
}

