我是使用linux / raspbian编程的新手,我正在尝试创建一个程序来提取Pi系统时间,并在引脚23变高时将其写入文本文件。引脚23连接到S-R锁存器,引脚24发出复位信号以复位锁存器。
我遇到的问题是它似乎没有向创建的文本文件写任何内容。该程序创建文件正常但不写任何东西。这是我的代码:
using namespace std;
FILE *f;
struct timeval curTime;
int main(int argc, char *argv[]){
char dateiname[256] = "";
int i=0;
int milli;
int seconds_in_day;
wiringPiSetupGpio();
time_t t = time(0);
struct tm * now = localtime(&t);
//Create and open file
sprintf(dateiname, "/home/raspbian/Desktop/%02d%02d%02d_%02d_%02d.txt",
now -> tm_year+1900,
now -> tm_mon+1,
now -> tm_mday,
now -> tm_hour,
now -> tm_min);
f = fopen(dateiname, "w");
//write heading to file before loop
fprintf(f, "Picture, system time\n");
//Set 23 & 24 as input/ output
pinMode(23, INPUT);
pullUpDnControl(23, PUD_DOWN);
pinMode(24, OUTPUT);
while(1){
if(digitalRead(23)){ //If 23 is high
i=i+1;
gettimeofday(&curTime, NULL);
milli = curTime.tv_usec / 1000; //Get time in milliseconds
seconds_in_day = curTime.tv_sec % 86400; //Get seconds since midnight
fprintf(f, "&d &d.%d\n", i, seconds_in_day, milli); //Write to file
//send out reset signal
digitalWrite(24, HIGH);
//pause for 1 second
delay(1000);
}
}
fclose(f);
return(0);
}
有人在这里看到任何明显的错误吗?我也在终端通过
运行程序sudo /home/raspbian/Desktop/program
退出终端窗口退出程序。感谢
答案 0 :(得分:3)
它可能会缓冲输出。在fclose
执行之前,不会写入缓冲区,这是永远不会。
如果您希望在引脚23为高电平时每秒更新一次文件,请将文件fopen
和fclose
放入循环中。如果您希望每秒添加一行,请在fflush(f);
之后添加fprintf
。
答案 1 :(得分:1)
我怀疑引脚24上的输出需要为“短”周期“高”才能使锁存器复位,然后返回“低”以准备下次需要复位锁存器。
像while( !digitalRead(23) );
这样的行会烧掉很多CPU周期,所以可能希望将一些'delay()'或yield()
放入每个循环的主体中
using namespace std;
FILE *f;
struct timeval curTime;
int main(int argc, char *argv[]){
char dateiname[256] = "";
int i=0;
int milli;
int seconds_in_day;
wiringPiSetupGpio();
time_t t = time(0);
struct tm * now = localtime(&t);
//Create and open file
sprintf(dateiname, "/home/raspbian/Desktop/%02d%02d%02d_%02d_%02d.txt",
now -> tm_year+1900,
now -> tm_mon+1,
now -> tm_mday,
now -> tm_hour,
now -> tm_min);
if( NULL == (f = fopen(dateiname, "w") )
{ // then fopen failed
perror( "fopen failed for output file");
exit(EXIT_FAILURE);
}
// implied else, fopen successful
//write heading to file before loop
fprintf(f, "Picture, system time\n");
fflush( f );
//Set 23 & 24 as input/ output
pinMode(23, INPUT);
pullUpDnControl(23, PUD_DOWN);
pinMode(24, OUTPUT);
// assure latch is reset
digitalWrite(24, LOW);
digitalWrite(24, HIGH);
digitalWrite(24, LOW);
while(1)
{
// wait while pin23 is low
while( !digitalRead(23));
// 23 is high
i=i+1;
gettimeofday(&curTime, NULL);
milli = curTime.tv_usec / 1000; //Get time in milliseconds
seconds_in_day = curTime.tv_sec % 86400; //Get seconds since midnight
fprintf(f, "&d &d.%d\n", i, seconds_in_day, milli); //Write to file
fflush( f );
// if a latch 'set' signal is received during the following
// three instructions, then could get locked into
// the while pin23 high loop
// reset latch
digitalWrite(24, HIGH);
digitalWrite(24, LOW);
// wait for pin 23 to be low
while( digitalRead(23) );
} // end while
fclose(f);
return(0);
}