【发布时间】:2015-03-31 00:47:10
【问题描述】:
我目前正在我的 Raspberry Pi 计算机上运行一段 C 代码。它是一个随机数生成器,从连接到 GPIO 数字输入 18 的盖革计数器读取。它生成随机位(参见代码)并以 8 个为一组打印位。此外,每 30 秒,它会打印当前观察到的辐射水平.代码似乎工作正常,除非辐射源被拿走。随机数的生成速度较慢,但似乎也减慢了其余任务的速度。程序开始时打印的消息在生成一个随机数之前不会显示。发生这种情况时,不会显示数字,但会添加一个没有数字的换行符。即使在程序运行时,辐射水平也会每 30 秒打印一次,而且还会显示在下一个随机数上。为什么 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()
【问题讨论】:
-
你对空格过敏吗?
-
没错。它使我的生活减损了很多年,因为我的指尖在太靠近空间、标签和返回时会燃烧。
-
将辐射源移入您的客厅展示了对随机数生成黑艺术的全新承诺。
-
我只是喜欢它给我的内在温暖、无形的光芒。
-
@GrahamHepworð,只需使用
fflush(stdout);完成您的 printf。由于您没有在\n中完成输出,并且 stdio 通过缓冲输出工作,因此您会遇到这些延迟。 fflush(3) 将在您调用它时完成实际输出的工作。
标签: c linux raspberry-pi