基本原理:靜態隊列
/* * 串口的FIFO簡單讀取實現 * 功能,實現串口的FIFO實現 * 使用方法: * 版本:v1.0.0 * */ #include "sys.h" #include "usartbuf.h" USARType Usart_fifo_Read( Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length) { if (Rusart->Count - length < 0)//緩沖區沒有足夠的數據 { return USARTREADOVER;//讀數據越界 } while (length--) { *buf = Rusart->Recerivrbuffer[Rusart->Pread]; buf++; Rusart->Count --; Rusart->Pread++;//讀取指針自加 if(Rusart->Pread == RECERIVRSIZE) { Rusart->Pread =0; } } return USARTOK;//數據讀取成功 } /*向緩沖區中寫入length個數據*/ USARType Usart_fifo_write(Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length)// { if (Rusart->Count + length > RECERIVRSIZE)//寫入的數據超過緩沖區 { return USARTWRITEOVER;//寫數據越界 } while(length--) { Rusart->Recerivrbuffer[Rusart->Pwrite] = *buf;//賦值給緩沖區 buf++;//緩沖區地址加一 Rusart->Count ++; Rusart->Pwrite++;// if(Rusart->Pwrite == RECERIVRSIZE) { Rusart->Pwrite =0; } } return USARTOK;//數據讀取成功 } /*清空緩沖區*/ void Usart_fifo_Clear(Usart_RecerivePoint Rusart) { Rusart->Count = 0; Rusart->Pread =0;//讀指針為0 Rusart->Pwrite = 0;//寫指針為0 }
#ifndef _USARTBUF_H #define _USARTBUF_H /*該參數設置接受區大小*/ #define RECERIVRSIZE 64//接受區大小 typedef struct { int Pread;//讀指針 int Pwrite;//寫指針 int Count;//緩沖區計數 uint8_t Recerivrbuffer[RECERIVRSIZE];//接受緩沖區 }Usart_ReceriveType,*Usart_RecerivePoint; #define USARType int #define USARTREADOVER -2//串口數據超出 #define USARTWRITEOVER -3//串口寫數據越界 #define USARTOK 1 USARType Usart_fifo_write(Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);USARType Usart_fifo_Read( Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length); void Usart_fifo_Clear(Usart_RecerivePoint Rusart); #endif/*_USARTBUF_H*/
使用方式:定義一個Usart_ReceriveType類型的緩沖隊列,然后就可以利用上述文件中提供的三個函數來實現串口的FIFO的數據接受和讀取
使用的時候可以利用
USARType Usart_fifo_write(Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);
USARType Usart_fifo_Read( Usart_RecerivePoint Rusart,uint8_t * buf,uint8_t length);
這兩個函數來向緩沖區中寫入和讀取數據,其中參數的含義如下
第一個參數(Rusart)是串口緩沖區指針類型,用來標示串口,
第二個參數(buf)是一個指uint8_t類型的指針,用來指向要寫入或者讀取數據的首地址,
第三個參數(length)表示要寫入或者讀取的數據長度
出口參數USARType 實際是一個整形數據,返回值得意義入下
#define USARTREADOVER –2//串口數據超出
#define USARTWRITEOVER -3//串口寫數據越界
#define USARTOK 1// 串口緩沖區數據讀出或者寫入成功
void Usart_fifo_Clear(Usart_RecerivePoint Rusart);
這個函數用來清空緩沖區數據,實現起來比較簡單
