2013-02-08 39 views
2

我想從波特率= 38400的PIC 18f4550傳感器讀取。使用FIFO循環緩衝區,我可以將來自傳感器的數據存儲到一個陣列中。PIC中斷驅動的UART與高波特率的循環緩衝區

傳感器將響應請求命令並返回15個字節的測量結果(與我創建的循環緩衝區相同)。我必須抓住所有的15個字節並在最後放置\ r \ n以分開每個測量,因爲沒有刪除器。

所以我用了兩個三分球,inputpointeroutputpointer存儲字節,發送字節出來。因爲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. 

}

+0

FIFO超限?您的代碼中存在FIFO欠載運行錯誤:在發送第一個字節之前,您不檢查是否有實際的數據。這可能只是一些作品,因爲你柔軟的uart速度很慢。 –

+0

@TurboJ我得到了帶有2個UART模塊的dsPIC30f4011,並且正在開發中。但我認爲它不能解決問題。有更多的代碼用於發送數據,然後接收數據和接收具有高優先級(中斷驅動),因此最終會出現溢出,除非我停止請求直到所有字節已發出。 – Timtianyang

回答

0

也許你可以關閉中斷,而你是轉移傳感器讀出,然後轉移完成後重新啓用數據出來了嗎?

它可能沒有顯着的區別,但它可能會阻止你提到的FIFO溢出?

+1

我想過,但是如果在禁用中斷之後有一個字節進入,但是當我還處於中斷程序之內呢?我會失去這個字節嗎? – Timtianyang

+0

是的,當然,你會失去字節。而且我的歉意,我以爲你的代碼塊是另一種方式,在INTERRUPT中你將緩衝區數據導出到你的筆記本電腦(每隔一段時間(或者當緩衝區已滿)或者在你的MAIN循環中緩衝傳感器讀數。 – Zeddy