Delding
Hello,
I´m just trying to get some temperature reading from the tempsensor to openPLC. Is there a step by step guide to this somewhere? Reading the temperature should be a very basic thing but it seems very hard to find a simple solution.
I have Raspberry Pi 3, Arduino Uno, tempsensor etc. Just need some info.
Thanks in advance!
Reply 0 0
thiagoralves
The DS18B20 is not a normal temperature sensor in the PLC world. Usually industrial temperature sensors would output an analog signal (voltage or current) that is related to the measured temperature. The DS18B20 is a digital sensor, which means you need to 'talk' to it to be able to read its temperature. That's why it is not straightforward to read its temperature from a PLC, unless you write a driver that does that for you under the hood.

If you are on the Raspberry Pi, you can use PSM for that. PSM allows you to write low level drivers for OpenPLC using Python, which is a very simplistic language. You can search the forum for more information on PSM, but essentially, once you've enabled PSM driver, you can grab any Python code that reads your DS18B20 sensor data, and then 'glue' that value into a PLC variable, such as %IW0.

If you are on the Arduino, then the latest version of the editor (v1.3) already has a FunctionBlock that does exactly that. Just grab the block from the list, inside the 'Arduino' category. But then you will have to upload your code directly to the Arduino board, it can no longer function as a slave device.
Reply 0 0
Delding
Thank you for fast reply! That clearifys a lot. So I also happens to have a PT100 temperature probe with four wires, is that something I could connect to the Arduino or Rapberry in a simpler way? I think I would like to go for the Rapberry as PLC and the Arduino as a slave device. 
BTW, what I am trying to do here is to build a model for controlling my cheesevat wich allready have some equipment from Delta (HMI, PLC, VFD and temperature controlller) but very poor logic. I do not want to play with the vat directly because it is in production but I would like it to be a little more intelligent.
Reply 0 0
thiagoralves
Yes, PT100 is the type of sensor a PLC can read natively. You can do that with the Arduino as a slave device, as the Raspberry Pi does not have any analog input. Just connect your PT100 to any of the analog input pins of your Arduino (check the web for the right wiring) and you should start getting your measurements right away. Remember you will have to run some math to get the actual measurement in C or F. The raw measurement is just a number from 0 to 65535 that represents the voltage read by the Arduino analog input, where 0 = 0V and 65535 = 5V. You can obtain the voltage reading using this formula:
                  5.0 * raw_reading
reading_volts =  -------------------
                       65535.0

Make sure you use REAL variables to avoid losing precision on the conversion (you will have to convert your raw_reading from UINT to REAL). Once you have the measurement in volts, then you can use the information in your PT100 datasheet to convert the voltage reading to C or F.
Reply 0 0
Delding
Thanks! Will try after some websearch. 🙏
Reply 0 0
Fuzzler
I've been testing the PSM (Python SubModule) with DS18B20 sensors in order to not need an additional slave device -just a raspberry pi 2 for now. I could post my code after work if you're still interested.
Reply 0 0
Delding
Fuzzler! That would be a great help. Still struggling with temperature reading. No success so far so a working code to start with would be very nice.
Reply 0 0
Fuzzler

you could delete a lot of this if you're only reading one DS18B20...

PS: Noticed one strange behaviour right now:  when Raspberry is powered on, PSM failes the first time... when i stop and start PLC from webpage (raspberry IP + Port 8080), everything works fine... @thiagoralves do you have any idea why?

Reply 0 0
Delding
Thanks a lot @Fuzzler ! Will dive into this. Not sure I understand everything right on, is it OK to ask questions when I get stuck?
Reply 0 0
thiagoralves
@Fuzzler you should paste your code as 
code
on the forum, otherwise important formatting rules such as tabs and spaces are removed, making it impossible to run the Python code.
Reply 0 0
Fuzzler
#                  - OpenPLC Python SubModule (PSM) -
# 
# PSM is the bridge connecting OpenPLC core to Python programs. PSM allows
# you to directly interface OpenPLC IO using Python and even write drivers 
# for expansion boards using just regular Python.
#
# PSM API is quite simple and just has a few functions. When writing your
# own programs, avoid touching on the "__main__" function as this regulates
# how PSM works on the PLC cycle. You can write your own hardware initialization
# code on hardware_init(), and your IO handling code on update_inputs() and
# update_outputs()
#
# To manipulate IOs, just use PSM calls psm.get_var([location name]) to read
# an OpenPLC location and psm.set_var([location name], [value]) to write to
# an OpenPLC location. For example:
#     psm.get_var("QX0.0")
# will read the value of %QX0.0. Also:
#     psm.set_var("IX0.0", True)
# will set %IX0.0 to true.
#
# Below you will find a simple example that uses PSM to switch OpenPLC's
# first digital input (%IX0.0) every second. Also, if the first digital
# output (%QX0.0) is true, PSM will display "QX0.0 is true" on OpenPLC's
# dashboard. Feel free to reuse this skeleton to write whatever you want.
#import all your libraries here
import psm
import time
import glob
import os
import RPi.GPIO as GPIO
#global variables
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices'
DInputs =  [17,27,22,5,6,13,19,26]
DOutputs = [18,23,24,25,12,16,20,21]
DevicePaths = []
counter = 0
connection = False
livetoggleIn = False
livetoggleOut = False
def hardware_init():
    #Insert your hardware initialization code in here
    global DInputs
    global Outputs
    global base_dir
    global Devicepaths

    # Getting file devices for all DS18B20 devices
    Devicepaths = []
    for path in glob.glob(f'{base_dir}/*/'):
        if "/28-" in path:
            DevicePaths.append(path + '/w1_slave')
    GPIO.setmode(GPIO.BCM) #BCM Mode -> GPIO number not pin number
    for x in DInputs: #setting up all inputs
        GPIO.setup(x, GPIO.IN)
    
    
    for x in DOutputs: #setting up all outputs
        GPIO.setup(x, GPIO.OUT)
    
    psm.start()
      
def general_conn():
    global counter
    global connection
    global livetoggleIn
    global livetoggleOut
    
    livetoggleIn = psm.get_var("QX0.0") #built in togglebits to check connection between PSM and PLC
    if (livetoggleOut == livetoggleIn):
        counter = counter + 1
    else:
        counter = 0
        connection = True
    if (counter > 10): # if 10 cycles no change -> connection error
        connection = False
        
    livetoggleOut = livetoggleIn #setting toggle for PLC - one side is setting its output to input value, other side (PLC) is negated
    psm.set_var("IX0.0", livetoggleOut)
def update_inputs():
    #place here your code to update inputs
    global DInputs
    global DevicePaths
    inp = "IX"
    by = 0
    bi = 1
    for x in DInputs: #updating all input bits in the order like in DInputs[] and writing them to adresses from IX0.1 up
        name = inp + str(by)+ "." + str(bi)
        a = GPIO.input(x)
        if (a and connection):
            psm.set_var(name, True)
        else:
            psm.set_var(name, False)
        
        if (bi == 7):
            by = by + 1
            bi = 0
        else:
            bi = bi + 1
    
    by = 0
    for p in DevicePaths: #reading all found DS18B20 sensors ind writing them to adresses from IW0 up
        cel = int(read_temp(p)*100) #temperature value times 100 to get more accurate values to PLC - has to be divided by 100 in PLC
        psm.set_var("IW"+str(by), cel)
        by = by + 1
 
    
def update_outputs():
    #place here your code to work on outputs
    global DOutputs
    out = "QX"
    by = 0
    bi = 1
    for x in DOutputs: #reading all Output bits from QX0.1 up and writing them in the order like in DOutputs[] to Output Pins
        name = out + str(by) + "." + str(bi)
        a = psm.get_var(name)
        if (a == True):
            GPIO.output(x, GPIO.HIGH)
        else:
            GPIO.output(x, GPIO.LOW)
        
        if (bi == 7):
            by = by + 1
            bi = 0
        else:
            bi = bi + 1
def disable_Outputs(): #writes false to all outputs
    global DOutputs
    out = "QX"
    by = 0
    bi = 1
    for x in DOutputs:
        name = out + str(by) + "." + str(bi)
        GPIO.output(x, GPIO.LOW)
        if (bi == 7):
            by = by + 1
            bi = 0
        else:
            bi = bi + 1
    
def read_temp(filepath): #read temperature values
    lines = read_temp_raw(filepath)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c #, temp_f could be returned instead of temp_c to get fahrenheit  
        
def read_temp_raw(filepath): #read raw temperature values
    f = open(filepath, 'r')
    lines = f.readlines()
    f.close()
    return lines    
if __name__ == "__main__":
    hardware_init()
    while (not psm.should_quit()):
        general_conn()
        update_inputs()
        update_outputs()
        time.sleep(1) #You can adjust the psm cycle time here
    disable_Outputs() #disable all GPIO Outputs
    GPIO.cleanup() # cleanup all GPIO 
    psm.stop()

Reply 0 0
Fuzzler

@Delding yeah sure, I try to answer your questions but I'm not quite a pro. it's my first time Python coding...

 

@thiagoralves thanks, now it looks a lot better 😅

I just tested PSM with original code and have exactly the same problem as with my code - when raspberry is powered on and PLC starts connection to PSM fails, when started manually on webpage everything works. Is there a simple possibility to delay the automatic PLC start?

Reply 0 0
thiagoralves
It is probably a bug. The automatic start might be missing the step to start up the PSM core
Reply 0 0
Fuzzler

@thiagoralves

the runtime logs indicate that the PSM is started, but connection to it fails:

 

OpenPLC Runtime starting...
Interactive Server: Listening on port 43628
PSM: Starting PSM...
Issued start_modbus() command to start on port: 502
Server: Listening on port 502
Server: waiting for new client...
Issued start_dnp3() command to start on port: 20000
DNP3 ID manager: Starting thread (0)
DNP3 ID DNP3_Server: Listening on: 0.0.0.0:20000
Issued start_enip() command to start on port: 44818
Server: Listening on port 44818
Server: waiting for new client...
Issued stop_pstorage() command
PSM: Connection to psm failed
PSM: Error connecting to psm!
PSM: PSM is disabled
Warning: Persistent Storage file not found

Reply 0 0
Reply