/********************************** (C) COPYRIGHT *******************************
* File Name          : main.c
* Author             : WCH
* Version            : V1.0.0
* Date               : 2021/08/08
* Description        : Main program body.
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/ 

/*
 *@Note
 模拟USB键盘设备例程，
 OTG_FS_DM(PA11)、OTG_FS_DP(PA12)
 PA0短接到地模拟一次按钮按下， 设备模拟一次键盘上传字符‘w’
*/

#include "debug.h"
#include "ch32f20x_usbotg_device.h"

/* Function statement */
void GPIO_Config( void );
UINT8 Basic_Key_Handle( void );

/* const value definition */
const UINT8 Key_W_Val[ 8 ]    = { 0x00, 0x00, 0x1A, 0x00, 0x00, 0x00, 0x00, 0x00  };
const UINT8 Key_NotPress[ 8 ] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  };

/*********************************************************************
 * @fn      main
 *
 * @brief   Main program.
 *
 * @return  none
 */
int main(void)
{
    UINT8 UpLoadFlag = 0x00;
	Delay_Init();
	USART_Printf_Init(115200);
	printf("SystemClk:%d\r\n",SystemCoreClock);

    /* USBOTG_FS device init */
	printf( "HIDKeyboardDevice Running On USBOTG_FS Controller\n" );
	Delay_Ms(10);
	USBOTG_Init( );

    /* GPIO Config */
    GPIO_Config( );
    
	while(1)
	{
        if( Basic_Key_Handle( ) )
        {
            while( USBHD_Endp1_Up_Flag );
            printf( "u\n" );
            memcpy( pEP1_IN_DataBuf, (UINT8*)Key_W_Val, 8 );
            DevEP1_IN_Deal( 8 );
            UpLoadFlag = 1;
        }
        else
        {
            if( UpLoadFlag )
            {
                while( USBHD_Endp1_Up_Flag );
                printf( "n\n" );
                memcpy( pEP1_IN_DataBuf, (UINT8*)Key_NotPress, 8 );
                DevEP1_IN_Deal( 8 );
                UpLoadFlag = 0;
            }
        }        
    }
}

/*********************************************************************
 * @fn      GPIO_Config
 *
 * @brief   GPIO Configuration Program
 *
 * @return  none
 */
void GPIO_Config( void )
{
    GPIO_InitTypeDef GPIO_InitTypdefStruct={0};

    RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA, ENABLE );
    GPIO_InitTypdefStruct.GPIO_Pin   = GPIO_Pin_0;
    GPIO_InitTypdefStruct.GPIO_Mode  = GPIO_Mode_IPU;
    GPIO_InitTypdefStruct.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init( GPIOA, &GPIO_InitTypdefStruct );
}

/*********************************************************************
 * @fn      Basic_Key_Handle
 *
 * @brief   Basic Key Handle
 *
 * @return  0 - no key press
 *          1 - key press down
 */
UINT8 Basic_Key_Handle( void )
{
    UINT8 keyval = 0;
    if( ! GPIO_ReadInputDataBit( GPIOA, GPIO_Pin_0 ) )
    {
        Delay_Ms(20);
        if( ! GPIO_ReadInputDataBit( GPIOA, GPIO_Pin_0 ) )
        {
            keyval = 1;
        }
    }

    return keyval;
}




