基于CC254x蓝牙协议栈的串口收发非常简单,现总结成5个步骤:
1.修改NPI下npi.c中的初始化函数
只需修改配置UART的两个参数:波特率和流控制。
使用两线的串口通信时必须关闭流控制,波特率根据需求选择。
void NPI_InitTransport( npiCBack_t npiCBack )
{
halUARTCfg_t uartConfig;
// configure UART
uartConfig.configured = TRUE;
uartConfig.baudRate = NPI_UART_BR;
uartConfig.flowControl = NPI_UART_FC;
uartConfig.flowControlThreshold = NPI_UART_FC_THRESHOLD;
uartConfig.rx.maxBufSize = NPI_UART_RX_BUF_SIZE;
uartConfig.tx.maxBufSize = NPI_UART_TX_BUF_SIZE;
uartConfig.idleTimeout = NPI_UART_IDLE_TIMEOUT;
uartConfig.intEnable = NPI_UART_INT_ENABLE;
uartConfig.callBackFunc = (halUARTCBack_t)npiCBack;
// start UART
// Note: Assumes no issue opening UART port.
(void)HalUARTOpen( NPI_UART_PORT, &uartConfig );
return;
}
上述代码中baudRate和flowControl两个成员分别为波特率和流控,点进去修改即可,非常方便。
2.修改预编译选项
打开 option——C/C++ 的 CompilerPreprocessor,添加 HAL_UART=TRUE,并将 POWER_SAVING 注释掉。
3.修改串口读写函数(可选,npi.c中)
比如封装其他格式的读写函数,以下参考博主甜甜大香瓜的代码:
//******************************************************************************
//name: NPI_PrintString
//introduce: 打印字符串
//parameter: str:字符串
//return: none
//******************************************************************************
void NPI_PrintString(uint8 *str)
{
NPI_WriteTransport(str, osal_strlen((char*)str));
}
//******************************************************************************
//name: NPI_PrintValue
//introduce: 打印指定的格式的数值
//parameter: title:前缀字符串
// value:需要显示的数值
// format,需要显示的进制,10或16
//return: none
//******************************************************************************
void NPI_PrintValue(char *title, uint16 value, uint8 format)
{
uint8 tmpLen;
uint8 buf[128];
uint32 err;
tmpLen = (uint8)osal_strlen( (char*)title );
osal_memcpy( buf, title, tmpLen );
buf[tmpLen] = ' ';
err = (uint32)(value);
_ltoa( err, &buf[tmpLen+1], format );
NPI_PrintString(buf);
}
记得在npi.h中声明自定义的函数。
4.定义串口接收的回调函数(可选,若需串口接收时必须)
//串口测试
static void NpiSerialCallback( uint8 port, uint8 events )
{
(void)port;
uint8 numBytes = 0;
uint8 buf[128];
if (events & HAL_UART_RX_TIMEOUT) //串口有数据
{
numBytes = NPI_RxBufLen(); //读出串口缓冲区有多少字节
if(numBytes)
{
//从串口缓冲区读出numBytes字节数据
NPI_ReadTransport(buf,numBytes);
//把串口接收到的数据再打印出来
//NPI_WriteTransport(buf,numBytes);
}
}
}
记得作前置声明,并且在simpleBLECentral.c中包含npi.h头文件。
5.调用串口初始化,进行串口通信
若只发送,可以在SimpleBLECentral_Init中做如下调用:
NPI_InitTransport(NULL);
NPI_PrintString("Hello World!\n");//测试串口发送
若还需要接收,可以在SimpleBLECentral_Init中做如下调用:
NPI_InitTransport(NpiSerialCallback);//串口接收中断触发后,接收回调函数中处理串口接收到的数据
NPI_PrintString("Hello World!\n");