/**
  ******************************************************************************
  * @file    USART/Printf/main.c 
  * @author  MCD Application Team
  * @version V3.3.0
  * @date    04/16/2010
  * @brief   Main program body
  ******************************************************************************
  * @copy
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2010 STMicroelectronics</center></h2>
  */ 

/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "stm32_eval.h"
#include "delay.h"		   
#include "NRF24L01.h"
#include "spi.h"
#include <stdio.h>
/** @addtogroup STM32F10x_StdPeriph_Examples
  * @{
  */

/** @addtogroup USART_Printf
  * @{
  */ 

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/*神州III号LED灯相关定义*/
#define RCC_GPIO_LED                    RCC_APB2Periph_GPIOE    /*LED使用的GPIO时钟*/
#define LEDn                            4                       /*神舟III号LED数量*/
#define GPIO_LED                        GPIOE                   /*神舟III号LED灯使用的GPIO组*/

#define DS1_PIN                         GPIO_Pin_4              /*DS1使用的GPIO管脚*/
#define DS2_PIN                         GPIO_Pin_5				/*DS2使用的GPIO管脚*/
#define DS3_PIN                         GPIO_Pin_6  			/*DS3使用的GPIO管脚*/
#define DS4_PIN                         GPIO_Pin_7				/*DS4使用的GPIO管脚*/

/*神州III号按键相关定义*/
#define RCC_KEY1                                    RCC_APB2Periph_GPIOC
#define GPIO_KEY1_PORT                              GPIOC    
#define GPIO_KEY1                                   GPIO_Pin_6

#define RCC_KEY2                                    RCC_APB2Periph_GPIOD
#define GPIO_KEY2_PORT                              GPIOD  
#define GPIO_KEY2                                   GPIO_Pin_14

#define RCC_KEY3                                    RCC_APB2Periph_GPIOD
#define GPIO_KEY3_PORT                              GPIOD    
#define GPIO_KEY3                                   GPIO_Pin_13 

#define RCC_KEY4                                    RCC_APB2Periph_GPIOA
#define GPIO_KEY4_PORT                              GPIOA    
#define GPIO_KEY4                                   GPIO_Pin_0 

#define GPIO_KEY_ANTI_TAMP                          GPIO_KEY3
#define GPIO_KEY_WEAK_UP                            GPIO_KEY4


/* Values magic to the Board keys */
#define  NOKEY  0
#define  KEY1   1
#define  KEY2   2
#define  KEY3   3
#define  KEY4   4
/*无线模块工作模式*/
#define IDLE   0
#define RX_MODE 1
#define TX_MODE 2


USART_InitTypeDef USART_InitStructure;				  //串口声明
/* Private function prototypes -----------------------------------------------*/
u8 ReadKeyDown(void);
void LED_config(void);
void KEY_Config(void);
void WIRELESS_MODE_SET(void);
#ifdef __GNUC__
  /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
     set to 'Yes') calls __io_putchar() */
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
 

    u8 WireLess_Work_Mode = IDLE;


/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
	u8 key;
	u16 t=0;			 
	u8 i=0;
	u8 tmp_buf[33];
    u8 txdata;
	 /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */     

    LED_config();        //LED使用的GPIO接口初始化
    GPIO_SetBits(GPIO_LED,DS1_PIN|DS2_PIN|DS3_PIN|DS4_PIN); //关闭所有的LED指示灯
   
    /* USARTx configured as follow:
        - BaudRate = 115200 baud  
        - Word Length = 8 Bits
        - One Stop Bit
        - No parity
        - Hardware flow control disabled (RTS and CTS signals)
        - Receive and transmit enabled
    */
    USART_InitStructure.USART_BaudRate = 115200;					//配置串口
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    STM_EVAL_COMInit(COM1, &USART_InitStructure);	   //串口使用声明
  
    KEY_Config();      //按键使用的GPIO接口初始化
  
    delay_init(72);		//延时初始化  	
  
    NRF24L01_Init();    //初始化NRF24L01 		
  
    while(NRF24L01_Check())//检测不到24L01
    {
        printf("nRF24L01检测出错!请确认nRF24L01的连接! \n\r");
		delay_ms(1000);
    }
    printf("\n\r--------------------------------------");
    printf("\n\r 神舟III号2.4G无线模块实验程序");
	printf("\n\r\n\r 请设置NRF24L01无线模块的工作模式");
	printf("\n\r   --USER1 按键:设置NRF24L01为接收模式");
	printf("\n\r   --USER2 按键:设置NRF24L01为发送模式");
	printf("\n\r   --TAMEPR按键:退出NRF24L01发送接收");
    printf("\n\r--------------------------------------");

    while(1)
    {
    	if(WireLess_Work_Mode == RX_MODE)//RX模式
	    { 
	    	RX_Mode();		  
		    while(1)
    		{	  		    		    				 
	    		if(NRF24L01_RxPacket(tmp_buf)==0)//一旦接收到信息,则显示出来.
		    	{
			    	tmp_buf[32]=0;//加入字符串结束符
				    printf("\n\r接收到数据为:");
    				for (i=0;i < 32;i++)
	    			{
		    	    	printf("%c",tmp_buf[i]);
			    	}
	    		}
		    }	
	    }
    	else if(WireLess_Work_Mode == TX_MODE)       //TX模式
	    {							    	
    		TX_Mode();
	    	txdata=' ';//从空格键开始  
		    while(1)
    		{	  		   				 
	    		if(NRF24L01_TxPacket(tmp_buf)==TX_OK)
		    	{
			    	printf("\n\r正在发送数据: ");
				    key=txdata;
    				for(t=0;t<32;t++)
	    			{
		    		    key++;
			    	    if(key>('~'))
                        {            
                            key=' ';
                        }
    				    tmp_buf[t]=key;	
    	    			printf("%c",tmp_buf[t]);
	    	    	}
			    	txdata++; 
    			    if(txdata>'~')
                    {
                        txdata=' ';     
                    }
	    	    	tmp_buf[32]=0;//加入结束符
		    	    delay_ms(500);
						   
    			}
                else
        		{										   	
	        		printf("\n\r请确认接收端是否正常");		
                    delay_ms(500);	    
		        }
                delay_ms(1000);	    

	    	}
	    }
        else
        {
            WIRELESS_MODE_SET();   
        }
    }
   
}

/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART */
  USART_SendData(EVAL_COM1, (uint8_t) ch);		//字节发送

  /* Loop until the end of transmission */
  while (USART_GetFlagStatus(EVAL_COM1, USART_FLAG_TC) == RESET)	  //等待发送完毕
  {}

  return ch;
}

/*******************************************************************************
* Function Name  : ReadKey
* Description    : Reads key from demoboard.
* Input          : None
* Output         : None
* Return         : Return RIGHT, LEFT, SEL, UP, DOWN or NOKEY
*******************************************************************************/
u8 ReadKeyDown(void)							   //按钮扫描
{
  /* 1 key is pressed */
  if(!GPIO_ReadInputDataBit(GPIO_KEY1_PORT, GPIO_KEY1))
  {
  	while(!GPIO_ReadInputDataBit(GPIO_KEY1_PORT, GPIO_KEY1))	   //按钮1按下
	{
		;//reserved
	}
    return KEY1; 
  }	
  /* 2 key is pressed */
  if(!GPIO_ReadInputDataBit(GPIO_KEY2_PORT, GPIO_KEY2))		   //按钮2按下
  {
  	while(!GPIO_ReadInputDataBit(GPIO_KEY2_PORT, GPIO_KEY2))
	{
		;//reserved
	}
    return KEY2; 
  }
  if(!GPIO_ReadInputDataBit(GPIO_KEY3_PORT, GPIO_KEY3))		   //按钮TAMPER按下
  {
  	while(!GPIO_ReadInputDataBit(GPIO_KEY3_PORT, GPIO_KEY3))
	{
		;//reserved
	}
    return KEY3; 
  }
  
  /* No key is pressed */
  else 
  {
    return NOKEY;
  }
}

void KEY_Config(void)					//按钮配置函数
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Configure KEY1 Button */
  RCC_APB2PeriphClockCmd(RCC_KEY1, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_InitStructure.GPIO_Pin = GPIO_KEY1;
  GPIO_Init(GPIO_KEY1_PORT, &GPIO_InitStructure);

  /* Configure KEY2 Button */
  RCC_APB2PeriphClockCmd(RCC_KEY2, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_InitStructure.GPIO_Pin = GPIO_KEY2;
  GPIO_Init(GPIO_KEY2_PORT, &GPIO_InitStructure);

  /* Configure KEY3 Button */
  RCC_APB2PeriphClockCmd(RCC_KEY3, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_InitStructure.GPIO_Pin = GPIO_KEY3;
  GPIO_Init(GPIO_KEY3_PORT, &GPIO_InitStructure);  

  /* Configure KEY4 Button */
  RCC_APB2PeriphClockCmd(RCC_KEY4, ENABLE);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_InitStructure.GPIO_Pin = GPIO_KEY4;
  GPIO_Init(GPIO_KEY4_PORT, &GPIO_InitStructure);

}

void LED_config(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  /* Enable GPIOB, GPIOC and AFIO clock */
  RCC_APB2PeriphClockCmd(RCC_GPIO_LED | RCC_APB2Periph_AFIO , ENABLE);  
  
  /* LEDs pins configuration */
  GPIO_InitStructure.GPIO_Pin = DS1_PIN | DS2_PIN | DS3_PIN | DS4_PIN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(GPIO_LED, &GPIO_InitStructure);
}

void WIRELESS_MODE_SET(void)
{
        if(ReadKeyDown() == KEY1)
        {
            WireLess_Work_Mode = TX_MODE;
		    printf("\n\rNRF24L01 发送模式设置成功");
            
        }
        
        else if(ReadKeyDown() == KEY2)
        {
            WireLess_Work_Mode = RX_MODE;
	  	    printf("\n\rNRF24L01 接收模式设置成功");   
    	   	printf("\n\r等待接收数据");            
        }
        else if(ReadKeyDown() == KEY3)
        {
        
            WireLess_Work_Mode = IDLE;
            printf("\n\r 退出发送接收，请重新设置工作模式");
			printf("\n\r USER1按键:设置NRF24L01为接收模式");
	        printf("\n\r USER2按键:设置NRF24L01为发送模式");
        }
        

}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */ 

/**
  * @}
  */ 

/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
