2015-03-31 130 views
2

我目前正在Raspberry Pi計算機上運行一段C代碼。它是一個隨機數發生器,它從連接到GPIO數字輸入18的蓋革計數器中讀取。它隨機產生位(見代碼)並以8爲一組打印位。此外,每隔30秒打印一次觀測輻射的當前電平。代碼似乎工作正常,除非輻射源被拿走。隨機數的生成速度較慢,但​​它似乎也減慢了其餘任務的速度。在程序開始時打印的信息不會顯示,直到生成一個隨機數。發生這種情況時,不顯示數字,但添加了一個沒有數字的換行符。即使在程序運行時,輻射水平似乎每30秒打印一次,但也會打印下一個隨機數。爲什麼C以錯誤的順序執行代碼?爲什麼C打印輸出較遲?

#include <wiringPi.h>//library for I/O 
#include <stdlib.h> 
int main(int argc, char *argv[]) 
{ 
    int lastRead;//if this is first time observing current pulse 
    int pulseCount = 0;//number of total pulses from Geiger counter 
    long timing[4] = {0,0,0,0};//values to compare to produce one bit 
    int bits[8] = {0,0,0,0,0,0,0,0};//the newest number 
    int bitCount = 0;//counts how many random bits have been made 
    int i = 0; 
    float startTime = 0;//start of the clock 
    float currentSec = 0; 
    float currentMin = 0; 
    float cpm = 0; 
    long elapsedTime = 0; 

    wiringPiSetupGpio();//establish physical connection 
    pinMode(18, INPUT);//set pin 18 to be input 
    printf("random\tradiation"); 

    while(1) 
    { 
     if(millis()-startTime >= 30000)//30 sec passed? 
     { 
      startTime = millis(); 
      currentSec = startTime/1000; 
      currentMin = currentSec/60; 
      cpm = pulseCount/currentMin;//calculate counts/min in several steps 
      printf("\t%f", cpm);//output counts/min 
     } 
     if(digitalRead(18) == HIGH)//pin is reading high 
     { 
      if(lastRead==0)//is not reading the same pulse again 
      { 
       lastRead = 1;//pulse has been identified 
       timing[pulseCount%4] = millis();//save the time 
       pulseCount++;//pulse detected 

       if(pulseCount%4 == 0)//if times have been collected 
       { 
        if(timing[1]-timing[0] > timing[3]-timing[2])//make a random bit 
        { 
         bits[bitCount%8] = 0;//nth bit of set of 8 is 0 
        } 
        else { 
         bits[bitCount%8] = 1;//it is one 
        } 
        bitCount++;//note that a bit was added 

        if(bitCount%8 == 0)//every 8 bits made 
        { 
         printf("\n"); 

         for(i = 0; i < 8; i++)//print them on a new line 
         { 
          printf("%d", bits[i]); 
         }//for 
        }//if(bitCount%8==0) 
       }//if(pulseCount%4==0) 
      }//if(lastRead==0) 
     }//if(digitalRead(18)==TRUE) 
     else { 
      lastRead = 0;//ready to read new pulse 
     }//else 
    }//while 
}//main() 
+1

你對空白過敏嗎? – 2015-03-31 00:59:08

+0

這是正確的。它已經減損了我生命中的歲月,因爲當太靠近空間,標籤和返回時,我的指尖燃燒。 – 2015-03-31 01:16:26

+0

將輻射源移入客廳,展現了對隨機數字生成黑色藝術的全新承諾。 – 2015-03-31 01:31:25

回答

9

默認情況下,stdout的輸出在寫入終端時被行緩衝。這意味着輸出將保存在內存中,直到您打印換行符或致電fflush(stdout)(或輸出緩衝區填滿 - 通常爲4K或8K字符)。

因此,將fflush(stdout)放在您想要顯示累計輸出的地方。或者使用setbuf(stdout, NULL)來完全禁用緩衝。

+0

感謝您的快速,有益的迴應!我在程序開始時禁用了緩衝區,現在看起來工作正常。 – 2015-03-31 01:09:26

+0

好迴應,並且簡短!!!做得好。 – 2015-03-31 09:58:15