Recent

Author Topic: Raspberry Pi Temperature Sensor Program  (Read 4177 times)

ipcroc

  • New Member
  • *
  • Posts: 13
Raspberry Pi Temperature Sensor Program
« on: January 06, 2016, 01:51:41 pm »
Happy new year to you all,

I have taken some time in the past week or so to develop a FPC based program to run on a Raspberry Pi 2B. The application takes temperature readings from two Dallas DS18B20  sensors and stores each reading in a Sqlite database table:

The project is working remarkably well and I hereby share the entire source code (code may be unoptimised in any for or shape):

Code: Pascal  [Select][+][-]
  1.  
  2.  
  3.     program tempsensors;
  4.  
  5.     {$mode objfpc}
  6.  
  7.     uses Classes, SysUtils, db, sqlite3ds;
  8.  
  9.     const appVersion = '0.1';
  10.  
  11.     var sl       : TStringlist;
  12.         rows     : integer;
  13.         temp     : string;
  14.         slDevs   : TStringlist; //devicesList
  15.         i        : integer;
  16.         devCount : integer;
  17.         devFile  : string;
  18.  
  19.         logOutput : string;
  20.  
  21.         dsTempLog : TSqlite3Dataset;
  22.         sqlstr  : string;
  23.  
  24.     function parseTemperature(tempStr: string):string;
  25.     {*
  26.      Function parses and returns a temperature value from the given string tempStr.
  27.      tempStr = temperature string.
  28.     *}
  29.     var
  30.         x : integer;   //index used to parse temperature value in a string.
  31.         c : integer;   //temperature reading in celsius.
  32.         f : real;      //temperature value / 1000.
  33.  
  34.     begin
  35.      result := '';
  36.  
  37.      if tempStr = '' then
  38.      exit;
  39.  
  40.      x := pos('=', tempStr) + 1;
  41.  
  42.      begin
  43.        c := strtoint(copy(tempStr,x,5));
  44.        f := c/1000;
  45.  
  46.        result := floatToStrF(f,ffFixed,2,1);
  47.      end;
  48.     end;
  49.  
  50.  
  51.     function logDateStamp:string;
  52.     var current : TDateTime;
  53.     begin
  54.      current := now;
  55.  
  56.      result := formatDateTime('YYYY/MM/DD hh:mm:ss', current);
  57.     end;
  58.  
  59.  
  60.     procedure logToTextFile(aFn, aLogdata: string);
  61.     var fh : TextFile;   //filename to log to.
  62.     begin
  63.      assignFile(fh,aFn);
  64.  
  65.      if not fileExists(aFn) then
  66.      begin
  67.        rewrite(fh);
  68.      end
  69.      else
  70.      begin
  71.        append(fh);
  72.      end;
  73.  
  74.      try
  75.        writeln(fh,aLogData);
  76.      finally
  77.        closeFile(fh)
  78.      end;
  79.     end;
  80.  
  81.     begin {begin of main program.}
  82.  
  83.     // writeln('Script started by user.');
  84.     // writeln('Hello Pascal on Raspberry Pi.');
  85.  
  86.  
  87.      //Exit this program if prescribed file does not exists:
  88.      if not fileExists('/home/pi/progs/pascal/sensorDevices.txt') then
  89.      begin
  90.        writeln('Alert: Error in opening the sensor devices descriptor file.');
  91.        exit;
  92.      end;
  93.  
  94.  
  95.      //Load into the devces stringlist a text file that contains declared sensor devices:
  96.      slDevs := TStringlist.create;
  97.  
  98.      dsTemplog := TSqlite3Dataset.create(nil);
  99.      dsTemplog.Filename   := '/home/pi/progs/pascal/templog.db';
  100.      dsTemplog.Tablename  := 'temps';
  101.      dsTemplog.PrimaryKey := 'id';
  102.  
  103.      try
  104.        slDevs.loadfromfile('/home/pi/progs/pascal/sensorDevices.txt');
  105.  
  106.        devCount := slDevs.count;
  107.  
  108.        //Declare String list that will hold conrtents of sensor device w1_slave file contents:
  109.        sl := TStringlist.create;
  110.  
  111.  
  112.        try
  113.           //Iterate through each device file name
  114.           for i := 0 to devCount-1 do
  115.           begin
  116.              logOutput := '';
  117.  
  118.              devFile := '/sys/bus/w1/devices/' + slDevs[i] + '/w1_slave';
  119.  
  120.              if not fileexists(devFile) then
  121.              begin
  122.                 writeln('Alert: Sensor device system file not found.');
  123.                 exit;
  124.              end;
  125.  
  126.              //Load fiel contents of w1_slave file to extract the temperature:
  127.              sl.loadfromfile(devFile);
  128.  
  129.              rows := sl.count;
  130.  
  131.              //Display temperature log reading if prescribed conditions are met, else display error message.
  132.              if (rows = 2) and (pos('YES', sl[0]) > 0)  then
  133.              begin
  134.                 temp := sl[1];
  135.                 writeln('Processing  device with index : [' + inttostr(i) + ']. Row count: ' + inttostr(rows));
  136.                 logOutput := logDateStamp + ',' + slDevs[i] + ',' + parseTemperature(temp);
  137.  
  138.                 writeln(logOutput);
  139.  
  140.                 try
  141.     {               sqlstr := 'insert into temps (date_log,device_id,temp) ' +
  142.                              'values ' +
  143.                              '(%f, ''%s'', %f)';
  144.     }
  145.  
  146.                    //Construct the SQL insert statement
  147.                    sqlstr := 'INSERT INTO temps ' +
  148.                              '(date_log,device_id, temp) ' +
  149.                              'VALUES '+
  150.                              '('''+logDateStamp+''','+''''+slDevs[i]+''','+''''+parseTemperature(temp)+''')';
  151.  
  152.     //               dsTemplog.sql := Format(sqlstr, [logDateStamp, slDevs[i], parseTemperature(temp)]);
  153.     //               dsTemplog.sql := Format(sqlstr, ['2016-01=03 10:00:00', slDevs[i], '28.0']);
  154.                    dsTemplog.sql := sqlstr;
  155.                    dsTemplog.ExecSql;
  156.                 except
  157.                   writeln('Alert: Error in inserting data to the DB table with sql statement:');
  158.                   writeln(sqlstr);
  159.                 end;
  160.  
  161.                 logToTextFile('/home/pi/progs/pascal/tempreadings.log',logOutput);
  162.              end
  163.              else
  164.              begin
  165.                 writeln('Alert: Temperature string not found');
  166.               end;
  167.           end;
  168.        finally
  169.           sl.free;
  170.        end;
  171.      finally
  172.        dsTemplog.free;
  173.        slDevs.free;
  174.      end;
  175.  
  176.     end.
  177.  
  178.  

I opted for FPC instead of Python which itself is virtually default on the Raspberries.

Enjoy.



Thaddy

  • Hero Member
  • *****
  • Posts: 10444
Re: Raspberry Pi Temperature Sensor Program
« Reply #1 on: January 06, 2016, 01:56:00 pm »
That's really nice!
One quick remark: don't use real, use single or double instead.

btw: real matches to double on the pi, but real is deprecated, being historically a 48 bit value.
When you ask a question that is actually answered in the documentation, you are either lazy or a moron.

ipcroc

  • New Member
  • *
  • Posts: 13
Re: Raspberry Pi Temperature Sensor Program
« Reply #2 on: January 06, 2016, 05:36:22 pm »
Thanks for the advice Thaddy, I was not aware about that.

Rayson

  • New Member
  • *
  • Posts: 10
Re: Raspberry Pi Temperature Sensor Program
« Reply #3 on: April 06, 2018, 07:33:49 pm »
Thanks ipcroc, This is exactly what I am interested in. Is additional information available - for example, schematic of the circuit, any other Pi settings that are necessary, etc.

Thanks,
Ray

ipcroc

  • New Member
  • *
  • Posts: 13
Re: Raspberry Pi Temperature Sensor Program
« Reply #4 on: April 06, 2018, 08:56:18 pm »
I do not have the original design details with me right now, suffice to say that there was no special configuration on the part of the Pascal environment.

I will have to see if I can find the schematic and advise further on that.

You may read further on my blog http://ipkwena.blogspot.co.za/2016/01/raspberry-pi-temperature-sensor.html?m=1 to learn more about the project

Regards

 

TinyPortal © 2005-2018