我正在尝试从具有 PIC 18f4550 的传感器以波特率 = 38400 读取数据。使用 FIFO 循环缓冲区,我可以将传感器中的数据存储到数组中。
传感器将响应请求命令并返回 15 个字节的测量值(与我创建的循环缓冲区相同)。我必须抓取所有15 个字节并将 \r\n 放在末尾以分隔每个测量值,因为没有分隔符。
所以我使用了两个指针,inputpointer和outputpointer来存储字节和传输字节。因为18f4550只有一个硬UART,所以我用它来读取数据并向传感器发送命令,同时使用软件UART通过RS232输出到笔记本电脑。
当缓冲区被读取并发送到串行端口时,我请求进行新的测量。
它工作得很好,但我只想知道当头指针超出尾指针时是否有更好的方法来避免FIFO溢出,即当有大量数据被缓冲但它们无法及时输出时。
这是代码:16MHZ PIC 18f4550 mikroC 编译器
char dataRx[15];
char unsigned inputpointer=0;
char unsigned outputpointer=0;
// initialize pointers and buffer.
void main() {
ADCON1=0x0F; //turn analog off
UART1_Init(115200); //initialize hardware UART @baudrate=115200, the same setting for the sensor
Soft_UART_Init(&PORTD,7,6,38400,0); //Initialize soft UART to commnuicate with a laptop
Delay_ms(100); //let them stablize
PIE1.RCIE = 1; //enable interrupt source
INTCON.PEIE = 1;
INTCON.GIE = 1;
UART1_Write(0x00); //request a measurement.
UART1_Write(0xE1); //each request is 2 bytes
while(1){
Soft_UART_Write(dataRx[outputpointer]); //output one byte from the buffer to laptop
outputpointer++; //increment output pointer
if(outputpointer==0x0F) //reset pointer if it's at the end of the array
{
outputpointer=0x00;
Soft_UART_Write(0x0D); //if it's at the end, that means the buffer is filled with exactly one measurement and it has been output to the laptop. So I can request another measurement.
Soft_UART_Write(0x0A); //add \r\n
UART1_Write(0x00); //request another measurement
UART1_Write(0xE1);
}
}
void interrupt(void){ //interrupt routine when a byte arrives
dataRx[inputpointer]=UART1_Read(); //put a byte to a buffer
inputpointer++;
if (inputpointer==0x0F){inputpointer=0;} //reset pointer.
}