我在使用const缓冲区和char arrray写入USARt时遇到了问题。
下面是我的UART写函数:
unsigned int USART_Send( unsigned char *p_pucData,
unsigned int p_unLen)
{
AT91C_BASE_US2->US_TPR = (unsigned int)p_pucData;
AT91C_BASE_US2->US_TCR = p_unLen;
AT91C_BASE_US2->US_PTCR = AT91C_PDC_TXTEN;
while((AT91C_BASE_US2->US_CSR & ((0x1 << 11) | (0x1 << 4) ) ) == 0);
AT91C_BASE_US2->US_PTCR = AT91C_PDC_TXTDIS;
return p_unLen;
}下面的函数与const char*类似:
USART_Send("IsitDone?",9); //Working如果我使用像下面这样的数组缓冲区来显示垃圾字符,那么为什么呢?
unsigned char arr[10];
memcpy(arr, "HelloWorld", 10);
USART_Send(arr, sizeof(arr)); //Not working properly displaying Garbage chars发布于 2014-12-29 22:23:32
里卡多·克鲁多是对的。您会遇到以下问题:
arr is created on the stack
arr is filled
call USART_Send
fill transmit pointer, counter, enable tx requests
/* peripheral state is TXBUFE = '0' and ENDTX = '0' because: */
/* TXBUFE = '0' when PERIPH_TCR != 0 and */
/* ENDTX = '0' when PERIPH_TCR != 0 */
/* but we just wrote to PERIPH_TCR, so it's != 0 */
/* both conditions are satisfied, b/c the transfer hasn't started yet! */
wait until (TXBUFE = '0' and ENDTX = '0')
/* your code thinks PDC is done here */
/* but in reality, PDC is getting started */
disable tx requests
return from sub-function
overwrite stack (and arr) with unrelated data here
/* PDC might push out last word(s) here due to pipelining/ */
/* instruction cache/side effects/you-name-it */
/* even though its matrix requests were disabled a few cycles ago */解决办法:
理想情况下,您应该为字符串分配一些动态内存,并在PDC异步执行到实际代码之后释放它。在完成PDC/外设之后,您可能需要检查是否可以得到某种中断,然后释放从它读取的内存。
如果您没有动态内存分配,那么使用全局循环缓冲区并抽象您的字符串/char发送函数来代替此缓冲区。
https://stackoverflow.com/questions/25680878
复制相似问题