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,而且我有一段时间没有在高端内核(带有向量表)中编程中断,因此您可能需要进行一两次更改。另请注意,您需要通过设置适当的寄存器来启用中断,因为默认情况下不启用它们。
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;
}
}