dsPic接收11byte usart字符串

时间:2015-01-09 09:42:23

标签: microchip usart

我正在使用dsPic33尝试接收一个11字节的字符串并将其放在一个数组中,但是没有成功完全接收它。我发送的字符串是“$ 123456789#”,应该由pic接收。我尝试过使用下面的代码。任何帮助将不胜感激。

char inBytes[11];
int i;
unsigned char temp;

while (U1STAbits.URXDA != 0)
{
  temp = U1RXREG;
  if (temp == '$')
  {
      inBytes[0] = temp;
      for(i = 1; i < 10; i++)
      {
        if (U1STAbits.URXDA != 0)
        inChar = U1RXREG;
        inBytes[i] = inChar;
      }
  }

2 个答案:

答案 0 :(得分:1)

for(i = 1; i < 10; i++)开始在索引1处保存数据,并在9处停止,只有9个字节。将< 10更改为<= 10< 11

答案 1 :(得分:1)

jolati有一个很好的观点,即最终值太低而无法获得11个字节,但我必须补充一点,你必须等待其他字节在你阅读之前可用。

在你的例子中;

char inBytes[11];
int i;
unsigned char temp;

while (!U1STAbits.URXDA ); //Wait until at least one byte is available

temp = U1RXREG;
if (temp == '$')
{
    inBytes[0] = temp;

    for(i = 1; i < 11; i++) //Loop over range i = 1 to 10 inclusively
    {
        while (!U1STAbits.URXDA ); //Wait until at least one byte is available
        inBytes[i] = U1RXREG;
    }
}

理想情况下,您可以使用中断以非阻塞方式执行此操作,以便在处理数据时处理数据,但是,如果您无法使用中断,则可以始终使用非阻塞轮询,如:

void AsyncRX()
{
    //Note that the static variables keeps their value between invocations of the
    //  function. i is set to 0 only on the first run of this function, it keeps 
    //  its value on every other run after that.
    static int i = 0;
    static char inBytes[11];

    //Nothing more to do until there is at least 1 byte available
    if( !U1STAbits.URXDA ) 
        return;

    //Save the byte and test that our message starts with $
    inBytes[i] = U1RXREG;
    if( inBytes[0] != '$' )
        return;

    //Test the counter to see if we have a full 11 bytes
    i++;
    if( i < 11 )
        return;

    //Do something with your 11 bytes
    //...
    //...

    //Reset the counter for the next message
    i = 0;
}

对于中断示例,您可以简单地抓取轮询版本并将其扔入ISR。以下是一个例子。请注意,我不知道您正在使用哪个dsp33,并且我没有在高端内核(使用向量表)中编程中断,因此您可能需要进行一两次更改。另请注意,您需要通过设置相应的寄存器来启用interupts,因为默认情况下它们未启用。

void __attribute__ ((interrupt, no_auto_psv)) _U1RXInterrupt(void) 
{
    //Note that the static variables keeps their value between invocations of the
    //  function. i is set to 0 only on the first run of this function, it keeps 
    //  its value on every other run after that.
    static int i = 0;
    static char inBytes[11];

    //Reset the interrupt flag
    IFS0bits.U1RXIF = 0;

    //Use up all bytes in the buffer (the interrupt can be set to only fire 
    //  once the buffer has multiple bytes in it).
    while( U1STAbits.URXDA ) 
    {
        //Save the byte and test that our message starts with $
        inBytes[i] = U1RXREG;
        if( inBytes[0] != '$' )
            continue;

        //Test the counter to see if we have a full 11 bytes
        i++;
        if( i < 11 )
            continue;

        //Do something with your 11 bytes
        //...
        //...

        //Reset the counter for the next message
        i = 0;
    }
}