#include "key.h"

void LED_Init(void)
{
    rt_pin_mode(LED_R, PIN_MODE_OUTPUT);
    rt_pin_mode(LED_G, PIN_MODE_OUTPUT);
    rt_pin_mode(LED_B, PIN_MODE_OUTPUT);
    rt_pin_write(LED_R, PIN_HIGH);
    rt_pin_write(LED_G, PIN_HIGH);
    rt_pin_write(LED_B, PIN_HIGH);
}
void Key_Init(void){
    rt_pin_mode(KEY1_PIN,PIN_MODE_INPUT_PULLUP);//KEY1  上拉输入
    rt_pin_mode(KEY2_PIN,PIN_MODE_INPUT_PULLUP);//KEY2  上拉输入
}

// 测试
static struct rt_thread key_thread;  //线程控制块
ALIGN(RT_ALIGN_SIZE)  // 线程栈字节对齐
static uint8_t key_thread_stack[512];//线程栈

void Key1_Press(void)
{
    rt_kprintf("Key1_Press\n");
}
void Key1_Release(void)
{
    rt_kprintf("Key1_Release\n");
}
void Key2_Press(void)
{
    rt_kprintf("Key2_Press\n");
}
void Key2_Release(void)
{
    rt_kprintf("Key2_Release\n");
}
//线程按键扫描函数
static void key_thread_entry(void *parameter)
{
    Key_Init();
    LED_Init();
    while (1)
    {
        if(rt_pin_read(KEY1_PIN)==0)
        {
            rt_thread_mdelay(20);
            if(rt_pin_read(KEY1_PIN)==0)
            {
                //rt_kprintf("KE1\n");
                Key1_Press();
                while(rt_pin_read(KEY1_PIN)==0)
                {
                    rt_thread_mdelay(5);
                }
                Key1_Release();
            }
        }
        if(rt_pin_read(KEY2_PIN)==0)
        {
            rt_thread_mdelay(20);
            if(rt_pin_read(KEY2_PIN)==0)
            {
                //rt_kprintf("KE2\n");
                Key2_Press();
                while(rt_pin_read(KEY2_PIN)==0)
                {
                    rt_thread_mdelay(5);
                }
                Key2_Release();
            }
        }
        rt_thread_mdelay(50);//按键状态查询周期 50ms
    }
}
//KEY线程初始化
static int rtt_key(void)
{
    rt_thread_t tid_key = rt_thread_create("KEY_SCAN", //线程1的名称是t1
            key_thread_entry, RT_NULL, //入口是thread1_entry，参数是RT_NULL
            512, //线程堆栈大小
            2, //线程优先级
            20);//时间片tic
    /* 如果获得线程控制块，启动这个线程 */
        if (tid_key != RT_NULL)
        {
            rt_thread_startup(tid_key);
            rt_kprintf("--Key_Thread_Init--\n");
        }

        return 0;
}
//INIT_APP_EXPORT(Key_Thread_Init);  // 初始化线程
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(rtt_key, thread init);
