Skip to content

Instantly share code, notes, and snippets.

@JeonghunLee
Created November 22, 2017 04:31
Show Gist options
  • Save JeonghunLee/6f61b91a93aabb71537fd25ddb3aa885 to your computer and use it in GitHub Desktop.
Save JeonghunLee/6f61b91a93aabb71537fd25ddb3aa885 to your computer and use it in GitHub Desktop.
FIFO example
/*
* Jeonghun Lee
* Recently, I made FIFO functions by using Array in MSP430 for optimization
*/
#define MAX_TX_BUFF 1024
#define MAX_RX_BUFF 128
/*
* TX-FIFO , Array Type FIFO so only used txhead and txcnt
*/
char txmsg[MAX_TX_BUFF]={0}; //FIFO Buffer
uint16_t txhead=0; //FIFO first Postion
uint16_t txcnt=0; //FIFO Size
/*
* RX-FIFO , Arrary Type FIFO so only used rxtail and rxcnt
*/
char rxmsg[MAX_RX_BUFF]={0}; //FIFO Buffer
uint16_t rxtail=0; //FIFO RX Last Postion but Real Last Postion (rxtail-1).
uint16_t rxcnt=0; //FIFO RX Count (rxcnt)
uint16_t rdUART1DATA(char *data , uint16_t lens) // remove elements from rxmsg
{
uint16_t i,start,end,cnt=0;
if(rxcnt >= (MAX_RX_BUFF-1)) { rxtail=0; rxcnt=0; return 1;} // overun
else if(rxcnt <= 0 ) { return 2;} // empty buffer
else if(rxcnt < lens ) { return 3;} // underrun
/*
* start point
*/
if( rxcnt > rxtail ) start = MAX_RX_BUFF-(rxcnt-rxtail); // rxcnt > rxtail means
else start = rxtail-rxcnt; //
end = lens;
cnt = 0;
i= start;
while( cnt < end ) //find sync
{
data[i] = rxmsg[i];
cnt++; // sync position
i=((i+1) & (MAX_RX_BUFF-1));
}
return 0;
}
uint16_t rdUART1STR(char *data, uint16_t lens)
{
uint16_t rt=0;
rt = rdUART1DATA(data,lens);
if(rt != 0){
rxcnt=0;
rxtail=0;
}
return rt;
}
bspIState_t intState;
uint16_t wrUART1DATA(char *data , uint16_t lens)
{
uint16_t i=0,pos=0;
if((txcnt+lens) > (MAX_TX_BUFF-1)) return 1;
for(i=0;i<lens;i++)
{
BSP_ENTER_CRITICAL_SECTION(intState);
pos = (txhead + txcnt) & (MAX_TX_BUFF-1);
txmsg[pos] = *(data+i);
txcnt++;
BSP_EXIT_CRITICAL_SECTION(intState);
}
if(!(UCA1IFG&UCTXIFG))
UCA1IFG |= UCTXIFG;
return 0;
}
uint16_t wrUART1STR(char *data, uint16_t lens)
{
uint16_t rt=0;
rt = wrUART1DATA(data,lens);
if(rt != 0){
BSP_ENTER_CRITICAL_SECTION(intState);
txcnt=0;
BSP_EXIT_CRITICAL_SECTION(intState);
}
return 0;
}
#if defined(__TI_COMPILER_VERSION__)
#pragma vector=USCI_A1_VECTOR
__interrupt void USCI_A1_ISR(void)
#else
#error Compiler not supported!
#endif
{
if(UCA1IFG & UCRXIFG){
UCA1IFG &= ~UCRXIFG;
//FIFO, Input
rxmsg[rxtail] = UCA1RXBUF; // insert data from register
rxtail = (rxtail + 1) & (MAX_RX_BUFF-1); // loop routine
rxcnt++;
}
if(UCA1IFG & UCTXIFG){ //somtimes, have the problem so change to polling mode
UCA1IFG &= ~UCTXIFG;
if(txcnt > 0 ){
UCA1TXBUF = txmsg[txhead];
txhead = (txhead + 1) & (MAX_TX_BUFF-1);
txcnt--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment