YC3121_PT26\Source:Interface.c开始

//                    Interface.c



/*********************************************************************
*File Name      : Interface.c
*CPU            : STM32F10XVC(ARM 32-bit Cortex-M3 CPU)
*Description    : 打印机与CPU之间的接口源文件
* Designe	      : XXXXXXXXXX
*********************************************************************/

#include "type.h"
#include "board_config.h"
#include "yc_timer.h"
#include "yc_systick.h"
#include "Interface.h"
//#include "usb_lib.h"
#include "PrtHead.h"
#include "misc.h"
#include "BT_BLE.h"
#include "yc_uart.h"
#include "yc_bt.h"
#include "RcvBuf.h"
#include "yc_wdt.h"
#include "PrtBuf.h"
#include "Sensor.h"
#include "app.h"

#define ADC1_DR_Address    ((u32)0x4001244C)

u32  iBaudRate;
static SemaphoreHandle_t SPIMutexHandle = NULL;

unsigned char Zimotemp[72];
void ScanFlash(void);

void RCC_Configuration(void);
void GPIO_Configuration(void);
void NVIC_Configuration(void);
void SysTick_Configuration(void);
void Tim_Configuration(void);
void USART_Configuration(void);
void ADC_Configuration(void);
void SPI_Configuration(void);
void IWDG_Configuration(void);
void FLASH_ReadProtection(void);
void Cpu_Init(void);
void PrinterBusy(unsigned char Status);

void SerialSendByte(unsigned char SendByte);


//PCT25VF080B
u8	SPI_Read_StatusReg(void);
u8	SPI_Read_ID1(void);
u8	SPI_Read_Byte(u32 Dst_Addr);
u8	SPI_FastRead_Byte(u32 Dst_Addr);
u8	SPI_Get_Byte(void);

void SPI_EnWrite_StatusReg(void);
void SPI_Write_StatusReg(u8 byte);
void SPI_Write_Enable(void);
void SPI_Write_Disable(void);
void SPI_Read_nBytes(u32 Dst_Addr, u8 *Data, int nBytes);
void SPI_FastRead_nBytes(u32 Dst_Addr,u8 *Data , int nBytes);
void SPI_Write_Byte(u32 Dst_Addr, u8 byte);
void SPI_Write_2Bytes(u32 Dst_Addr, u8 Data1,u8 Data2);
void SPI_Write_nBytes(u32 Dst_Addr, u8 *Data, int nBytes);
void SPI_Erase_Chip(void);
void SPI_Erase_Sector(u32 Dst_Addr);
void SPI_Wait_Busy(void);
void SPI_Send_Byte(u8 out);


//void USB_Init(void);
void usb_inial(void);

void usb0_respond(byte const *buff,byte size);


typedef struct
{
    GPIO_TypeDef 	port;
	uint16_t		pin;
	FunctionalState	f_pullup;	
	uint8_t			dir;
	uint8_t 		out_bit;
} USER_PORT_STRUCT;

const USER_PORT_STRUCT gpio_init_buff[]={
	//por				     pin			    pull    dir out_bit

	//tph
	{TPH_SPI_CLK_PORT,		TPH_SPI_CLK_PIN,	ENABLE,	1,	1},    //TPH_CLK
	{TPH_SPI_MOSI_PORT,		TPH_SPI_MOSI_PIN,	ENABLE,	1,	1},    //TPH_DAT
	{TPH_SPI_CS_PORT,		TPH_SPI_CS_PIN,		ENABLE,	1,	1},        //TPH_LAT
	{TPH_STB1_PORT,			TPH_STB1_PIN,		ENABLE,	1,	0},       //
	{TPH_STB2_PORT,			TPH_STB2_PIN,		ENABLE,	1,	0},

	
	{TPH_MDEN_PORT,			TPH_MDEN_PIN, 		ENABLE, 1,	0},



	{FLASH_SPI_MOSI_PORT,	FLASH_SPI_MOSI_PIN,	ENABLE,	1,	1},
	{FLASH_SPI_MISO_PORT,	FLASH_SPI_MISO_PIN,	ENABLE,	0,	1},
	{FLASH_SPI_CLK_PORT,	FLASH_SPI_CLK_PIN,	ENABLE,	1,	1},
	{FLASH_SPI_CS_PORT,		FLASH_SPI_CS_PIN,	ENABLE,	1,	1},


	

#ifdef  USE_LCD_IIC_PORT

	{LCD_IIC_SDA_PORT,		LCD_IIC_SDA_PIN,	ENABLE,	1,	1},
	{LCD_IIC_CLK_PORT,		LCD_IIC_CLK_PIN,	ENABLE,	1,	1},
	{LCD_CS_PORT,			LCD_CS1_PIN,		ENABLE,	1,	0},
	{LCD_RST_PORT,			LCD_RST_PIN,		ENABLE,	1,	1},
	//{LCD_PWR_PORT,			LCD_PWR_PIN,	ENABLE,	1,	0},
#else

	{LCD_SDA_PORT,		    LCD_SDA_PINT,	    ENABLE, 1,	1},
	{LCD_CLK_PORT,		    LCD_CLK_PIN,	    ENABLE, 1,	1},
	{LCD_CS_PORT,		    LCD_CS1_PIN, 	    ENABLE, 1,	1},
	{LCD_RST_PORT,		    LCD_RST_PIN,	    ENABLE, 1,	1},
//	{LCD_DC_PORT,               LCD_DC_PIN,	    ENABLE, 1,	1},
	//{LCD_PWR_PORT,		    LCD_PWR_PIN,	    ENABLE, 1,	0},

#endif

	{Head_En_PORT,		    Head_En_PIN, 	    ENABLE, 1,	1},



	{STEP_MOTOR_A1_PORT,	STEP_MOTOR_A1_PIN,	ENABLE,	1,	0},
	{STEP_MOTOR_A2_PORT,	STEP_MOTOR_A2_PIN,	ENABLE,	1,	0},
	{STEP_MOTOR_B1_PORT,	STEP_MOTOR_B1_PIN,	ENABLE, 1,	0},
	{STEP_MOTOR_B2_PORT,	STEP_MOTOR_B2_PIN,	ENABLE, 1,	0},
	{STEP_MOTOR_EN_PORT,	STEP_MOTOR_EN_PIN,	ENABLE, 1,	0},
	{TPH_POWER_EN_PORT,	TPH_POWER_EN_PIN,   ENABLE,	1,	0},
	{BM_E0_PORT,			BM_E0_PIN,			ENABLE,	1,	0},
	{BM_E1_PORT,			BM_E1_PIN,			ENABLE,	1,	0},
	{gap_e3_port,				gap_e3_pin,			ENABLE,	1,	0},
	{gap_e2_port,				gap_e2_pin,			ENABLE,	1,	0},
	
	{KEY_WAKE_PORT,			KEY_WAKE_PIN,		DISABLE, 0,	0},
	{KEY_SET_PORT,			KEY_SET_PIN,		ENABLE, 0,	1},


	{SYS_POWER_EN_PORT,		SYS_POWER_EN_PIN,	ENABLE, 1,	1},
	{PORT_CHARGE_STATE,		PIN_CHARGE_STATE,	ENABLE, 0,	1},
	//{BEEP_PORT,				BEEP_PIN,			ENABLE, 1,	0},
	//{USB_PLUG_IN_PORT,		USB_PLUG_IN_PIN,	ENABLE, 0,	1},
	{UART0_RX_PORT,			UART0_RX_PIN,		ENABLE, 0,	1},

	
};
/*******************************************************************************
** Function name:    GPIO_Configuration    
**
** Descriptions :    GPIO模式配置
**  
*******************************************************************************/

void GPIO_Configuration(void){

	GPIO_InitTypeDef GPIO_InitStruct;

	uint8_t gpio_init_buff_size;
	uint8_t i;


    gpio_init_buff_size = (uint8_t)(sizeof(gpio_init_buff)/sizeof(USER_PORT_STRUCT));

	MyPrintf("gpio_init_buff_size = %d\n",gpio_init_buff_size);

	enable_gpio_32();
	for(i=0;i<gpio_init_buff_size;i++){


		if(gpio_init_buff[i].dir == 1){
			
			GPIO_InitStruct.GPIO_Pin = gpio_init_buff[i].pin;
			GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
			GPIO_Init(gpio_init_buff[i].port, &GPIO_InitStruct);
			if(gpio_init_buff[i].out_bit){
				GPIO_SetBits(gpio_init_buff[i].port,gpio_init_buff[i].pin);
			}
			else{
				GPIO_ResetBits(gpio_init_buff[i].port,gpio_init_buff[i].pin);
			}
		}
		else{
			GPIO_InitStruct.GPIO_Pin = gpio_init_buff[i].pin;

			if(gpio_init_buff[i].f_pullup)
				GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
			else
				
				GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
			GPIO_Init(gpio_init_buff[i].port, &GPIO_InitStruct);



		}
	}


}


/*******************************************************************************
** Function name:    NVIC_Configuration    
**
** Descriptions :    中断向量配置及优先级别设置
**  
*******************************************************************************/
void NVIC_Configuration(void)
{

}
/*******************************************************************************
** Function name:   Tim_Configuration    
**
** Descriptions :   定时器配置
**  
*******************************************************************************/
void Tim_Configuration(void)
{
	TIM_InitTypeDef TIM_InitStruct;	
	TIM_InitStruct.period = 48000;
	TIM_InitStruct.TIMx = TIM1;
	TIM_Init(&TIM_InitStruct);	
	TIM_ModeConfig(TIM1, TIM_Mode_TIMER);
	TIM_Cmd(TIM1, ENABLE);	//key
	NVIC_EnableIRQ(TIM1_IRQn);
	NVIC_SetPriority(TIM1_IRQn, 0);	         //数字越小,优先级越高
	Timer_key_SetCounter(10000);
	//Timer_key_SetCounter(1000);
	
	TIM_InitStruct.period = 48000;
	TIM_InitStruct.TIMx = TIM2;
	TIM_Init(&TIM_InitStruct);	
	TIM_ModeConfig(TIM2, TIM_Mode_TIMER);
	TIM_Cmd(TIM2, DISABLE);	//STEP_MOTOR
	NVIC_EnableIRQ(TIM2_IRQn);
	NVIC_SetPriority(TIM2_IRQn, 1);	
	
	TIM_InitStruct.period = 48000;       
	TIM_InitStruct.TIMx = TIM3;             
	TIM_Init(&TIM_InitStruct);	
	TIM_ModeConfig(TIM3, TIM_Mode_TIMER);      
	TIM_Cmd(TIM3, DISABLE);//TPH                打印头加热时间中断
	NVIC_EnableIRQ(TIM3_IRQn);
	NVIC_SetPriority(TIM3_IRQn, 1);

	TIM_InitStruct.period = 48000;
	TIM_InitStruct.TIMx = TIM4;
	TIM_Init(&TIM_InitStruct);	
	TIM_ModeConfig(TIM4, TIM_Mode_TIMER);
	TIM_Cmd(TIM4, DISABLE);	//SYSBASE 	
	NVIC_EnableIRQ(TIM4_IRQn);
	NVIC_SetPriority(TIM4_IRQn, 2);

//	TIM_InitStruct.period = 65530;
	TIM_InitStruct.TIMx = TIM7;
	TIM_Init(&TIM_InitStruct);	
	TIM_ModeConfig(TIM7, TIM_Mode_TIMER);
	TIM_Cmd(TIM7, ENABLE);	//Lcd
	NVIC_EnableIRQ(TIM7_IRQn);
	NVIC_SetPriority(TIM7_IRQn, 20);	               //屏幕刷新优先级放最低
	Timer_Lcd1_SetCounter(100000);
	
}
/*******************************************************************************
** Function name:  BlueTooth_Configuration    
**
** Descriptions :  串口1(蓝牙通信)配置
**  
*******************************************************************************/
void USART_Configuration(void)
{
	UART_InitTypeDef UART_InitStruct;
	
	/* Configure serial ports 0 RX and TX for IO. */
	GPIO_Config(GPIOA, GPIO_Pin_1, UART0_TXD);
	GPIO_Config(GPIOA, GPIO_Pin_0, UART0_RXD);


	/* USARTx configured as follow:
	- BaudRate = 115200 baud
	- Word Length = 8 Bits
	- Stop Bit = 1 Stop Bit
	- Parity = No Parity
	- Hardware flow control disabled (RTS and CTS signals)
	- Receive and transmit enabled
	*/
	UART_InitStruct.BaudRate = 921600;			//Configure serial port baud rate, the baud rate defaults to 128000.
	UART_InitStruct.DataBits = Databits_8b;
	UART_InitStruct.StopBits = StopBits_1;
	UART_InitStruct.Parity = Parity_None;
	UART_InitStruct.FlowCtrl = FlowCtrl_None;
	UART_InitStruct.Mode = Mode_duplex;

	UART_Init(UART0, &UART_InitStruct);
	


}
/*******************************************************************************
** Function name:   ADC_Configuration    
**
** Descriptions :   AD配置
**  
*******************************************************************************/
void ADC_Configuration(void)
{
    ADC_InitTypeDef ADCInitStruct;

	GPIO_Config(ADC_IO_PORT, ADC1_IO_PIN, ANALOG);  //ADC??????IO??
	GPIO_Config(ADC_IO_PORT, ADC2_IO_PIN, ANALOG);
	GPIO_Config(ADC_IO_PORT, ADC3_IO_PIN, ANALOG);
	GPIO_Config(ADC_IO_PORT, ADC4_IO_PIN, ANALOG);
	
    ADCInitStruct.ADC_Channel = ADC_CHANNEL_1;
    ADCInitStruct.ADC_Mode = ADC_GPIO;
    ADC_Init(&ADCInitStruct);

}

/*******************************************************************************
** Function name:   SPI_Configuration    
**
** Descriptions :   SPI配置 用于读取外部FLASH
**  
*******************************************************************************/
void SPI_Configuration(void)
{	
    SPI_InitTypeDef SPI_InitStruct;	
	
    //GPIO_Config(GPIOC, GPIO_Pin_0, SPID0_MISO);
    GPIO_Config(TPH_SPI_MOSI_PORT	,TPH_SPI_MOSI_PIN	,SPID0_MOSI);
    GPIO_Config(TPH_SPI_CS_PORT		,TPH_SPI_CS_PIN		,SPID0_NCS);
    GPIO_Config(TPH_SPI_CLK_PORT	,TPH_SPI_CLK_PIN	,SPID0_SCK);


    SPI_InitStruct.Mode = SPI_Mode_Master;
    SPI_InitStruct.BaudRatePrescaler = SPI_BaudRatePrescaler_16;//48M/2/8=3MHZ
    SPI_InitStruct.CPHA = SPI_CPHA_Second_Edge;
    SPI_InitStruct.CPOL = SPI_CPOL_High;
    SPI_InitStruct.RW_Delay = 33;

	MyPrintf("SPI_Init TPH_SPI\n");
    SPI_Init(TPH_SPI, &SPI_InitStruct);

#if 1

    GPIO_Config(FLASH_SPI_MISO_PORT, FLASH_SPI_MISO_PIN, SPID1_MISO);
    GPIO_Config(FLASH_SPI_MOSI_PORT	,FLASH_SPI_MOSI_PIN	,SPID1_MOSI);
    GPIO_Config(FLASH_SPI_CS_PORT	,FLASH_SPI_CS_PIN	,SPID1_NCS);
    GPIO_Config(FLASH_SPI_CLK_PORT	,FLASH_SPI_CLK_PIN	,SPID1_SCK);

    SPI_InitStruct.Mode = SPI_Mode_Master;
    SPI_InitStruct.BaudRatePrescaler = SPI_BaudRatePrescaler_8;//48M/2/8=3MHZ
    SPI_InitStruct.CPHA = SPI_CPHA_Second_Edge;
    SPI_InitStruct.CPOL = SPI_CPOL_High;
    SPI_InitStruct.RW_Delay = 33;

	MyPrintf("SPI_Init FLASH_SPI\n");
    SPI_Init(FLASH_SPI, &SPI_InitStruct);



	MyPrintf("SPI_EnWrite_StatusReg 1\n");
	SPI_EnWrite_StatusReg(); //Enable 	
	MyPrintf("SPI_Write_StatusReg 1\n");
	SPI_Write_StatusReg(0x00); //Write 0x00
	MyPrintf("SPI_Write_Disable 1\n");
	SPI_Write_Disable();
#endif
//    SPIMutexHandle = xSemaphoreCreateMutex();
	MyPrintf("xSemaphoreCreateMutex %d\n", SPIMutexHandle);
}

/*******************************************************************************
** Function name:    FLASH_ReadProtection    
**
** Descriptions :    Flsah读保护
**  
*******************************************************************************/
void FLASH_ReadProtection(void)
{	
#if 0
	if(FLASH_GetReadOutProtectionStatus() == RESET)
	{
		FLASH_Unlock();
		FLASH_ReadOutProtection(ENABLE);
		NVIC_SystemReset();
	}
#endif
}

void delay_mcs(unsigned char mm)
{
   unsigned int i,j;
   
   for(i=0;i<mm;i++)
   {

      for(j=0;j<1000;j++)
      {
        ;
	  }
   }

}

///*

void test_3(unsigned char mm)
{


        if(mm==1)
       	{
			gap_e3_on;
		}

        else
       	{
			gap_e3_off;
		}
	


}

void test_2(unsigned char mm)
{


        if(mm==1)
       	{
			gap_e2_on;
		}

        else
       	{
			gap_e2_off;
		}
	


}

//*/

void test_1(void)
{
    static mm=0;

	if(mm==0)
	{
		mm=1;
		gap_e2_on;

	}
	else if(mm==1)
	{
		mm=0;
		gap_e2_off;

	}




}



void charge_enable(void)
{

	Head_En_OFF;
}


void charge_disable(void)
{
	Head_En_ON;
}

/*******************************************************************************
** Function name:   PowerKey_Configuration    
**
** Descriptions :   电源按键中断模式
**  
*******************************************************************************/
/*void PowerKey_Configuration(void)
{
	EXTI_InitTypeDef EXTI_InitStructure;
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource15);
	EXTI_InitStructure.EXTI_Line = EXTI_Line15;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;	//先屏蔽掉
	EXTI_Init(&EXTI_InitStructure);
}*/
/*******************************************************************************
** Function name:   Cpu_Init    
**
** Descriptions :   CPU初始化函数
**  
*******************************************************************************/	
void Cpu_Init(void)
{
	//RCC_Configuration();//时钟配置
	//NVIC_Configuration();//中断向量控制器配置
	SYSCTRL_HCLKConfig(SYSCTRL_HCLK_Div_None);
	SysTick_Config(CPU_MHZ/1000);
	//WDT_Configuration();
	GPIO_Configuration();//GPIO配置




	//USB_Connect;
	//USB_Init();//USB初始化配置--//USB功能打开后,SPI_DMA只有CLOCK没有数据
       usb_inial();
	USART_Configuration();
	ADC_Configuration();//ADC配置
	SPI_Configuration();//SPI总线配置
	
	Tim_Configuration();//定时器配置

#ifdef USE_BLE
	Ble_Confication();
#endif

//    MyPrintf("PWM_Configuration\r\n");
#ifdef USE_PWM_BEEP
	PWM_Configuration();
#else
	MusicPlay();
#endif



}

/*******************************************************************************
** Function name:   SerialSendByte
**
** Descriptions :    串口发送一个字节
**  
*******************************************************************************/	
void SerialSendByte(unsigned char SendByte)
{
	UART_SendData(UART0,SendByte);
}
/*******************************************************************************
** Function name:   SerialSendBuff
**
** Descriptions :    串口发送一个字节
**  
*******************************************************************************/	
void SerialSendBuff(unsigned char *SendBuff,unsigned int leng)
{
	unsigned int i;
	for(i=0;i<leng;i++)
	UART_SendData(UART0,SendBuff[i]);
}

/*******************************************************************************
** Function name:     PCT25VF080B    
**
** Descriptions :     SPI读取外部Flash功能函数
**  
*******************************************************************************/	
// PCT25VF080B 8Mbit SPI Serial Flash Function
void SPI_EnWrite_StatusReg(void)
{	
	SPI_Wait_Busy();
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_EnWriteSR);
	FLASH_CS_SET;
}

u8	SPI_Read_StatusReg(void)
{	
	u8 byte = 0;
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_ReadStatusReg);
	byte = SPI_Get_Byte();
	FLASH_CS_SET;
	return byte;
}

void SPI_Write_StatusReg(u8 byte)
{
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_WriteStatusReg);
	SPI_Send_Byte(byte);
	FLASH_CS_SET;
	SPI_Wait_Busy();
}

void SPI_Write_Enable(void)
{
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_WriteEnable);
	FLASH_CS_SET;
}

void SPI_Write_Disable(void)
{	
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_WriteDisable);
	FLASH_CS_SET;
}

u8 SPI_Read_ID1(void)
{	

	uint8_t byte = 0;

	uint8_t TxBuff[5] = {FLASH_DeviceID, 0, 0, 0,0xFF};

	FLASH_CS_RESET;

	SPI_SendAndReceiveData(FLASH_SPI, TxBuff, 5, &byte, 1);

	FLASH_CS_SET;

	return byte;
}

u8 SPI_Read_Byte(u32 Dst_Addr)//从片外读1个字节
{
	uint8_t byte = 0;


	uint8_t TxBuff[5] = {FLASH_FastReadData, Dst_Addr >> 16, Dst_Addr >> 8, Dst_Addr,0xFF};

    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return byte;
    }

	FLASH_CS_RESET;

	SPI_SendAndReceiveData(FLASH_SPI, TxBuff, 5, &byte, 1);

	FLASH_CS_SET;
    xSemaphoreGive(SPIMutexHandle);

	return byte;
}

void SPI_Read_nBytes(u32 Dst_Addr, u8 *Data, int nBytes)//从片外读n个字节
{


	uint16_t i;

    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return ;
    }
	for(i=0;i<nBytes;i++){
        uint8_t TxBuff[5] = {FLASH_FastReadData, (Dst_Addr + i) >> 16, (Dst_Addr + i) >> 8, (Dst_Addr + i),0xFF};
        FLASH_CS_RESET;
        SPI_SendAndReceiveData(FLASH_SPI, TxBuff, 5, &Data[i], 1);
        FLASH_CS_SET;
	}
    xSemaphoreGive(SPIMutexHandle);
}
u8	SPI_FastRead_Byte(u32 Dst_Addr)//从片外读1个字节
{
	uint8_t byte = 0;
	uint8_t TxBuff[5] = {FLASH_FastReadData, Dst_Addr >> 16, Dst_Addr >> 8, Dst_Addr,0xFF};
    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return byte;
    }
	FLASH_CS_RESET;
	SPI_SendAndReceiveData(FLASH_SPI, TxBuff, 5, &byte, 1);
	FLASH_CS_SET;
    xSemaphoreGive(SPIMutexHandle);
	return byte;
}
void SPI_FastRead_nBytes(u32 Dst_Addr,u8 *Data ,int nBytes)//从片外读n个字节
{
	uint8_t TxBuff[5] = {FLASH_FastReadData, Dst_Addr >> 16, Dst_Addr >> 8, Dst_Addr,0xFF};
    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return;
    }
	FLASH_CS_RESET;
	SPI_SendAndReceiveData(FLASH_SPI, TxBuff, 5, Data, nBytes);
	FLASH_CS_SET;
    xSemaphoreGive(SPIMutexHandle);
}
void SPI_Write_Byte(u32 Dst_Addr, u8 byte)//往片外写1个字节数据
{	
	if(Dst_Addr < UndefinedAddr)	return;
    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return ;
    }




	SPI_Wait_Busy();
	SPI_Write_Enable();
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_ByteProgram);
	SPI_Send_Byte(((Dst_Addr & 0xFFFFFF) >> 16));
	SPI_Send_Byte(((Dst_Addr & 0xFFFF) >> 8));
	SPI_Send_Byte(Dst_Addr & 0xFF);
	SPI_Send_Byte(byte);
	FLASH_CS_SET;
	SPI_Wait_Busy();
	SPI_Write_Disable();
	SPI_Wait_Busy();
    xSemaphoreGive(SPIMutexHandle);
}

void SPI_Write_2Bytes(u32 Dst_Addr, u8 Data1,u8 Data2)//往片外写2个字节数据
{
    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return;
    }
	SPI_Wait_Busy();
	SPI_Write_Enable();
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_AAIWordProgram);
	SPI_Send_Byte(((Dst_Addr & 0xFFFFFF) >> 16));
	SPI_Send_Byte(((Dst_Addr & 0xFFFF) >> 8));
	SPI_Send_Byte(Dst_Addr & 0xFF);
	SPI_Send_Byte(Data1);
	SPI_Send_Byte(Data2);
	FLASH_CS_SET;
	SPI_Wait_Busy();
	SPI_Write_Disable();
	SPI_Wait_Busy();
	
    xSemaphoreGive(SPIMutexHandle);
}

void SPI_Write_nBytes(u32 Dst_Addr, u8 *Data,int nBytes)//往片外写n个字节数据
{	
	uint16_t i;

	if(Dst_Addr < UndefinedAddr)	return;
	
    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return;
    }
	
	for(i=0;i<nBytes;i++){
		//SPI_Write_Byte(Dst_Addr+i,Data[i]);
        
        SPI_Wait_Busy();
        SPI_Write_Enable();
        FLASH_CS_RESET;
        SPI_Send_Byte(FLASH_ByteProgram);
        SPI_Send_Byte((((Dst_Addr+i) & 0xFFFFFF) >> 16));
        SPI_Send_Byte((((Dst_Addr+i) & 0xFFFF) >> 8));
        SPI_Send_Byte((Dst_Addr+i) & 0xFF);
        SPI_Send_Byte(Data[i]);
        FLASH_CS_SET;
        SPI_Wait_Busy();
        SPI_Write_Disable();
        SPI_Wait_Busy();
	}
    xSemaphoreGive(SPIMutexHandle);
}

void SPI_Erase_Chip(void)//擦除整片
{
    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return;
    }
	SPI_Write_Enable();	// set WEL
	SPI_Wait_Busy();
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_ChipErase);
	FLASH_CS_SET;
	SPI_Wait_Busy();
	
    xSemaphoreGive(SPIMutexHandle);
}

void SPI_Erase_Sector(u32 Dst_Addr)//擦除一块的数据
{	


    if(SPIMutexHandle == NULL)
    {
        SPIMutexHandle = xSemaphoreCreateMutex();
    }
    if(xSemaphoreTake(SPIMutexHandle, 10000) != pdTRUE)
    {
        return;
    }
	
	SPI_Write_Enable();	// set WEL
	FLASH_CS_RESET;
	SPI_Send_Byte(FLASH_4KSectorErase);
	SPI_Send_Byte((u8)((Dst_Addr & 0xFFFFFF) >> 16));
	SPI_Send_Byte((u8)((Dst_Addr & 0xFFFF) >> 8));
	SPI_Send_Byte((u8)Dst_Addr & 0xFF);
	FLASH_CS_SET;
	SPI_Wait_Busy();
	
    xSemaphoreGive(SPIMutexHandle);
}

void SPI_Wait_Busy(void)
{	
	while (SPI_Read_StatusReg() == 0x03);

}


void SPI_Send_Byte(u8 out)//spi 发送一个字节
{	
	u8 tx_buff = out;
	//SPI_SendAndReceiveData(FLASH_SPI,&tx_buff,1,&rx_buff,1);
	SPI_SendAndReceiveData(FLASH_SPI,&tx_buff,1,0,0);
}

u8 SPI_Get_Byte(void)//spi 接收一个字节
{	
	u8 tx_buff = 0x55;
	u8 rx_buff;

	SPI_SendAndReceiveData(FLASH_SPI,&tx_buff,1,&rx_buff,1);
	
	return rx_buff;

}	
/*******************************************************************************
** Function name:     SendnBytes_To_Head    
**
** Descriptions :     向打印头发送一点行的数据
**  
*******************************************************************************/	
void SendnBytes_To_Head(unsigned char *pData,unsigned int nByte)
{	

	SPI_SendAndReceiveData(TPH_SPI,pData,nByte,0,0);

	//printfsend(UART0, (uint8_t *)pData, nByte);

}


/*******************************************************************************
** Function name:     LFMotorPhaseSet    
**
** Descriptions :     电机相位控制函数
**  
*******************************************************************************/	
void LFMotorPhaseSet(unsigned char Phase)
{
//          B-	   A-      B      A	
//   step1	1	   1	   0	  0
//   step2	0	   1	   1	  0
//   step3	0	   0	   1	  1
//   step4	1	   0	   0	  1	
volatile	uint8_t temp;

#if 0
	if(ONEDOTSTEPNUM == 2){
		if(Phase != 0)	temp = (Phase<<1)-1;
		else			temp = 0;
	}
	else
#endif
	{
		temp = Phase;
	}

  
  // MyPrintf("m-%d",Phase);

if(f_error_no_paper)  //没纸了
{

//	MyPrintf("no paper	\n"); 
	temp=0;
}


#if 1
   switch (temp)
   {

		case 1:
			Motor_A1_OFF;
			Motor_B1_OFF;
			Motor_A2_OFF;
			Motor_B2_ON;
			break; 

		case 2:
			Motor_A1_OFF;
			Motor_B1_OFF;
			Motor_A2_ON;
			Motor_B2_ON;
			break; 			
		case 3:
			Motor_A1_OFF;
			Motor_B1_OFF;
			Motor_A2_ON;
			Motor_B2_OFF;

			break; 
			
		case 4:
			Motor_A1_OFF;
			Motor_B1_ON;
			Motor_A2_ON;
			Motor_B2_OFF;
			break; 
			
		case 5:
			Motor_A1_OFF;
			Motor_B1_ON;
			Motor_A2_OFF;
			Motor_B2_OFF;
			break; 			
		case 6:
			Motor_A1_ON;
			Motor_B1_ON;
			Motor_A2_OFF;
			Motor_B2_OFF;
			break; 
		case 7:
			Motor_A1_ON;
			Motor_B1_OFF;
			Motor_A2_OFF;
			Motor_B2_OFF;
			break; 
		case 8:
			Motor_A1_ON;
			Motor_B1_OFF;
			Motor_A2_OFF;
			Motor_B2_ON;
			break; 

		case 0://Close	
	    default:
			TPH_EN_OFF;
			MOTOR_EN_OFF;
			Motor_A1_OFF;
			Motor_B1_OFF;
			Motor_A2_OFF;
			Motor_B2_OFF;

			
			break;
   }
#else

	switch (temp)
   	{
		case 1:
			Motor_A1_ON;
			Motor_B1_OFF;
			Motor_A2_OFF;
			Motor_B2_ON;		
			
			break; 
		case 2:
			Motor_A1_OFF;
			Motor_B1_OFF;
			Motor_A2_ON;
			Motor_B2_ON;
			break; 
		
		case 3:
			Motor_A1_OFF;
			Motor_B1_ON;
			Motor_A2_ON;
			Motor_B2_OFF;
			break; 
		
		case 4:
			Motor_A1_ON;
			Motor_B1_ON;
			Motor_A2_OFF;
			Motor_B2_OFF;
			break; 


		case 0://Close	
	    default:

			MOTOR_EN_OFF;
			Motor_A1_OFF;
			Motor_B1_OFF;
			Motor_A2_OFF;
			Motor_B2_OFF;
			
			break;
   	}

#endif
	if(temp != 0)
	{
	
		TPH_EN_ON;
		MOTOR_EN_ON;
		//test_1();
	
	}
}





/*******************************************************************************
** Function name:    PrtStbStatus    
**
** Descriptions :    STB1--STB6 使能/失能函数
**  
*******************************************************************************/
void PrtStbAllStatus(unsigned char Status)
{
	if(Status == 1)
	{
		PrtStb123_ON;//Stb123 on
		PrtStb456_ON;//Stb456 on

	}

	
	else
	{
		PrtStb123_OFF;//Stb123 off
		PrtStb456_OFF;//Stb456 off

	}

	
	//test_1(void)

	
}


/*******************************************************************************
** Function name:    PrinterBusy    
**
** Descriptions :    打印机忙信号控制
**  
*******************************************************************************/	
void PrinterBusy(unsigned char Status)
{
	if(Status)
	{
		USBBusy_ON;      //Usb   Busy
		USARTBusy_ON;    //USART    Busy
	}
	else
	{
		USBBusy_OFF;    //Usb   Free
		USARTBusy_OFF;  //USART    Free
	}
}
/**********************************END*****************************************/
//
void PrinterSend(unsigned char *SendBuf,unsigned int leng){
	Rcv_Port = RCV_TYPE_USB;

	if(Rcv_Port == RCV_TYPE_BLE){
		BT_SendBleData(SendBuf,leng);
	}	
	else if(Rcv_Port == RCV_TYPE_USB){
		//usb0_respond(SendBuf,leng);
	}
	else{
		SerialSendBuff(SendBuf,leng);
	}

}


























//                                Interface.h



/*File Name  : Interface.h
*CPU        : STM32F10XC8(ARM 32-bit Cortex-M3 CPU)
*Description: 打印机与CPU之间的接口头文件
*********************************************************************/
#ifndef _INTERFACE_H_
#define _INTERFACE_H_

#include "PrtConfig.h"
#include "type.h"
//FLASH CS
#define FLASH_CS_SET      	(GPIO_SetBits(FLASH_SPI_CS_PORT, FLASH_SPI_CS_PIN))
#define FLASH_CS_RESET   	(GPIO_ResetBits(FLASH_SPI_CS_PORT, FLASH_SPI_CS_PIN))

//KEY
#define GET_WAKE_KEY  		(GPIO_ReadInputDataBit(KEY_WAKE_PORT, KEY_WAKE_PIN))
#define GET_SET_KEY   		(GPIO_ReadInputDataBit(KEY_SET_PORT, KEY_SET_PIN))


//charge
#define   GET_CHARGE_STATE     (GPIO_ReadInputDataBit(PORT_CHARGE_STATE, PIN_CHARGE_STATE))

//#define GET_USB_PLUG		(GPIO_ReadInputDataBit(USB_PLUG_IN_PORT, USB_PLUG_IN_PIN)) 	


//CBUSY
#define USBBusy_ON   		NVIC_DisableIRQ(USB_IRQn)//disable_intr(INTR_USB); 
#define USBBusy_OFF			NVIC_EnableIRQ(USB_IRQn)
#define USARTBusy_ON  		//(GPIO_SetBits(GPIOB, GPIO_Pin_5))
#define USARTBusy_OFF		//(GPIO_ResetBits(GPIOB, GPIO_Pin_5))

#define Busy_ON   			PrinterBusy(1)
#define Busy_OFF    		PrinterBusy(0)

//USB Connect
#define USB_Connect  		//(GPIO_SetBits(GPIOB, GPIO_Pin_8))
#define USB_Disconnect 		//(GPIO_ResetBits(GPIOB, GPIO_Pin_8))

//LAT
#define LAT_ON         		  GPIO_ResetBits(TPH_SPI_CS_PORT, TPH_SPI_CS_PIN)
#define LAT_OFF     		  GPIO_SetBits(TPH_SPI_CS_PORT, TPH_SPI_CS_PIN)





#define TPH_EN_ON			  do{GPIO_SetBits(TPH_MDEN_PORT,TPH_MDEN_PIN) ; GPIO_SetBits(TPH_POWER_EN_PORT,TPH_POWER_EN_PIN);} while(0)
#define TPH_EN_OFF			  do{GPIO_ResetBits(TPH_MDEN_PORT,TPH_MDEN_PIN) ; GPIO_ResetBits(TPH_POWER_EN_PORT,TPH_POWER_EN_PIN);} while(0)

#define TIME_RAW	7
//Timer
#define Timer_SetCounter(value)    	TIM_SetPeriod(TIM4,(value*96))
#define Timer_Enable               	TIM_Cmd(TIM4, ENABLE)
#define Timer_Disable               TIM_Cmd(TIM4, DISABLE)


#define Timer_key_SetCounter(value) TIM_SetPeriod(TIM1,(value*96))
#define Timer_key_Enable            TIM_Cmd(TIM1, ENABLE)
#define Timer_key_Disable           TIM_Cmd(TIM1, DISABLE)
//LF Motor Timer
#define LFTimer_Enable             	TIM_Cmd(TIM2, ENABLE)
#define LFTimer_Disable            	TIM_Cmd(TIM2, DISABLE)
#define LFTimer_SetCounter(value)   TIM_SetPeriod(TIM2,value*PAPER.print_speed_time_multiple)
									

//Prt Timer
#define PrtTimer_Enable             TIM_Cmd(TIM3, ENABLE)
#define PrtTimer_Disable           	TIM_Cmd(TIM3, DISABLE)
#define PrtTimer_SetCounter(value)  TIM_SetPeriod(TIM3,value*120)

//Lcd Timer
//#define Timer_Lcd_SetCounter(value) TIM_SetPeriod(TIM5,(value*96))
//#define Timer_Lcd_Enable            TIM_Cmd(TIM5, ENABLE)
//#define Timer_Lcd_Disable           TIM_Cmd(TIM5, DISABLE)

#define Timer_Lcd1_SetCounter(value) TIM_SetPeriod(TIM7,(value*96))
#define Timer_Lcd1_Enable            TIM_Cmd(TIM7, ENABLE)
#define Timer_Lcd1_Disable           TIM_Cmd(TIM7, DISABLE)

//Interrupt Switch
#define CloseAllInt      //(__set_PRIMASK(1))
#define OpenAllInt       //(__set_PRIMASK(0))

//SystemReset
#define SystemReset     //(NVIC_SystemReset())

//Load  WDG
#define IWDG_Reload     WDT_ReloadCounter();


//Prt Stb
#define PrtStb123_ON       GPIO_SetBits(TPH_STB1_PORT,TPH_STB1_PIN)
#define PrtStb123_OFF      GPIO_ResetBits(TPH_STB1_PORT,TPH_STB1_PIN)
#define PrtStb456_ON       GPIO_SetBits(TPH_STB2_PORT,TPH_STB2_PIN)
#define PrtStb456_OFF      GPIO_ResetBits(TPH_STB2_PORT,TPH_STB2_PIN)

//Cash前箱
#define bCash_ON           //(GPIO_SetBits(GPIOA, GPIO_Pin_8))
#define bCash_OFF          //(GPIO_ResetBits(GPIOA, GPIO_Pin_8))

//Motor
#define Motor_A1_ON          GPIO_SetBits(STEP_MOTOR_A1_PORT, STEP_MOTOR_A1_PIN)
#define Motor_A1_OFF         GPIO_ResetBits(STEP_MOTOR_A1_PORT, STEP_MOTOR_A1_PIN)
#define Motor_A2_ON          GPIO_SetBits(STEP_MOTOR_A2_PORT, STEP_MOTOR_A2_PIN)
#define Motor_A2_OFF         GPIO_ResetBits(STEP_MOTOR_A2_PORT,STEP_MOTOR_A2_PIN)
#define Motor_B1_ON          GPIO_SetBits(STEP_MOTOR_B1_PORT,STEP_MOTOR_B1_PIN)
#define Motor_B1_OFF         GPIO_ResetBits(STEP_MOTOR_B1_PORT,STEP_MOTOR_B1_PIN)
#define Motor_B2_ON          GPIO_SetBits(STEP_MOTOR_B2_PORT,STEP_MOTOR_B2_PIN)
#define Motor_B2_OFF         GPIO_ResetBits(STEP_MOTOR_B2_PORT,STEP_MOTOR_B2_PIN)

#define MOTOR_EN_ON			GPIO_SetBits(STEP_MOTOR_EN_PORT,STEP_MOTOR_EN_PIN)
#define MOTOR_EN_OFF		GPIO_ResetBits(STEP_MOTOR_EN_PORT,STEP_MOTOR_EN_PIN)
#define GET_MOTOR_OUT_BIT	GPIO_ReadOutputDataBit(STEP_MOTOR_EN_PORT,STEP_MOTOR_EN_PIN)
//lcd
#define LCD_RST_ON			GPIO_ResetBits(LCD_RST_PORT,LCD_RST_PIN) 
#define LCD_RST_OFF			GPIO_SetBits(LCD_RST_PORT,LCD_RST_PIN) 

//#define LCD_POWER_OFF		GPIO_SetBits(LCD_PWR_PORT,LCD_PWR_PIN) 
//#define LCD_POWER_ON		GPIO_ResetBits(LCD_PWR_PORT,LCD_PWR_PIN) 



#define Head_En_ON		    GPIO_SetBits(Head_En_PORT,Head_En_PIN) 
#define Head_En_OFF		    GPIO_ResetBits(Head_En_PORT,Head_En_PIN) 



#ifdef   USE_LCD_IIC_PORT
#define LCD_I2C_SDA_H		GPIO_SetBits(LCD_IIC_SDA_PORT,LCD_IIC_SDA_PIN)  
#define LCD_I2C_SDA_L		GPIO_ResetBits(LCD_IIC_SDA_PORT,LCD_IIC_SDA_PIN)

#define LCD_I2C_SCL_H		GPIO_SetBits(LCD_IIC_CLK_PORT,LCD_IIC_CLK_PIN)  
#define LCD_I2C_SCL_L		GPIO_ResetBits(LCD_IIC_CLK_PORT,LCD_IIC_CLK_PIN)


#define LCD_CS_H		      GPIO_SetBits(LCD_CS_PORT,LCD_CS1_PIN)  
#define LCD_CS_L		      GPIO_ResetBits(LCD_CS_PORT,LCD_CS1_PIN)

#else
#define LCD_SDA_H		      GPIO_SetBits(LCD_SDA_PORT,LCD_SDA_PINT)  
#define LCD_SDA_L		      GPIO_ResetBits(LCD_SDA_PORT,LCD_SDA_PINT)

#define LCD_SCL_H		      GPIO_SetBits(LCD_CLK_PORT,LCD_CLK_PIN)  
#define LCD_SCL_L		      GPIO_ResetBits(LCD_CLK_PORT,LCD_CLK_PIN)




#define LCD_CS_H		      GPIO_SetBits(LCD_CS_PORT,LCD_CS1_PIN)  
#define LCD_CS_L		      GPIO_ResetBits(LCD_CS_PORT,LCD_CS1_PIN)

//#define LCD_DC_H		      GPIO_SetBits(LCD_DC_PORT,LCD_DC_PIN)  
//#define LCD_DC_L		      GPIO_ResetBits(LCD_DC_PORT,LCD_DC_PIN)

#endif



#define  on_0      0




#if   on_0






#define     LED_BULE_off	    GPIO_SetBits(LCD_CLK_PORT,LCD_CLK_PIN)  
#define 	  LED_BULE_on	    GPIO_ResetBits(LCD_CLK_PORT,LCD_CLK_PIN)

#define 	  LED_RED_off	    GPIO_SetBits(LCD_SDA_PORT,LCD_SDA_PINT)  
#define 	  LED_RED_on	    GPIO_ResetBits(LCD_SDA_PORT,LCD_SDA_PINT)


#else







#define  LED_BULE_on          GPIO_SetBits(LCD_CLK_PORT,LCD_CLK_PIN)  
#define  LED_BULE_off         GPIO_ResetBits(LCD_CLK_PORT,LCD_CLK_PIN)

#define  LED_RED_on	         GPIO_SetBits(LCD_SDA_PORT,LCD_SDA_PINT)  
#define  LED_RED_off          GPIO_ResetBits(LCD_SDA_PORT,LCD_SDA_PINT)

#endif


//power
#define SYS_POWER_EN_ON	  		GPIO_SetBits(SYS_POWER_EN_PORT,SYS_POWER_EN_PIN)  
#define SYS_POWER_EN_OFF	    GPIO_ResetBits(SYS_POWER_EN_PORT,SYS_POWER_EN_PIN)  

//bm adc sw
#define BM_E0_ON			  GPIO_SetBits(BM_E0_PORT,BM_E0_PIN)		
#define BM_E0_OFF			  GPIO_ResetBits(BM_E0_PORT,BM_E0_PIN)	

#define BM_E1_ON			  GPIO_SetBits(BM_E1_PORT,BM_E1_PIN)		
#define BM_E1_OFF			  GPIO_ResetBits(BM_E1_PORT,BM_E1_PIN)	


#define gap_e3_on			  GPIO_SetBits(gap_e3_port,gap_e3_pin)		
#define gap_e3_off			  GPIO_ResetBits(gap_e3_port,gap_e3_pin)

#define gap_e2_on			  GPIO_SetBits(gap_e2_port,gap_e2_pin)		
#define gap_e2_off			  GPIO_ResetBits(gap_e2_port,gap_e2_pin)

//#define BEEP_ON				GPIO_SetBits(BEEP_PORT,BEEP_PIN)
//#define BEEP_OFF			GPIO_ResetBits(BEEP_PORT,BEEP_PIN)


#if(GB2312 == 1)//2M FLASH
	/* 	
	字库存放分为以下6个部分:
	1>Part1 : 0000~EDEF             汉字  A1~A9区 24x24
	2>Part2: EDF0~18C8F              FontB 9x24 (其中EDF0~F80F 为ASCII 0x20~0x7F,其余为代码页)
	代码页为:page0~page 5 , page 16~page19, page 255 .
	3>Part3: 18C90~8FC0F            汉字 B0~F7区  24x24
	4>Part4 : 8FC10~B060F           code page 0~code page 32, page 255    12x24
	5>Part3: B0610~E780F            code page 50~code page 96                  12x24
	6>Part2: E7810~E858F            ASCII 0x20~0x7F                                   12X24
	*/

	//#define EXTFLASH_ADDRESS_FONT_EN_16x8    (0x000DF400)
	//#define EXTFLASH_ADDRESS_FONT_CN_16x16   (0x000081C0)
	//#define EXTFLASH_ADDRESS_FONT_EN_24x12_1 (0x000E2780)
	//#define EXTFLASH_ADDRESS_FONT_EN_24x12_2 (0x000E26F0)
	//#define EXTFLASH_ADDRESS_FONT_CN_24x24   (0x001C23F0)


	#define BaseAddr1_24x24            0x000000//~0x00EDEF 
    #define BaseAddr_9x24              0x00EDF0//~0x00F80F
    #define ExtendedBaseAddr_9x24      0x00F810//~0x018C8F 
    #define BaseAddr2_24x24            0x018C90//~0x08FC0F
    #define ExtendedBaseAddr1_12x24	   0x08FC10//~0x0B060F
    #define ExtendedBaseAddr2_12x24	   0x0B0610//~0x0E780F
    #define BaseAddr_12x24             0x0E7810//~0x0E858F
   // #define UserParameterBaseAddr      0x0E9000//~0x0E9FFF 4K
	#define UserCharAddr_12x24         0x0EA000//~0x149FFF 96*4K
	#define UserCharAddr_9x17          0x0EA000//~0x149FFF 96*4K
	#define Pty860Addr				   0x100000
	#define UserCharAddr_24x24         0x14A000//~0x1A9FFF 93*4K
    #define NvImageBaseAddr            0x1AA000//~0x1BEFFF  5*16k(每幅图片最大16K)
    #define UndefinedAddr              0x1BF000//~0x1FFFFF
    #define LogAddr                    0x1FF000//~0x1FFFFF
    
	#define ZKBlockSize_12x24          0x1200
	#define ZKBlockSize_9x24           0x0D80
#endif


//PC25VF080B 8Mbit SPI Serial Flash op code
#define FLASH_WriteStatusReg	  0x01
#define FLASH_ByteProgram		  0x02
#define FLASH_ReadData			  0x03
#define FLASH_WriteDisable		  0x04
#define FLASH_ReadStatusReg		  0x05
#define FLASH_WriteEnable		  0x06
#define FLASH_FastReadData		  0x0B
#define FLASH_4KSectorErase		  0x20
#define FLASH_EnWriteSR           0x50
#define FLASH_AAIWordProgram      0xAD
#define FLASH_ChipErase			  0xC7
#define FLASH_DeviceID			  0xAB

#define DensitySetTimeLevel1       100
#define DensitySetTimeLevel2       200
#define DensitySetTimeLevel3       300
#define DensitySetTimeLevel4       450

#define BAUDRATE9600              9600
#define BAUDRATE19200            19200
#define BAUDRATE38400            38400
#define BAUDRATE57600            57600
#define BAUDRATE115200          115200

#define AD_Value_PE_EXIT		  1200
extern u32  iBaudRate;

extern unsigned char  Zimotemp[72]; 
extern unsigned char KeySelfTestPrinting_flag ;    //按键打印自检标志_
extern unsigned char Key_Feed_Line_flag;            //右键走纸标志_
extern unsigned char No_paper_flag ;
typedef struct  
{ 
	uint8_t Previous_shortreleaseKey;
	uint8_t  Previous_shortrelease_counter;
	uint8_t PreviousKeyArray[5];     //上上次按键状态
	uint8_t PreviousKey;
	uint8_t CurrentKey;
	uint8_t ProcessTime;
	uint16_t ProcessTime2;
	uint16_t ProcessTime3;  
	uint16_t ProcessTime4;          //用于记录按键按下之后计时(目前设置500),计时减到0再回主界面
	uint8_t scan_time;
	uint8_t power_state;
	uint8_t Key_Cancel_No_paper_state;      //按键按下时不显示缺纸显示的标志
	uint8_t poweron_firsttime;
	uint16_t keySelfTestProcessTime;
	uint8_t key_counter;
	uint16_t Power_Key_Long_Press;        //电源键长按标志
	uint16_t PowerKeyLongPressTime;       //电源键长按时间
	uint8_t FCancelWrongOrders;          //取消报错标志
}KEY_STRUCT;  
extern KEY_STRUCT BOARD_KEY;
extern void Cpu_Init(void);
extern void USART_Configuration(void);
extern void SerialSendByte(unsigned char SendByte);
extern void SerialSendBuff(unsigned char *SendBuff,unsigned int leng);
extern void PrinterSend(unsigned char *SendBuf,unsigned int leng);
extern void LFMotorPhaseSet(unsigned char Phase);
extern void SPI_Send_Byte(u8 out);
extern u8   SPI_Read_Byte(u32 Dst_Addr);
extern void SPI_Write_Byte(u32 Dst_Addr, u8 byte);
extern void SPI_Erase_Sector(u32 Dst_Addr);

extern void SPI_Write_nBytes(u32 Dst_Addr, u8 *Data, int nBytes);
extern void SPI_FastRead_nBytes(u32 Dst_Addr,u8 *Data , int nBytes);
extern void SPI_Read_nBytes(u32 Dst_Addr, u8 *Data, int nBytes);

extern void PrtStbAllStatus(unsigned char Status);
extern void PrinterBusy(unsigned char Status);

extern void SendnBytes_To_Head(unsigned char *pData,unsigned int nByte);
extern void KEY_Main(void);

extern void PWM_Configuration(void);
extern void MusicPlay(void);

extern void SetTphDensitySetTime(void);
extern void SetMotorSpeedTime(void);

extern void test_3(unsigned char mm);
extern void test_2(unsigned char mm);

extern void test_1(void);
extern void  charge_enable(void);

extern  void charge_disable(void);
void poweroff_set(void);
#endif

/**********************************END*****************************************/



























//                              Key.c

#include "yc3121.h"
#include "yc_power.h"
#include "yc_gpio.h"
#include "yc_wdt.h"
#include "yc_bt.h"
#include "board_config.h"
#include "Interface.h"
#include "LcdDrv.h"
#include "PrtHead.h"
#include "PrtBuf.h"
#include "RcvBuf.h"
#include "CmdSet.h"
#include "Sensor.h"
#include "LcdMenu.h"

//#include "Led.h"



KEY_STRUCT BOARD_KEY;
unsigned char KeySelfTestPrinting_flag;  //按键打印自检标志
unsigned char Calibrate_enable=0;
unsigned char Key_Feed_Line_flag;           //右键走纸标志_
unsigned char No_paper_flag =0;                //没纸标志
#define KEY_EVENT_IDE			  0
#define KEY_EVENT_SHORT			  1
#define KEY_EVENT_SHORT_RELEASE	  2
#define KEY_EVENT_LONG			  3
#define KEY_EVENT_DOUBLE	      4

#define NO_KEY	0x11

#define KEY_CODE_MENU	0x01
#define KEY_CODE_SET	0x10

void BeepKey(void);
void poweroff_set(void);

void KeyProcess(uint8_t key_code,uint8_t key_type)
{

	if(key_type == KEY_EVENT_SHORT_RELEASE)            //短释放
	{
//		if((error_state.byte[0] & 0xFE) || (error_state.byte[1] & 0x08))       //上盖打开
//		{
//			//if(error_state.byte[0] & 0xFE){

//			MyPrintf("error_state.byte[0] --%02x\n",error_state.byte[0]);     //未检测到纸张时byte[0]=05  =0101
//			if(!f_error_no_paper)
//			  return;
//		}	

		if(BOARD_KEY.power_state == 0)	return;
		//打印时不处理按键
		if(GetIsVirtualPrinting()) return;

		BeepKey();

		MyPrintf("short key --%02x,%02x\n",key_code,key_type);

		if((!MOTOR.bLFMotorMove))
		{
			if(key_code == 0x10)
			{   
				LCD_Change_By_Setup_Key();
			}
			else if(key_code == 0x01)
			{
				MyPrintf("LCD_Change_By_Menu_Key\n");
				LCD_Change_By_Menu_Key();
			}
		}

	}

	if(key_type == KEY_EVENT_DOUBLE)        //双击按键
	{

		if((error_state.byte[0] & 0xFE) || (error_state.byte[1] & 0x18))
		{
			//MyPrintf("error_state.byte[0] --%02x\n",error_state.byte[0]);
			return;
		}	
		if(BOARD_KEY.power_state == 0)	
		{
			return;
		}
		if(menu_state!= LCD_MENU_MAIN)
		{
			return;
		}	
		BeepKey();

		MyPrintf("double key --%02x,%02x\n",key_code,key_type);
		if((!MOTOR.bLFMotorMove))
		{
			if(key_code == 0x10)
			{   
			//	MyPrintf("type=%d\n",PAPER.type);
				//if(PAPER.type !=E_PAPER_TYPE_CONTINUE)
				if((PAPER.type !=E_PAPER_TYPE_CONTINUE)&&(Can_Be_Calibrated_Flag==0)&&(f_error_no_paper==0))
				{
					LCD.main_menu_resume_time = 150;
					menu_state= LCD_MENU_AUTO_Calibration;	
					PAPER.auto_cal_type++;
					PAPER.auto_cal_type %= 4;
					LCD_TimeEvent_100ms();			
				}				
				
			}
		}

	}
	else if(key_type == KEY_EVENT_LONG)        //长按按键
	{
		BeepKey();
		MyPrintf("long key --%02x,%02x\n",key_code,key_type);
		if(key_code == 0x01)             //左键长按
		{

			if(BOARD_KEY.power_state)    //关机
			{	

//			    if(BOARD_KEY.poweron_firsttime==1)  //防止第一次开机后就关机
//			    {
//					BOARD_KEY.poweron_firsttime=0;
//                    return;
//				}
//				else
				{
					BOARD_KEY.power_state = 0;
				}
			
				//LCD_Reset();
				//LCD_POWER_OFF;
				LCD_RST_ON;
				Update_Eeprom_Data();
				MyPrintf("Update_Eeprom have saved \n");				
				while(GET_WAKE_KEY == 0);
				SYS_POWER_EN_OFF;	          //
				BOARD_KEY.power_state = 0;		
				while(GET_WAKE_KEY);
				soft_reset();                      
			}                                
			else                                  //开机            
			{
				//MyPrintf("power on \n");    OLED_Clear();
		
				BOARD_KEY.power_state = 1;
				SYS_POWER_EN_ON;	
				delay_ms(100);
#ifdef USE_LCD		
				LCD_Drv_Init();
#endif
			}
		}
		//右键长按  0x10
		else if(key_code == 0x10)
		{
//			MyPrintf("f_lable_printing=%d\n",f_lable_printing);
			if(f_lable_printing == 1)	      //正在打印中  if( bPrt_Statu_flag==1&&MOTOR.bLFMotorMove==1)
			{
		//		memset((void*)RcvBuff,0,sizeof(RcvBuff));
				f_print_canncel = 1;
				memset((void*)RcvBuff,0,0x9000);
				f_lable_printing = 0;
		//		strcpy((unsigned char*)RcvBuff, "");
				InitRcvBuf();//初始化接收缓冲区
				usb_inial();
	
	//			MOTOR.bLFMotorMove = 0;
//				bPrt_Statu_flag=0;
		//		LAT_ON;//  Open Lat
		//		PrtStbAllStatus(0);    //关打印头通道
				LFMotorPhaseSet(0);//关闭电机驱动			
			}

		}
		
	}
}


#define change_key   1



void KEY_Main(void)
{

	volatile static unsigned char buf1=0;
	static unsigned char key_step = 0;
	static unsigned char f_rcv_date_times = 0;     //记录没接收到数据的次数的标记
//	MyPrintf("menu_state=%d\n",menu_state);
//	MyPrintf("f_=%d\n",f_error_no_paper);
//		MyPrintf("Key_Feed_Line_flag= %d\n",Key_Feed_Line_flag);
	if(PAPER.auto_calibrate_flag) return;          //定标时返回
	if(Key_Feed_Line_flag == 1)   return;         //右键走纸时返回
//	MyPrintf("!!1\n");
//	if(BOARD_KEY.scan_time)	return;
//		 BOARD_KEY.scan_time = 3;
//  以下是通过查询接收数据情况,并累加没有接收到数据的标志的次数,没接收到数据标志次数大于等于6时,把打印状态置为0	
	if(f_rcv_data==0) 
	{		
		if(f_rcv_date_times<100)
	    f_rcv_date_times ++;
	}
	if(f_rcv_date_times>=100)       //处理打印份数大于1时,当前张打印完到下一张开始打印之间有一个间隙时间不打印
		f_rcv_data2 = 0;
	if(f_rcv_data)         //有打印数据
	{
	  f_rcv_data2 = 1;
	  f_rcv_date_times = 0;
	}
//	MyPrintf("f_rcv_data2= %d\n",f_rcv_data2);
	BOARD_KEY.PreviousKey = BOARD_KEY.CurrentKey;
	if(BOARD_KEY.ProcessTime)
	{
			if(BOARD_KEY.ProcessTime<=190&&BOARD_KEY.ProcessTime>160)
				BOARD_KEY.PreviousKeyArray[0] = BOARD_KEY.CurrentKey;
			else if (BOARD_KEY.ProcessTime<=160&&BOARD_KEY.ProcessTime>120)
				BOARD_KEY.PreviousKeyArray[1] = BOARD_KEY.CurrentKey;
			else if(BOARD_KEY.ProcessTime<=120&&BOARD_KEY.ProcessTime>80)
				BOARD_KEY.PreviousKeyArray[2] = BOARD_KEY.CurrentKey; 
			else if(BOARD_KEY.ProcessTime<=100&&BOARD_KEY.ProcessTime>50)
				BOARD_KEY.PreviousKeyArray[3] = BOARD_KEY.CurrentKey; 
			else if(BOARD_KEY.ProcessTime<=50)
				BOARD_KEY.PreviousKeyArray[4] = BOARD_KEY.CurrentKey; 
	}
	if(GET_WAKE_KEY)           //左键按下时,为高电平_
	{
//		MyPrintf("GET_WAKE_KEY= %d\n",GET_WAKE_KEY);
		buf1=0;
	}
	else
	{
		buf1=1;
	}

	BOARD_KEY.CurrentKey = (uint8_t)(buf1<<4|GET_SET_KEY);      //GET_SET_KEY 获取右边按键的值_
	
//_左键按下,右键释放 :CurrentKey=0x01,  左右键不按 :CurrentKey=0x11,左右键按下:CurrentKey=0x00;  左键不按,右键按下 :CurrentKey=0x10,

	if(BOARD_KEY.CurrentKey!=NO_KEY)   //NO_KEY	=0x11   :左右键不按
	{
		if(f_lable_printing!=1)      //不打印才执行关机延时时间计算
		   poweroff_set();
	}
//	MyPrintf("CurrentKey=%2x\n",BOARD_KEY.CurrentKey );
	switch(key_step)
	{
		case 0:
			if(BOARD_KEY.CurrentKey==0x10)    //右键
			{  
				 //   if(f_error_no_paper)
					{
					BOARD_KEY.ProcessTime4 = 500;
					BOARD_KEY.Key_Cancel_No_paper_state =1;
					f_error_Voltage_low=0;//电量低状态
					f_error_no_paper=0;
					}
					if(f_lable_printing==1||(f_rcv_data2==1))   return;   //打印过程按键不起作用
					if(BOARD_KEY.ProcessTime2 == 0&& BOARD_KEY.PreviousKey == NO_KEY && BOARD_KEY.CurrentKey == 0x10)  
					{
					//	MyPrintf("KEY_Main_1\n");
						if((BOARD_KEY.Previous_shortreleaseKey!=BOARD_KEY.CurrentKey))                 //第一次按下 (只考虑右键)
						{
								MyPrintf("Firstpress\n");
								KeyProcess(BOARD_KEY.CurrentKey,KEY_EVENT_SHORT);          //KeyProcess函数中没有 KEY_EVENT_SHORT,所以不会执行
								BOARD_KEY.ProcessTime2 = 300;					
						}
						key_step = 1;
					}
					else if(BOARD_KEY.PreviousKey == NO_KEY && BOARD_KEY.CurrentKey != NO_KEY&&BOARD_KEY.ProcessTime != 0) //不是第一次按下,但按键是释放了再按下的
					{
						key_step = 1;
						MyPrintf("secondpress\n");
					}
			}
		//	else if(BOARD_KEY.CurrentKey==0x01&&BOARD_KEY.ProcessTime == 0&& BOARD_KEY.PreviousKey == NO_KEY)         //左键按下
			else if(BOARD_KEY.CurrentKey==0x01) 	    //左键电源键
			{
				f_error_no_paper=0;
				BOARD_KEY.ProcessTime4 = 500;
				f_error_Voltage_low=0;//电量低状态
				BOARD_KEY.Key_Cancel_No_paper_state =1;
			    if(f_error_no_paper==1&&BOARD_KEY.CurrentKey==0x01)     //报没纸时左键按下取消报错
				{
					BOARD_KEY.FCancelWrongOrders=1;
					LCD.nopaper_resume_time = 500;
					
				}
                    BOARD_KEY.ProcessTime = 200;
					BOARD_KEY.ProcessTime3 = 5;
					key_step = 7;
			}
			break;
		case 1:
		//	MyPrintf("KEY_Main_2\n");
			if(BOARD_KEY.CurrentKey == NO_KEY && BOARD_KEY.PreviousKey != NO_KEY && BOARD_KEY.ProcessTime<200)  //单击抬起,后边有双击的的问题单击不能马上起作用
			{
				if(f_lable_printing==1)   
				{
					return;
				}
				else
				{
	//				MyPrintf("relaese\n");
					BOARD_KEY.ProcessTime = 0xff;
					BOARD_KEY.Previous_shortreleaseKey=BOARD_KEY.PreviousKey;
					BOARD_KEY.Previous_shortrelease_counter=30;
				}
				key_step = 2;
			}   	
			//  //右键长按
			else if(BOARD_KEY.CurrentKey == 0x10&&BOARD_KEY.PreviousKey == BOARD_KEY.CurrentKey&& BOARD_KEY.ProcessTime2 == 0&&f_lable_printing==1 )    
			{
				MyPrintf("RightLongpress\n");
				key_step = 4;
			}
			break;
		case 2:	         //右键短按
//			MyPrintf("KEY_Main_3\n");
			if((BOARD_KEY.Previous_shortreleaseKey!= NO_KEY)&&(BOARD_KEY.Previous_shortrelease_counter==0))  //单击抬起以后>=300ms起作用
			{
				if(f_lable_printing==1)   
				{
					return;
				}
				else
				{
					MyPrintf("relaese_last\n");
					KeyProcess(BOARD_KEY.Previous_shortreleaseKey,KEY_EVENT_SHORT_RELEASE);
					BOARD_KEY.Previous_shortreleaseKey=NO_KEY;
					BOARD_KEY.CurrentKey   = NO_KEY;
					BOARD_KEY.PreviousKey = NO_KEY;
						key_step = 0;
				}			
			}	
			else if(BOARD_KEY.Previous_shortreleaseKey==BOARD_KEY.CurrentKey&&BOARD_KEY.Previous_shortrelease_counter!=0)  //双击
			{
				MyPrintf("double_press_\n");
				key_step = 3;
			}				
		 break;
		case 3:
		//	MyPrintf("KEY_Main_4\n");
	//		if(BOARD_KEY.Previous_shortreleaseKey==BOARD_KEY.CurrentKey&&BOARD_KEY.Previous_shortrelease_counter!=0) //双击
			{
				if(f_lable_printing==1)   
				{
					return;
				}else{
				MyPrintf("double_press_22\n");
				KeyProcess(BOARD_KEY.Previous_shortreleaseKey,KEY_EVENT_DOUBLE);
				BOARD_KEY.Previous_shortreleaseKey=NO_KEY;
				BOARD_KEY.Previous_shortrelease_counter=0;
				BOARD_KEY.ProcessTime = 0x00;
				BOARD_KEY.ProcessTime2 = 0x00;
				BOARD_KEY.CurrentKey   = NO_KEY;
				BOARD_KEY.PreviousKey = NO_KEY;
				}
			}
			key_step = 0;
			break;		
#if(change_key)
		case 4:
		//	if(BOARD_KEY.CurrentKey == 0x10&&BOARD_KEY.PreviousKey == BOARD_KEY.CurrentKey&& BOARD_KEY.ProcessTime2 == 0&&f_lable_printing==1 )   //打印中右键长按,按下3秒
			{		
		//			MyPrintf("long press_22\n");
					KeyProcess(BOARD_KEY.CurrentKey,KEY_EVENT_LONG);
					BOARD_KEY.ProcessTime = 0x00;
					BOARD_KEY.ProcessTime2 = 0x00;	
					BOARD_KEY.CurrentKey   = NO_KEY;
					BOARD_KEY.PreviousKey = NO_KEY;					
				  key_step = 0;
			}
			
			break;			
#endif
		case 7:
				if(BOARD_KEY.CurrentKey != 0x01&&BOARD_KEY.ProcessTime3==0)      //左键松开
				{
				
				//	MyPrintf("f_rcv_data2= %d\n",f_rcv_data2);
					if(f_lable_printing==1||(f_rcv_data2==1)) 
					{ 
						
						key_step = 0;
						return;			
					}
					BOARD_KEY.Previous_shortreleaseKey=BOARD_KEY.PreviousKey;
					key_step = 8;	
				}		 
				//   //左键长按 >2秒, 且不在打印中
				else if(BOARD_KEY.PreviousKeyArray[0]==BOARD_KEY.PreviousKeyArray[1]==BOARD_KEY.PreviousKeyArray[2]==BOARD_KEY.PreviousKeyArray[3]==BOARD_KEY.PreviousKeyArray[4]) 
				{
					if(BOARD_KEY.CurrentKey == 0x01&&BOARD_KEY.PreviousKey == BOARD_KEY.CurrentKey && BOARD_KEY.CurrentKey != NO_KEY && BOARD_KEY.ProcessTime == 0 )
					{
						MyPrintf("LeftLongpress\n");
						key_step = 9;
					}
				}				
			break;
		case 8:    //左键短按
				KeyProcess(BOARD_KEY.Previous_shortreleaseKey,KEY_EVENT_SHORT_RELEASE);
				BOARD_KEY.Previous_shortreleaseKey=NO_KEY;
				BOARD_KEY.CurrentKey   = NO_KEY;
				BOARD_KEY.PreviousKey = NO_KEY;
				key_step = 0;
			break;				
		case 9:			                           //左键长按2秒(没有打印时)
		//		MyPrintf("KEY_Main_5\n");
				//检测中间没有释放过按键,采样5次
	//			if(BOARD_KEY.PreviousKeyArray[0]==BOARD_KEY.PreviousKeyArray[1]==BOARD_KEY.PreviousKeyArray[2]==BOARD_KEY.PreviousKeyArray[3]==BOARD_KEY.PreviousKeyArray[4])    
				{
					KeyProcess(BOARD_KEY.CurrentKey,KEY_EVENT_LONG);          //不松开按键只执行1次
					BOARD_KEY.ProcessTime = 0x00;
					key_step = 10;		
				}
			break;
		case 10:
	//		MyPrintf("KEY_Main_7\n");
			if(BOARD_KEY.CurrentKey == NO_KEY)
			{
				key_step = 0;
			}		
			break;
	default:
     break;	
			
			
 }
	
#if(!change_key)


	 else if(BOARD_KEY.PreviousKey == BOARD_KEY.CurrentKey && BOARD_KEY.CurrentKey != NO_KEY )//长按
	{

		BOARD_KEY.key_counter++;
	       if(BOARD_KEY.key_counter>70)
		{
			BOARD_KEY.key_counter=0;
			MyPrintf("long press\n");
			KeyProcess(BOARD_KEY.CurrentKey,KEY_EVENT_LONG);
			BOARD_KEY.ProcessTime = 0xFF;
		}

	}
	else if(BOARD_KEY.PreviousKey!= BOARD_KEY.CurrentKey)
	{
		BOARD_KEY.key_counter=0;
	}

#endif
 
}
//10MS?¨ê±


const uint16_t power_off_time_buff[]={
	0,
	300,
	600,
	1200,
	1800,
};

void SetPowerOffTime(uint8_t power_off_type)
{
	EXT_DEV.power_off_time_count = power_off_time_buff[power_off_type];

}

void poweroff_set(void)
{

	if(EXT_DEV.ble_link_flag==1||EXT_DEV.spp_link_flag==1)
	{
		//EXT_DEV.power_off_mode=2;
		SetPowerOffTime(EXT_DEV.power_off_mode);

	}
	else
	{
		//EXT_DEV.power_off_mode=1;
		SetPowerOffTime(EXT_DEV.power_off_mode);
	}
	
}





//10MS 定时事件
void TIMER1_IRQHandler(void)
{
	Timer_key_SetCounter(10000);
//	MyPrintf("TIMER1_IRQHandler\n");   
	
	if(BOARD_KEY.PowerKeyLongPressTime ) BOARD_KEY.PowerKeyLongPressTime --;
	if(EXT_DEV.charging_flsh_time2) EXT_DEV.charging_flsh_time2--;
	if(EXT_DEV.charging_flsh_time)	EXT_DEV.charging_flsh_time--;
	if(EXT_DEV.bat_scan_time)		EXT_DEV.bat_scan_time--;
	if(EXT_DEV.usb_scan_time)		EXT_DEV.usb_scan_time--;
	if(EXT_DEV.tph_scan_time)		EXT_DEV.tph_scan_time--;
	if(EXT_DEV.no_paper_scan_time)	EXT_DEV.no_paper_scan_time--;
	if(EXT_DEV.print_scan_time)	EXT_DEV.print_scan_time--;
	if(EXT_DEV.dlabel_save_counter)	EXT_DEV.dlabel_save_counter--;
	if(EXT_DEV.Lcd_flsh_time)       EXT_DEV.Lcd_flsh_time--;                           //打印过程显示...的刷新时间
//  if(BOARD_KEY.keySelfTestProcessTime) BOARD_KEY.keySelfTestProcessTime--;           //右键打印自测计时
	if(LCD.dsp_delay)	LCD.dsp_delay--;
	if(EXT_DEV.hight_tem_release_counter) EXT_DEV.hight_tem_release_counter--;
	if(EXT_DEV.print_err_release_delay_counter) EXT_DEV.print_err_release_delay_counter--;

	if(EXT_DEV.hight_tem_release_counter==0)
	{
		f_error_tph_temp = 0;
		if((!(error_state.byte[0] & 0xFE)) && (!(error_state.byte[1] & 0x18)))
		{
			f_printer_error = 0;
		}
	}
	//按键显示计时
	if(LCD.main_menu_resume_time)
	{
		//MyPrintf("main_menu_resume_time=%d\n",LCD.main_menu_resume_time);
		if(MOTOR.bLFMotorMove)
		{
			if(menu_state != LCD_MENU_AUTO_CHECK&&menu_state != LCD_MENU_AUTO_Calibration&&SelfTestPrinting_flag!=1)
			  LCD.main_menu_resume_time = MAIN_MENU_RESUME_TIME;
		}
		else if((error_state.byte[0] & 0xFE) || (error_state.byte[1] & 0x18))
		{
			LCD.main_menu_resume_time = MAIN_MENU_RESUME_TIME;
		}
		else
		{		
			if(BOARD_KEY.CurrentKey==NO_KEY)  //按键没再按下
			{	LCD.main_menu_resume_time--;}
			else
			{//	MyPrintf("CurrentKey=%d\n",BOARD_KEY.CurrentKey);
				LCD.main_menu_resume_time = MAIN_MENU_RESUME_TIME;	
			}
		}
	}	
	if(LCD.time_event_100ms)		LCD.time_event_100ms--;
	if(LCD.time_event3_100ms)		LCD.time_event3_100ms--;
	if(LCD.time_event4_100ms)		LCD.time_event4_100ms--;
	if(LCD.time_event5_100ms)		LCD.time_event5_100ms--;
	if(LCD.time_event6_50ms)    	LCD.time_event6_50ms--;
	//if(Led.led_event_100ms)			Led.led_event_100ms--;
	if(LCD.nopaper_resume_time ) 	LCD.nopaper_resume_time--;
  //按键相关计时
	if(BOARD_KEY.ProcessTime)	BOARD_KEY.ProcessTime--;
	if(BOARD_KEY.ProcessTime2)	BOARD_KEY.ProcessTime2--;
	if(BOARD_KEY.ProcessTime3) BOARD_KEY.ProcessTime3--;
	if(BOARD_KEY.ProcessTime4) BOARD_KEY.ProcessTime4--;
	if(BOARD_KEY.Previous_shortrelease_counter)	BOARD_KEY.Previous_shortrelease_counter--;
	if(BOARD_KEY.scan_time)		BOARD_KEY.scan_time--;
//	PollingExtDev_1(0);        //查询电量状态,放在这里会导致打印过程关机


//	if(EXT_DEV.usb_pugin_flag==0)//插入的时候不关机
	{
			// 1秒种定时事件
		if(EXT_DEV.base_100ms_time++>=100)
		{
	//		MyPrintf("usb_pugin_flag\n");
			EXT_DEV.base_100ms_time = 0;
			if(EXT_DEV.power_off_time_count)
			{
				if((--EXT_DEV.power_off_time_count) == 0)
				{
					Update_Eeprom_Data();
				
					MyPrintf("Power off");
					SYS_POWER_EN_OFF;
					BOARD_KEY.power_state = 0;
					while(GET_WAKE_KEY);
					soft_reset();
				}
			}
		}

	}

			
}


























//                                     main.c


/****************************************************************************
*File Name    : main.c
*Company      : XXXXXXXXXXXXXXXXXX
*Description  : 打印机软件主流程源文件
*Author       : XXXX
****************************************************************************/

#include "yc3121.h"
#include "yc_gpio.h"

#include "type.h"
#include "board_config.h"
#include "Interface.h"
#include "PrtBuf.h"
#include "CmdSet.h"
#include "RcvBuf.h"
#include "PrtHead.h"
#include "BT_BLE.h"
#include "yc_uart.h"
#include "yc_wdt.h"
#include "LcdDrv.h"
#include "yc_wdt.h"
#include "Sensor.h"
//#include "usb_lib.h"
//#include "Hw_config.h"
#include "hal.h"
#include "app.h"





const char APP_UPDATA_ENABLE_FLAG __attribute__((at(0x1008000)))= 0x55;
/*******************************************************************************
** Function name:   main    
**
** Descriptions :   主函数
**  
******************************************************************************/

void delay_ms(int ms);

/**
  * @brief  Watchdog initialization function.
  * @param  None
  * @retval None
  */
void WDT_Configuration(void)
{
    WDT_SetReload(29);(2^(29-1))/48*1000000 = 5.69(s)
    WDT_ModeConfig(WDT_CPUReset);
    WDT_Enable();
}

/*******************************************************************************
** Function name:     GlobalVariableInit    
**
** Descriptions :     系统变量初始化
**  
******************************************************************************/
void GlobalVariableInit(void)
{
	TPH.bErrTemperature = 0;//Temp ERROR 
	
	bHaveFilledAscii = 0;    //字符行填充ASCII 标志
	bHaveFilledChinese = 0;  //字符行填充汉字标志
	bHaveFilledBarCode = 0;  //字符行填充条码标志
	bHaveFilledRasterDot = 0;//字符行填充光栅位图标志
	bHaveFilledImageDot = 0; //字符行填充下载位图标志
	iRasterDotHight = 0;     //光栅位图的高度
	iImageDotHight = 0;      //位图的高度
	
	MOTOR.iLFStepNum = 0;   //电机步数
	MOTOR.cLFMotorPhase = 1;//电机相位
	MOTOR.bLFForward = 1;   //电机前进标志位
	MOTOR.bLFMotorMove = 0; //电机在运行标志位
	
	bTimer2FeedLine = 0;//电机在走行间距标志位
	bTimer2KeyFeed = 0; //电机在按键下走纸
	bTimer2Prt = 0;     //电机在打印过程中走纸
	InitRcvBuf();       //初始化接收BUFFER

	cCurrentFillRow = 0;//当前默认填充buffer1
	iCurrentFillColumn = 0;//当前填充位置标志位
	cCurrentPrtCharLine = 1;
	bPart1 = 0;//字符解码表1标志位
	bPart2 = 0;//字符解码表2标志位
	bPart3 = 0;//字符解码表3标志位
	bPart4 = 0;//字符解码表4标志位
//	BOARD_KEY.power_off_delay = POWER_OFF_DELAY;
	one_dotline_lfstep_num=ONEDOTSTEPNUM;//默认汉字,和字符步进4步打印一个点行

}





/*******************************************************************************
** Function name:     PrinterInit    
**
** Descriptions :     打印机初始化
**  
******************************************************************************/
void PrinterInit(void)
{
	bPrt_Statu_flag = 0;
	LAT_ON;//Open Lat
	//CloseAll();
	PrtStbAllStatus(0);
	
	LFMotorPhaseSet(0);//关闭电机驱动
	GlobalVariableInit();//系统变量初始化

	ESC_ATInit();//打印机参数初始化	
	//没有连蓝牙就设置成5分钟

	poweroff_set();

}


uint16_t DensityTimeBuff[]=
{
	120,//1
	140,//2
	160,//3
	180,//4
	200,//5
	220,//6
	240,//7
	260,//8
	280,//9
	300,//10
	320,//11
	340,//12
	360,//13
	380,//14
	400,//15	
	
};

//uint16_t SpeedTimeBuff_IOS[]={
//	270,//1
//	260,//2
//	250,//3
//	240,//4
//	230,//5	
//
//};
//
//	uint16_t SpeedTimeBuff_IOS[]={
//	
//		//280,
//		//260,
//	  	240,
//	    220,
//		200,//
//		180,//
//		160,//
//		//140,//
//		
//	   // 120,
//	};

uint16_t SpeedTimeBuff_IOS[]=
{
	
//		280,
//		265,
		240,
		220,
		200,//
		180,//
		160,//
		//140,

		// 120,
};


	
//
//uint16_t SpeedTimeBuff_Android[]={
//	180,//1
//	160,//2
//	140,//3
//	120,//4
//	100,//5	
//};


//uint16_t SpeedTimeBuff_Android[]={
//
//	220,
//
//    200,
//	180,//1
//	160,//2
//	140,//3
//	//120,//4
//	//100,//5	
//};

//安卓和USB速度设置
	uint16_t SpeedTimeBuff_Android[]={
	
//		220,	
//		200,
//		140, // 1
//		130, // 2
		110, // 3      1
		100,//4        2
		90,//5         3	
		80,     //     4
		70,        //  5
	};

extern u8 os_type;
void SetTphDensitySetTime(void)
{
	//读取打印浓度参数并设置
	
//	if(PAPER.print_density > 15)
//	{     
//		PAPER.print_density=15;
//		TPH.iDensitySetTime = DensityTimeBuff[PAPER.print_density-1];
//	}
//	else if(PAPER.print_density==0)//其实这个数值是不存在的。
//	{
//		TPH.iDensitySetTime = TPH.iDensitySetTime;	
//	}
//	else
//	{
//		TPH.iDensitySetTime = DensityTimeBuff[PAPER.print_density-1]; 
//	}

	if(PAPER.print_density > 14)
	{     
		PAPER.print_density=14;
	
	}
	if(os_type)
		TPH.iDensitySetTime = DensityTimeBuff[PAPER.print_density]+5;
	else
		TPH.iDensitySetTime = DensityTimeBuff[PAPER.print_density];

	
}

void SetMotorSpeedTime(void)
{
#if 0
	if(PAPER.print_speed > 5)
	{
		PAPER.print_speed = 5;
	}
#else
	if(PAPER.print_speed > 5)
	{
		PAPER.print_speed = 5;
	}
#endif
//	MyPrintf("buff_speed = %d \n",SpeedTimeBuff_IOS[PAPER.print_speed]);
	if(os_type)
	{
//		MyPrintf("buff_speed = %d \n",SpeedTimeBuff_IOS[PAPER.print_speed]);
		//PAPER.print_speed_time_multiple = SpeedTimeBuff_IOS[PAPER.print_speed-1];
	//	if(PAPER.print_speed > 3)  PAPER.print_speed = 3; 
		PAPER.print_speed_time_multiple = SpeedTimeBuff_IOS[PAPER.print_speed];
	}

	else     //安卓及USB
	{
		//PAPER.print_speed_time_multiple = SpeedTimeBuff_Android[PAPER.print_speed-1];
		PAPER.print_speed_time_multiple = SpeedTimeBuff_Android[PAPER.print_speed];
	}

}


void factory_default_set(void)
{	
		//flash 
		MyPrintf("eeprom first set\n");
		SPI_Erase_Sector(UndefinedAddr);//擦除

		EEPROM.save_flag = 0x66;
		EEPROM.CharacterMode = 0x01;
		EEPROM.CodePage = 0x00;
		EEPROM.DensitySelect = 5;
		EEPROM.SpeedSelect = 2;
			
		EEPROM.gap_size = 224;
		EEPROM.hold_size = 224;
		EEPROM.bm_size = 244;
	
		if((Factory_Reset_Flag== 1)&&(LCD.language==0))//英文状态下复位不恢复语言
		   EEPROM.language = ENGLISH;
		else
		   EEPROM.language = CHINESE;
		EEPROM.paper_size = 960;

		EEPROM.paper_type = E_PAPER_TYPE_GAP;

		EEPROM.power_off_mode = E_POWER_OFF_NEVER;
		EEPROM.SerialBauRate = 5;		
		
		SPI_Write_nBytes(UndefinedAddr,(uint8_t *)&EEPROM,sizeof(EEPROM_STRUCT));

		PAPER.adj_gap_size = EEPROM.gap_size;
		PAPER.adj_bm_size = EEPROM.bm_size;
		PAPER.adj_hold_size = EEPROM.hold_size;
		PAPER.adj_paper_size = EEPROM.paper_size;
		PAPER.type = EEPROM.paper_type;	
//		MyPrintf("EEPROM.paper_type=%d\n",EEPROM.paper_type);
		
		PAPER.print_density = EEPROM.DensitySelect;

		PAPER.print_speed = EEPROM.SpeedSelect;	
		EXT_DEV.power_off_mode = EEPROM.power_off_mode;
		LCD.language = EEPROM.language;	

}



/*******************************************************************************
** Function name:     ScanFlash    
**
** Descriptions :     读取FLASH中的打印机系统参数
**  
******************************************************************************/

void ScanFlash(void)
{

    
	SPI_FastRead_nBytes(UndefinedAddr,(uint8_t *)&EEPROM,sizeof(EEPROM_STRUCT));
	MyPrintf("EEPROM.save_flag=%d\n",EEPROM.save_flag);
       
	if(EEPROM.save_flag != 0x66)//flash第一次设置参数
	{	
		factory_default_set();
	}	

	PAPER.adj_gap_size = EEPROM.gap_size;
	PAPER.adj_bm_size = EEPROM.bm_size;
	PAPER.adj_hold_size = EEPROM.hold_size;
	PAPER.adj_paper_size = EEPROM.paper_size;
	PAPER.type = EEPROM.paper_type;	
//	MyPrintf("EEPROM.paper_type=%d\n",EEPROM.paper_type);
	PAPER.print_density = EEPROM.DensitySelect;
	
	PAPER.print_speed = EEPROM.SpeedSelect;	
	EXT_DEV.power_off_mode = EEPROM.power_off_mode;
	LCD.language = EEPROM.language;	

	//串口属性
	if(EEPROM.SerialBauRate == 1)
	{
		iBaudRate = BAUDRATE9600;
	}
	else if(EEPROM.SerialBauRate == 2)
	{
		iBaudRate = BAUDRATE19200;
	}
	else if(EEPROM.SerialBauRate == 3)
	{
		iBaudRate = BAUDRATE38400;
	}
	else if(EEPROM.SerialBauRate == 4)
	{
		iBaudRate = BAUDRATE57600;
	}
	else if(EEPROM.SerialBauRate == 5)
	{
		iBaudRate = BAUDRATE115200;
	}
	else
	{
		iBaudRate = BAUDRATE115200;
	}

	//字符模式
	if(EEPROM.CharacterMode)
	{
		bChinese = 1;
	}
	else
	{
		bChinese = 0;
	}
	SetTphDensitySetTime();
	SetMotorSpeedTime();

	//代码页
	cCodePage = EEPROM.CodePage;

}

void Update_Eeprom_Data(void){

	uint8_t i;
	MyPrintf("eeprome save start:");

	for(i=0;i<sizeof(EEPROM_STRUCT);i++)
	{
		MyPrintf("%02x ",*(((uint8_t *)&EEPROM)+i));
	}
	EEPROM.paper_type=PAPER.type;
	EEPROM.DensitySelect=PAPER.print_density;

	SPI_Erase_Sector(UndefinedAddr);//擦除
	SPI_Write_nBytes(UndefinedAddr,(uint8_t *)&EEPROM,sizeof(EEPROM_STRUCT));

}






static void main_task(void *pvParameters)
{
	unsigned char i_flage=0;


	unsigned int  back_data=0;

	//	ret_stru cData;
	unsigned char cData;
	int i = 0;
	(void)pvParameters;
	SuppliseAuth_Init();
	while (1)
	{
       
		IWDG_Reload;		
		cData = GetDataFromRcvBuf();
//		MyPrintf("cData2=%02x\n",cData);
		if(cData < 0x20)
		{
			//command
			ExecuteCmd(cData);
//			MyPrintf("cData=%02x\n",cData); 
			
		}
		else
		{
			//Prt data
//			MyPrintf("cData area cData=0x%02x\n",cData);                  //只有CPCL指令才会进来
			ExecuteData(cData);
		}		

	}
	/* no reach here */
	//    BUG();
	vTaskSuspend(NULL);
}

static void  prvInitialiseHeap(void)    	//
{
	static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
	const HeapRegion_t xHeapRegions[] = 
	{
		{ ucHeap, configTOTAL_HEAP_SIZE },
		{ NULL, 0 }
	};
	vPortDefineHeapRegions(xHeapRegions);
}
BOOL initFlag = 0;


int main(void)
{

	unsigned char i_flage=0;
	unsigned int  back_data=0;


	prvInitialiseHeap();
	configASSERT(POS_MANAGE_PRIORITY < configTIMER_TASK_PRIORITY);
	Cpu_Init();	
	
	ScanFlash();
	
	PrinterInit();
       
	SendSor_Init();

#ifdef USE_LCD
	LCD_Drv_Init();	
#endif

	WDT_Configuration();		

	BOARD_KEY.power_state = 1;



	MyPrintf("main loop start:\n");

	Init_KalmanInfo(&KFP_height,0.01,0.5);


	PollingExtDev_1(1);
	PollingExtDev_2(0);
	hal_Init();


	xTaskCreate(main_task, "MAIN", 4 * configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 2), NULL);
//_	App_Init();
	initFlag = 1;
	vTaskStartScheduler();
	
//	while(1)
//	{
//			IWDG_Reload;
//			cData = GetDataFromRcvBuf();
//	
//			if(cData < 0x20)
//			{
//				//command
//				ExecuteCmd(cData);
//			}
//			else
//			{
//				//Prt data
//				//MyPrintf("cData area cData=0x%02x\n",cData); 
//				ExecuteData(cData);
//			}
//	}

}	






/**********************************END*****************************************/















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值