2015年7月30日 星期四

ZigBee TI CC2530 程式筆記-UART(RS-232) 使用方式 IAR

我主要開發的是SampleAPP,版本2.5.1a。

一.初始化(在SampleAPP.c內設定UART的相關參數)

#include "hal_uart.h" //include UART的function

在Init內增加UART的code。

void SampleApp_Init( uint8 task_id )
{
  halUARTCfg_t uartConfig;
  uartConfig.configured           = TRUE;
  uartConfig.baudRate             =   HAL_UART_BR_38400;  
  uartConfig.flowControl          = FALSE;
  uartConfig.flowControlThreshold = 64;
  uartConfig.rx.maxBufSize        = 128;
  uartConfig.tx.maxBufSize        = 128;
  uartConfig.idleTimeout          = 6;  
  uartConfig.intEnable            = TRUE;            
  uartConfig.callBackFunc         = SerialApp_CallBack;
  HalUARTOpen (HAL_UART_PORT_0, &uartConfig);
}

簡單介紹一下相關參數
1.uartConfig.baudRate 設定Data Rate

Data Rate的定義在hal_uart.h裡面,總共有5種可以選擇。

     #define HAL_UART_BR_9600   0x00
     #define HAL_UART_BR_19200  0x01
     #define HAL_UART_BR_38400  0x02
     #define HAL_UART_BR_57600  0x03
     #define HAL_UART_BR_115200 0x04

2.uartConfig.flowControl 流量控制,我是設定關。

3.uartConfig.rx.maxBufSize 和 uartConfig.tx.maxBufSize,就是當你收資料和送資料的時候,最大值是多少,小於等於可以送,不能超過。

4.uartConfig.callBackFunc 指定一個function給UART用,這很好用。請參考第二點。

5.HalUARTOpen 開啟Port
如果是使用TI CC2530 ZDK的開發版,都是用HAL_UART_PORT_0。
定義在hal_uart.h
/* Ports */
#define HAL_UART_PORT_0   0x00
#define HAL_UART_PORT_1   0x01
#define HAL_UART_PORT_MAX 0x02


---------------------------------------我是分隔線--------------------------------------------------
二.Call Back Function

當設備收到UART資料的時候,就會執行指定的function,做後續的處理。
SerialApp_CallBack是自定義的,也可以不用,看需求。

宣告
void SerialApp_CallBack( uint8 port, uint8 event );

程式內容
void SerialApp_CallBack( uint8 port, uint8 event ){

 if (event & (HAL_UART_RX_FULL | HAL_UART_RX_ABOUT_FULL | HAL_UART_RX_TIMEOUT))
  {
     //UART收到資料後續處理
  }
}

注意並不是function寫上去,有資料進入UART,才會執行。
事實上它會一直執行,所以function內用 if 是判斷是否有資料進入UART,有就做後續的處理。

---------------------------------------我是分隔線--------------------------------------------------
三.Write and Read

UART收到資料後,就可以讀出資料。下面有一個簡單範例

首先新增兩個Array,一個用來收資料,另一個送資料。
其實也可以一個就好,但是分開比較清楚。
1.定義 Array
static uint8 SerialApp_TxBuf[128];
static uint8 SerialApp_RxBuf[128];
static uint8 SerialApp_RxLen;

2.Read
void SerialApp_CallBack( uint8 port, uint8 event ){

 if (event & (HAL_UART_RX_FULL | HAL_UART_RX_ABOUT_FULL | HAL_UART_RX_TIMEOUT))
  {
     //UART收到資料後續處理
     SerialApp_RxLen=HalUARTRead(HAL_UART_PORT_0, SerialApp_RxBuf, 127);
    //讀UART資料,儲存到SerialApp_RxBuf,SerialApp_RxLen為實際資料長度。
    //設定127是因為array max 128的關係,UART傳送最好比128小。
  }
}

3.Write

SerialApp_TxBuf[0]=0;
SerialApp_TxBuf[1]=1;
SerialApp_TxBuf[2]=2;
SerialApp_TxBuf[3]=3;

HalUARTWrite(HAL_UART_PORT_0, SerialApp_TxBuf, 4);