Some SCM serial port does not have FIFO, or can be assigned to the FIFO size is very limited, if the program needs to send a large packet to the peripheral, it takes a long time, in order to solve the application and peripherals hardware read and write synchronization problem, it is necessary to realize the circular FIFO.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace Std;
#define Error_full_w-1
#define Error_empty_r-2
#define TRUE 0
#define FULL 1
#define EMPTY 1
#define UCHAR unsigned char
#define UINT unsigned int
First, the definition of circular FIFO
struct fifo{
Uchar *m_buf;
UINT m_bufsize;
UINT m_wp;
UINT M_RP;
UINT Fullflag;
UINT Emptyflag;
};
typedef struct FIFO Cfifo;
Second, write queue
int Ffifopush (Cfifo *myfifo, Uchar c) {
UINT Tmp_len;
if (Myfifo->fullflag!= full) {
Tmp_len = myfifo->m_wp;
Myfifo->m_buf[tmp_len] = c;
tmp_len++;
if (Tmp_len >= myfifo->m_bufsize) tmp_len = 0;
if (Tmp_len = = MYFIFO->M_RP) {
myfifo-> Fullflag = full;
}
MYFIFO->M_WP = Tmp_len;
Myfifo-> Emptyflag =! EMPTY;
return TRUE;
}
else return error_full_w;
}
3. Read the data from the queue
int Ffifopop (Cfifo *myfifo, int *data) {
UINT Tmp_len;
Uchar Tmp_char;
if (Myfifo->emptyflag!= EMPTY) {
Tmp_len = myfifo->m_rp;
Tmp_char = myfifo->m_buf[tmp_len];
*data = Tmp_char;
tmp_len++;
if (Tmp_len >= myfifo->m_bufsize) tmp_len = 0;
MYFIFO->M_RP = Tmp_len;
if (Tmp_len = = myfifo->m_wp) {
Myfifo->emptyflag = EMPTY;
}
Myfifo-> Fullflag =! Full;
return TRUE;
}
else return error_empty_r;
}
4. Calculate the length of data in the queue
UINT Ffifochecklen (Cfifo *myfifo) {
if (Myfifo->emptyflag = = EMPTY) return 0;
else if (Myfifo->fullflag = Full) return myfifo->m_bufsize;
if (myfifo->m_wp >= myfifo->m_rp) {
return MYFIFO->M_WP-MYFIFO->M_RP;
}
else{
return MYFIFO->M_BUFSIZE-MYFIFO->M_RP + myfifo->m_wp;
}
}
5. Empty queues
void Ffifoempty (Cfifo *myfifo) {
myfifo->m_wp = 0;
MYFIFO->M_RP = 0;
Myfifo->emptyflag = EMPTY;
Myfifo->fullflag =! Full;
}
6. Initializing queues
void Ffifoinit (Cfifo *myfifo, Uchar *tmp_buf, UINT tmp_size) {
Myfifo->m_buf = Tmp_buf;
Myfifo->m_bufsize = tmp_size;
Ffifoempty (MYFIFO);
}
7. Test queue
int main (void) {
Cfifo *myfifo;
Uchar cnt = 0;
int i = 0;
int data = 0;
if ((Myfifo = (Cfifo *) calloc (1,sizeof (CFIFO))) = = NULL) {
cout<< "malloc failed" <<endl;
}
Uchar DATA_BUF[20];
Ffifoinit (myfifo,data_buf,20);
for (i = 0; i<21;i++) {
if (Ffifopush (myfifo,i*2) = = TRUE)
cout<< "The Push data is" <<i*2<< "the Lengh is" <<ffifochecklen (MYFIFO) <<endl;
else break;
}
for (i = 0; i<22;i++) {
if (Ffifopop (Myfifo, &data) = = TRUE)
cout<< "The pop data is" <<data<< "the Lengh is" <<ffifochecklen (MYFIFO) <<endl;
else break;
}
}
8. Running results in VC6.0