#include "gkbaseusart.h"
#include "string.h"
GK_USARTBASE_TYPE GKU1;
GK_USARTBASE_TYPE GKU2;
uint8_t GK_usart_init(GK_USARTBASE_TYPE *myuart,uint8_t usartid)
{
switch(usartid)//绑定关系
{
case 1:myuart->huart=&huart1;break;
case 2:myuart->huart=&huart2;break;
default :return 0;
}
HAL_UART_Receive_IT(myuart->huart, &myuart->one, 1);//开启中断接收 1个1个的接收
__HAL_UART_ENABLE_IT(myuart->huart,UART_IT_IDLE);//开启空闲中断
return 1;
}
void GK_usart_clear(GK_USARTBASE_TYPE *myuart)
{
myuart->one=0;
myuart->rx_len=0;
myuart->received2idle=0;
memset(myuart->rxBuf,0,sizeof(myuart->rxBuf));
}
void GK_UART_RxIdleCallback(GK_USARTBASE_TYPE *myuart)
{
if(__HAL_UART_GET_FLAG(myuart->huart,UART_FLAG_IDLE))
{
__HAL_UART_CLEAR_IDLEFLAG(myuart->huart);
myuart->received2idle=1;
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) //这里扩展一下!!!!
{
if(huart->Instance == USART1)
{
GKU1.rxBuf[GKU1.rx_len++]=GKU1.one; //类似标准外设库函数
HAL_UART_Receive_IT(huart, &GKU1.one, 1) ;
}
if(huart->Instance == USART2)
{
GKU2.rxBuf[GKU2.rx_len++]=GKU2.one; //类似标准外设库函数
HAL_UART_Receive_IT(huart, &GKU2.one, 1) ;
}
}
uint8_t GK_usart_TXRX(GK_USARTBASE_TYPE *myuart, void *Tx ,uint16_t TXlen ,uint8_t *RX,uint16_t *RXlen)
{
uint8_t Cnt = 100,ack=0;
uint8_t *TX =(uint8_t*)Tx;
//准备工作:
GK_usart_clear(myuart);
//发送:
HAL_UART_Transmit(myuart->huart, TX, TXlen, 0xFFFF);
//等待返回:
while(Cnt--)
{
if(myuart->received2idle)
{
ack=1;
break;
}
HAL_Delay(10);//尝试次数 10次 这里面其实需要喂狗 每次这样的情形都有喂狗
}
//处理返回:
if(ack==0)
return 0;
*RXlen=myuart->rx_len;
memcpy(RX,myuart->rxBuf,myuart->rx_len);
//收尾工作:
GK_usart_clear(myuart);
return 1;
}
#ifndef __GKBASEUSART_H_
#define __GKBASEUSART_H_
#include "usart.h"
#define RECEIVELEN 1024
typedef struct
{
UART_HandleTypeDef *huart;
uint8_t one;//当前过来的HEX
uint16_t rx_len;
uint8_t rxBuf[RECEIVELEN];
uint8_t received2idle;//1空闲中断到了
}GK_USARTBASE_TYPE ;
extern GK_USARTBASE_TYPE GKU1;
extern GK_USARTBASE_TYPE GKU2;
extern uint8_t GK_usart_init(GK_USARTBASE_TYPE *myuart,uint8_t usartid);
extern uint8_t GK_usart_TXRX(GK_USARTBASE_TYPE *myuart, void *Tx ,uint16_t TXlen ,uint8_t *RX,uint16_t *RXlen);
extern void GK_usart_clear(GK_USARTBASE_TYPE *myuart);
extern void GK_UART_RxIdleCallback(GK_USARTBASE_TYPE *huart);
#endif