照度センサー2

前回の照度センサーの読み込みを自動起動で定周期で継続させる。
/etc/rc.localでプログラムを起動しようとしたが、うまくいかない(なぜかよくわかっていない)。
代替としてcronで定周期起動を行うこととする。

rootになって、
$ crontab -e
でcronのエディタを起動し、以下を追記

/1 * * * * /home/pi/exp_photo_register/photo_register_once

書き込んで、終了させる。
上記は1分ごとにphoto_register_onceというプログラムが実行される。
photo_register_onceは前回の照度船さとは違い、cronから定期的に起動されるため、
内部にwhileループを持たない。
照度データの保存場所はマウントしたHDDにしている。

// spi_photo_register.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

#define CS 0
#define CLOCK_SPEED 2000000

#define SAMPLING_INTERVAL 60

#define PRINTLINE   printf("%s, %d\n", __FUNCTION__, __LINE__);

int spi_read_write(void);

//------------------------------
int main(void)
{
  spi_read_write();
}

//------------------------------
int spi_read_write(void)
{
  int pf;
  int ret;
  unsigned char data[2];
  unsigned short sdata[2];
  unsigned short value;

  float vf;

  struct timespec ts;
  ts.tv_sec = SAMPLING_INTERVAL;
  ts.tv_nsec = 0;

  time_t t;
  char *t_str;

  FILE *fd;
  char str[256];

PRINTLINE

  pf = wiringPiSPISetup(CS, CLOCK_SPEED);
  if(pf < 0){
    perror("Fail to wiringPiSPISetup");
    exit(1);
  }

  while(1){

    // Write and Read DAC(MCP3002) via SPI
    //
    // For MCP3002
    //
    // [send data]
    // - mode = single ended
    // - channel selection = 0
    // - bit order = MSBF (MSB first)
    // 
    // +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+
    // | x| 1|  |  |  | x| x| x| | x| x| x| x| x| x| x| x| 
    // +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+
    //         |  |  |
    //         |  |  +------ MSBF
    //         |  +--------- ODD/SIGN
    //         +------------ SGL/DIFF
    // 
    // [received data]
    // +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+
    // | x| x| x| x| x| 0|B9|B8| |B7|B7|B5|B4|B3|B2|B1|B0| 
    // +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+
    // 
    data[0] = 0b01101000;
    data[1] = 0b00000000;
    ret = wiringPiSPIDataRW(CS, data, 2);
    if(ret < 0){
      perror("Fail to wiringPiSPIDataRW");
      exit(1);
    }

    sdata[0] = (unsigned short)data[0];
    sdata[1] = (unsigned short)data[1];
    value = ((sdata[0] << 8) | sdata[1]) & 0x03FF;

    // transform degital value to voltage
    vf = value;
    vf = vf*3.3/1024;

#if 1 // date and time
    t = time(NULL);
    t_str = ctime(&t);
    t_str[strlen(t_str)-1] = '\0';
    sprintf(str, "%s => %1.6f\n", t_str, vf);
#endif

#if 1 // to store the record to a file.
    fd = fopen("/mnt/hdd1/photo_record.txt", "a");
    if(fd < 0){
      perror("Fail to open file");
      exit(1);
    }
    fprintf(fd, str);
    fclose(fd);
#endif

    nanosleep(&ts,NULL);
  }


}