gpt4 book ai didi

c - 如何从 UART 正确接收字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:52 24 4
gpt4 key购买 nike

我发送这样的字符串:$13,-14,283,4,-4,17,6,-240,-180#

但由于缓冲区“重载”而未显示,我如何接收整个字符串或如何在读取每个字节后清除它?

// get a character string 
char *getsU2(char *s, int len) {
char *p = s; // copy the buffer pointer
do {
*s = getU2(); // get a new character
if (( *s=='\r') || (*s=='\n')) // end of line...
break; // end the loop s++;

// increment the buffer pointer
len--;
} while (len>1); // until buffer is full

*s = '\0'; // null terminate the string

return p; // return buffer pointer
}


// get a character string
char *getsU2(char *s, int len) {
char *p = s; // copy the buffer pointer
do {
*s = getU2(); // get a new character

if (( *s=='\r') || (*s=='\n')) // end of line...
break; // end the loop

s++;

// increment the buffer pointer
len--;
} while (len>1); // until buffer is full

*s = '\0'; // null terminate the string

return p; // return buffer pointer
}



char getU2(void) {
if(U2STAbits.OERR == 1)
{ U2STAbits.OERR = 0; }
while (!U2STAbits.URXDA); // wait for new character to arrive return U2RXREG;
// read character from the receive buffer }

getsU2(buffer,sizeof(buffer));

最佳答案

尝试使用 UART 接收中断。以下代码适用于 PIC24H;适当修改。

在你的初始化函数中:

IFS0bits.U1RXIF = 0;        // clear rx interrupt flag
IFS0bits.U1TXIF = 0; // clear tx interrupt flag

IEC0bits.U1RXIE = 1; // enable Rx interrupts
IPC2bits.U1RXIP = 1;
IEC0bits.U1TXIE = 1; // enable tx interrupts
IPC3bits.U1TXIP = 1;

创建一个将字节放入缓冲区或队列的中断处理程序:

void __attribute__((__interrupt__, auto_psv)) _U1RXInterrupt(void)
{
char bReceived;

// Receive Data Ready
// there is a 4 byte hardware Rx fifo, so we must be sure to get all read bytes
while (U1STAbits.URXDA)
{
bReceived = U1RXREG;

// only usethe data if there was no error
if ((U1STAbits.PERR == 0) && (U1STAbits.FERR == 0))
{
// Put your data into a queue
FIFOPut(bReceived);

}

}

IFS0bits.U1RXIF = 0; // clear rx interrupt flag
}

您的队列代码如下:

#define FIFO_SIZE 64

char pbBuffer[FIFO_SIZE];
char *pbPut;
char *pbGet;

void FIFOInit(void)
{
pbPut = pbBuffer;
pbGet = pbBuffer;
}

void FIFOPut(char bInput)
{
*pbPut = bInput;
pbPut++;

if (pbPut >= (pbBuffer + FIFO_SIZE))
pbPut = pbBuffer;
}

char FIFOGet(void)
{
char bReturn;

bReturn = *pbGet;
pbGet++;

if (pbGet>= (pbBuffer + FIFO_SIZE))
pbGet= pbBuffer;
}

显然,应该加强 FIFO 功能以防止溢出、在空队列上返回错误等。

关于c - 如何从 UART 正确接收字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10244643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com