Read temperature with DS18B20

Raspberry PI specific forum
Rudy M
User
User
Posts: 44
Joined: Fri Aug 23, 2024 1:18 pm

Read temperature with DS18B20

Post by Rudy M »

Dear Purebasic programmers,

I was frustrated to obtain a good temperature measuring system for my home-beer-brewing system.

During several months I tested a lot of listings, not only in Purebasic but also in several other basic-like compilersystems.

A lot of the listings did not work at all, or in best case they worked but after a time the execution they stopt execution because of errors.

Most errors where file errors (file not found, could not open file, EOF errors and so on...

This is now one thing we do not will obtain in our listings for/with a temperature measuring system.

So I decide to experiment my self.

The listing I deal with You, is tested with 8000 loops, each reading 3 DB18B20 sensors, during 5,5 hours (= 24.000 times reading a DB18B20 file).
And this without obtaining no one error.

Looking forwards for Your comments (and possible tips to make the listing better...)

Greatings,
Rudy M

Code: Select all

EnableExplicit
;Measuring T is important, so always use EnableExplicit!!!
;                          ===============================                   

;This listing Read one or more DS18B20 without using PIGPIO or other libs.
;=========================================================================
;I saw a lot of listings on the internet, but lot of them did not work good or gave errors.
;Those using libs were sometimes to complicated.
;So I was very frustrated to obtain no good working T-measurement.
;So I decide to make my own listing.
;Purebasic surprised my with an (till to day!!!) errorless working T-measuring.
;So I will deal with You my listing.

;If You can make something better or efficienter, please deal it on this forum.

;Tested on RasperryPI3 Model B+ met Linux en xfce desktop: 
;Testtime: 3 ours, continue reading 3 DB18B20 sensors... Works without errors!
;I let run this listing during 5 1/2 hours with 8000 loops, each with 3 DB18B20 sensors.
;I'm very glad to announce I became:
;24000 times a reading of the DSB18B20 file without no one error!
;================================================================

;Do not forget there is always a sensor-toleration for temperature-result AND for responstime.
;So, if You use 1 DB18B20 (only 1 responstime!!!) You need to incorporate one or more delay()
;statements in Your listing to obtain no errors. In that case, You need to test it out Yourself.

;In case of program errors during runtime,
;then test again With Delay(xxx) milliseconds, see listing
;Tip: start With 25 milliseconds and increase of necessery.
;AND... test again during minimal several ours!!! (I take 3 ours as absolute minimum test time).
;Do such test again when You replace a sensor.

;=====================================Disclaimer =========================================
;                    Do all your test very carefully And punctual.
;=========================================================================================
;    With a failing temperature-control, You easely obtain very dangerous situations!
;=========================================================================================
;For all Your home made constructions: Read and follow all rules and laws of Your country.
;=========================================================================================
;P.e.: All metal parts of my home made beerboiling installations have perfect earth connections.


Define.s PathName , FullPathName,  Path_to_w1slave, sensormap
Define.s Temperature_string, content
Define.l File, start, sensornr, test, x
Define.l totalSeconds , hr, min, sec, MaxNumberSensors
Define.d Temperature
Define.q Tstart,Telapsed,Tmeetpunt 

;Full pathname of my sensor3 is:
;Path_to_w1slave = "/sys/devices/w1_bus_master1/28-3c01d60706a2/w1_slave"
;                                               xxxxxxxxxxxxxxx 
;xxxxxxxxxxxxxxx = the sensormap
; Replace white those of Your specifieke sensor(s) in the select case below.

;Tip: In Linux You can also search in terminal with "locate w1_slave" to find the path

MaxNumberSensors = 3 
;For my beerbrewing I only use 3 sensors
;1 in my beervessel, 1 in my watercooker, 1 in my plate cooler (to not spoil water...).

;Line below for testing purposes
Tstart = ElapsedMilliseconds()

;For next loop for testpurpose.
For test = 1 To 50
  
  For sensornr = 1 To MaxNumberSensors 
    
   Select sensornr 
     Case 1 
       sensormap = "28-0316a279f80d"  
     Case 2 
       sensormap = "28-0319a27920d7"
     Case 3 
       sensormap = "28-3c01d60706a2"
     Case 4 
       sensormap = "28-3c01d607bcca"
     Case 5 
       sensormap = "28-3c01d607e340"
     Default 
       sensormap = "28-0316a279f80d" ;I take sensor 1 as Default sensor (my beervessel...)
   EndSelect   
 
     FullPathName = "/sys/devices/w1_bus_master1/" + sensormap +"/w1_slave" 
  
  
     File = ReadFile(#PB_Any, FullPathName)
    ;Delay (50) 

    If File
      Repeat       
        
        Temperature = #False
        content = ReadString(File) 
        ;Delay (50)
        ;Debug content , for testpurpose
        start = FindString(Content, "t=", 1)
    
        If start > 0     
          Temperature_string = Mid(Content, start + 2, 7)     ;+2 because we do'nt need t=    
          Temperature = ValF(Temperature_string) / 1000       ; Convert to centigrade Celsius
          Temperature = Round (Temperature,#PB_Round_Nearest) ;1°C is OK for my beerbrewing installation  
          If Temperature <> #False
            Debug Temperature
            ; First possibility to store here the temp-data:
            ; P.e.: Store temperatures in a global array to use elders in Your programma.
            ; See further: "Second possibility"
          Else  
            Debug "Could not measure Temperature"
            Break    
          EndIf  
       
          Break     
          
        EndIf      
        
      Until Eof(File)       
      CloseFile(File) 
      
    Else
      
      Debug "Could not read sensor number :" +Str (sensornr)
      Debug "Could not open sensorfile: "
      Debug  FullPathName
      Break     
      ; P.E.: For safety call here a procedure,
      ; play an alarmsound, swith off all heaterelements, close all taps etc,etc...
    EndIf
    
  Next sensornr
  ;Second Possibility to call from here procedures.
  ;P.E. Switch heaterelements on or off.
  ;The outer For next loop could be p.e. a Repeat-Forever or Repeat-while and other.

Next test ;For next loop for testpurpose, see other comments.
 
;Measuring time, for tespurpose:
;Telapsed = ElapsedMilliseconds() - Tstart
;totalSeconds=Telapsed/1000
;hr = totalSeconds/3600
;min = (totalSeconds - 3600*hr) / 60
;sec = totalSeconds - 3600*hr - 60*min
;Debug Str(hr) + " uur " + Str(min) + " min " + Str(sec) + " sec"

;Other possibility to obtain data on Your screen:
;P.E.: MessageRequester("Temperature", Temp, #PB_MessageRequester_Ok)


Rudy M
User
User
Posts: 44
Joined: Fri Aug 23, 2024 1:18 pm

Re: Read temperature with DS18B20

Post by Rudy M »

Forgot this:
To obtain the mapname(s) of Yours Sensor(s)) in a Linux system:

Open a Terminal and type:
cd /sys/bus/w1/devices

In this map each sensor has his own mapname
benubi
Enthusiast
Enthusiast
Posts: 219
Joined: Tue Mar 29, 2005 4:01 pm

Re: Read temperature with DS18B20

Post by benubi »

Cool :D Do you only monitor temperatures with your RP3 or do you also steer things? I have no clue about brewing and also for now I haven't done anything crafty on my R400 except compiling a few PB programs (to see how far they are portable with some networking experiments).

Perhaps you get more accurate values with

Code: Select all

Temperature = ValD(Temperature_string) / 1000.0
I don't know if it's of any use for you but if there's an apache server already running on the system (happens some times) you might want to make a fast-cgi version so that you can access through browser via LAN, offer an XML or HTML (...) output to a monitoring app/server.

I can't test it because I don't have the sensors (and your configuration). If you encounter problems with reading and writing it might be because of file access permissions (you might give the executing user more privileges or let the root run your program so it can read the files). I am not a linux expert but perhaps you have access permissions for devices you can set for each user or group.
User_Russian
Addict
Addict
Posts: 1522
Joined: Wed Nov 12, 2008 5:01 pm
Location: Russia

Re: Read temperature with DS18B20

Post by User_Russian »

It is more reliable to read DS18B20 via serial port.
viewtopic.php?t=57705
http://purebasic.mybb.ru/viewtopic.php?id=475&p=4#p9286
Rudy M
User
User
Posts: 44
Joined: Fri Aug 23, 2024 1:18 pm

Re: Read temperature with DS18B20

Post by Rudy M »

@Benube:
Thanks for the tip for more accurate values.

At this moment I still use freebasic to put on/off heaterelements, and to put on/off the circulationpump (beerbrewing...).

I have the intention to rewrite my routines in Purebasic, but I'm still learning PB.
For that reasen I did a test with PIGPIOD (see topic on this forum).
I use the principle of to put on/off a led to do this.
Therefore I replace the LED with a type of SSR (Aliexpress) directly connected to an GPIO port.

On a raspberryPI I use an Connectorboard with leds (Aliexpress) so for testing purpose You do not need to connect an SSR to test Your procedures.

Every time I obtain a good working procedure for this, I shall publisch it on this forum.
I possible I shall also give the info and/or internet-links of the electronic parts.

@User_Russian:
This opens the possibility to use any PC to do the job (without an RaspberryPI...)
Also thanks for the electronic info.
Great!!!
Rudy M
User
User
Posts: 44
Joined: Fri Aug 23, 2024 1:18 pm

Re: Read temperature with DS18B20

Post by Rudy M »

To give an answer at the first question of Benubi:


RaspberryPI: Info of electronic devices we can use with/for our PB software:

To prevent technical info between the Purebasic info, I decided to announce, as little as possible,
the info of the devices I used with freebasic and going to use further with Purebasic.
For further details and to keep the topic clean: Please send a private message.

How to connect DS18B20
https://www.circuitbasics.com/raspberry ... -tutorial/

Screwconnectionboard
I strongly recommend a screwconnectionboard for all RaspberryPI's, specially for testing purposes.
You minimize the risk to make short-circuits (damage to Your Raspberry!!!)

The advantage for testing Your Purebasic routines is that You did not need to connect anything,
P.E. You can see the blinking led on the board.
Specially if for testing Your PB routines p.e. to open or close an SSR (pump, heater-element...).


To give an idea, two links but Temu, Aliexpress Amazone sell it also.
https://www.kiwi-electronics.com/en/gpi ... -hat-10762
https://thepihut.com/products/gpio-screw-terminal-hat

On the same board I connected also three DS18B20 temperature sensors to test my Purebasic-routine.

SSR info:
1) Be very carefully, most of Chinese SSR's announce de peak-values of their devices.
For safety reasons, I use the double or more of the announced current.
So for switching the heater of my beervessel 15 Ampère, I use a 40 Ampére SSR.
For those currents the Temp. of the SSR rises easely to 60-70°C so in that case,
2)You need an SSR who's input works from 3 Volt DC (not AC!!!) . (The tension of the GPPIO pins).
There are also universal types working at inputs between 3V and 32V both DC and AC.
Output: Take one who can switch tensions till 380 Volt (no matter Your heater works on 110V or 220V).
ALWAYS USE A BIG HEAT DISSIPATION RADIATOR!!! (I even always place a litte PC ventilator).

An idee how those SSR's and radiators "look a like" and for prices:
https://www.aliexpress.com/w/wholesale- ... elays.html

Very important for Your safety: Disclaimer for me and the forum:
Read and follow the rules of Your region / country for mounting boxes, heating devices, electrical connections, always use correct earth connections.
Not sure: Ask professional technical help.
Rudy M
User
User
Posts: 44
Joined: Fri Aug 23, 2024 1:18 pm

Re: Read temperature with DS18B20

Post by Rudy M »

Sorry Benubi,
I forgot to answer your suggestion (cfr Apache server etc.).

Thank you for your suggestion, but I use the RaspberryPi 100% as a standalone PC, not connected to wifi, no bluethooth.
That is why in this one case I use the RaspberryPi as root, which with everything that is connected to or via the Internet
is a risk.
But what you write is indeed a possibility, I have acquaintances who are C-programmers and also beer brewers. They do use an Arduino and other mini-PCs that they control via wifi from another PC.
There is even someone on the beer brewing forum who starts his beer program, and follows the process from his armchair. (Which of course also entails a risk if something goes wrong.
Your system will certainly be interesting for Purebasic programmers who, for example, create a program that wants to monitor and follow up earthquakes, follow up a fermentation process of longer duration, burglary protection, etc.

Hats off to you for having knowledge of this!

Greetings, Rudy M
User_Russian
Addict
Addict
Posts: 1522
Joined: Wed Nov 12, 2008 5:01 pm
Location: Russia

Re: Read temperature with DS18B20

Post by User_Russian »

I found an app written in PB on a brewers forum. Maybe it will be useful to someone.
https://forum.homedistiller.ru/index.php?topic=143069.0 On page 10 there is an application for Raspberry Pi.
https://forum.homedistiller.ru/index.php?topic=143557.0
Text in Russian. Use a translator.
Rudy M
User
User
Posts: 44
Joined: Fri Aug 23, 2024 1:18 pm

Re: Read temperature with DS18B20

Post by Rudy M »

@User_Russian:
Your information makes me think of another possibility to control devices, namely via the serial ports.
A usb to parallel port adapter would be the easiest solution for that in my opinion.
Both for expanding a RaspPI and for use with any other PC.
A ready-made Usb to Parallel port plug or unit would be ideal,
because not every (PB-)programmer has the electronic knowledge to make such a circuit.
Thanks for the interesting info.
With Google translate:
Ваша информация наводит меня на мысль о другой возможности управления устройствами,
а именно через последовательные порты. Я думаю, что адаптер USB-параллельный порт будет самым простым решением для этой проблемы.
Как для расширения RaspPI, так и для использования с любым другим ПК.
Готовая вилка или модуль USB-параллельного порта были бы идеальными,
потому что не каждый программист (PB) обладает электронными знаниями для создания такой схемы.
Спасибо за интересную информацию
Post Reply