arraiz
Hello first want to tell that I think OpenPLC is a great tool to learn about "OT" Hardware and communications and very easy to set up, so keep going!.

Recently I have purchased a DS18B20 temperature sensor it works via OneWire protocol as a digital input. I am just wondering if it is posible to get it to work with OpenPLC running on my Raspberry PI, and make a silly program that turns a led to high when certain value is raised (for example).

Thanks is advance!
arraiz
Okay now I see the log

OpenPLC Runtime starting...
Interactive Server: Listening on port 43628
Device: 28-0300a279ac61
Device: 28-0300a279ac61  - Temp: 25.562 C  78.012 F
Warning: Persistent Storage file not found
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
Device: 28-0300a279ac61  - Temp: 25.562 C  78.012 F
Device: 28-0300a279ac61  - Temp: 25.562 C  78.012 F
Device: 28-0300a279ac61  - Temp: 25.500 C  77.900 F
Device: 28-0300a279ac61  - Temp: 25.437 C  77.787 F
Device: 28-0300a279ac61  - Temp: 25.500 C  77.900 F
Device: 28-0300a279ac61  - Temp: 25.437 C  77.787 F
Device: 28-0300a279ac61  - Temp: 25.437 C  77.787 F
Device: 28-0300a279ac61  - Temp: 25.375 C  77.675 F
Device: 28-0300a279ac61  - Temp: 25.375 C  77.675 F


The temperature is correct in the logs (the tempC temperature if fine) but at the monitor theres no change...
Thanks in advance...
Reply 0 0
thiagoralves
Ah, now I saw the issue. The original code divides the temperature by 1000, and I'm not doing that. That's why you are getting this crazy number. This code fixes that. Keep in mind that the number you will see is the temperature in C times 100 (so to keep at least 2 decimal digits. This means that 25.437 C = 2543
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
//-----------------------------------------------------------------------------
// DISCLAIMER: EDDITING THIS FILE CAN BREAK YOUR OPENPLC RUNTIME! IF YOU DON'T
// KNOW WHAT YOU'RE DOING, JUST DON'T DO IT. EDIT AT YOUR OWN RISK.
//
// PS: You can always restore original functionality if you broke something
// in here by clicking on the "Restore Original Code" button above.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// These are the ignored I/O vectors. If you want to override how OpenPLC
// handles a particular input or output, you must put them in the ignored
// vectors. For example, if you want to override %IX0.5, %IX0.6 and %IW3
// your vectors must be:
//     int ignored_bool_inputs[] = {5, 6}; //%IX0.5 and %IX0.6 ignored
//     int ignored_int_inputs[] = {3}; //%IW3 ignored
//
// Every I/O on the ignored vectors will be skipped by OpenPLC hardware layer
//-----------------------------------------------------------------------------
int ignored_bool_inputs[] = {2}; //sensor is connected to pin %IX0.2 so we need to disable it
int ignored_bool_outputs[] = {-1};
int ignored_int_inputs[] = {0}; //we are writing 1-wire sensor readings to %IW0
int ignored_int_outputs[] = {-1};
char devPath[128];
char dev[16];
//-----------------------------------------------------------------------------
// This function is called by the main OpenPLC routine when it is initializing.
// Hardware initialization procedures for your custom layer should be here.
//-----------------------------------------------------------------------------
void initCustomLayer()
{
    unsigned char log_msg[1000];
    DIR *dir;
    struct dirent *dirent;
    char path[] = "/sys/bus/w1/devices";
    dir = opendir(path);
    if (dir != NULL)
    {
        while ((dirent = readdir(dir)))
            // 1-wire devices are links beginning with 28-
            if (dirent->d_type == DT_LNK && strstr(dirent->d_name, "28-") != NULL)
            {
                strcpy(dev, dirent->d_name);
                sprintf(log_msg, "\nDevice: %s\n", dev);
                log(log_msg);
            }
        (void)closedir(dir);
    }
    else
    {
        sprintf(log_msg, "Couldn't open the w1 devices directory\n");
        log(log_msg);
    }
    // Assemble path to OneWire device
    sprintf(devPath, "%s/%s/w1_slave", path, dev);
}
//-----------------------------------------------------------------------------
// This function is called by OpenPLC in a loop. Here the internal input
// buffers must be updated with the values you want. Make sure to use the mutex 
// bufferLock to protect access to the buffers on a threaded environment.
//-----------------------------------------------------------------------------
void updateCustomIn()
{
    // Example Code - Overwritting %IW3 with a fixed value
    // If you want to have %IW3 constantly reading a fixed value (for example, 53)
    // you must add %IW3 to the ignored vectors above, and then just insert this 
    // single line of code in this function:
    //     if (int_input[3] != NULL) *int_input[3] = 53;
    unsigned char log_msg[1000];
    char tmpData[6];
    ssize_t numRead;
    char buf[256];
    int fd = open(devPath, O_RDONLY);
    if (fd == -1)
    {
        sprintf(log_msg, "Couldn't open the w1 device\n");
        log(log_msg);
    }
    while ((numRead = read(fd, buf, 256)) > 0)
    {
        strncpy(tmpData, strstr(buf, "t=") + 2, 5);
        float tempC = strtof(tmpData, NULL);
    
        //save value in OpenPLC buffer
        if (int_input[0] != NULL) *int_input[0] = (uint16_t)(tempC / 10);
        
        //print values in Dashboard
        //sprintf(log_msg, "Device: %s  - Temp: %.3f C  %.3f F\n\n", dev, (tempC / 1000), (tempC / 1000) * 9 / 5 + 32));
        //log(log_msg);
    }
    close(fd);
}
//-----------------------------------------------------------------------------
// This function is called by OpenPLC in a loop. Here the internal output
// buffers must be updated with the values you want. Make sure to use the mutex 
// bufferLock to protect access to the buffers on a threaded environment.
//-----------------------------------------------------------------------------
void updateCustomOut()
{
    // Example Code - Sending %QW5 value over I2C
    // If you want to have %QW5 output to be sent over I2C instead of the
    // traditional output for your board, all you have to do is, first add
    // %QW5 to the ignored vectors, and then define a send_over_i2c()
    // function for your platform. Finally you can call send_over_i2c() to 
    // send your %QW5 value, like this:
    //     if (int_output[5] != NULL) send_over_i2c(*int_output[5]);
    //
    // Important observation: If your I2C pins are used by OpenPLC I/Os, you
    // must also add those I/Os to the ignored vectors, otherwise OpenPLC
    // will try to control your I2C pins and your I2C message won't work.
}
Reply 0 0
arraiz
Whoa, thanks now works perfectly, really looking forward to learn some good C and PLC basics, thanks!!
Reply 0 0
SETL
Hello, thank you for this. 
I want to connect also DS18B20 to Raspberry pi 4 or ESP8266 but i still don't know how... What i understood, Raspberry with OpenPLC_3 Runtime HW layer, we must add code from thiagoralves  to HWLCB two post UP  in this topic and Save. After this with running program on %IW0 we will be have AI from DS18B20 what is connected to raspberry pi 7 pin. DS18B20 must be connected with resistor 4,7 or 10 Kohm ? If this it's working, what we need to do for DS18B20 working with Slave ESP8266 connected (how to update HWL?). Its possible connect more DS18B20 to ESP8266 his DI to simulate AI from temp sensor ? How its this possible.  I put this chode to HWLCB and successfully save. After run program I have this error:  save.jpg 
thank you. 
Reply 0 0
thiagoralves
This means that the HWLCB driver can't reach your DS18B20 sensor. Make sure you wired it up properly and check if you have enabled 1-Wire protocol on raspi-config:
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-11-ds18b20-temperature-sensing/hardware
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-11-ds18b20-temperature-sensing/ds18b20
Reply 0 0
SETL
Thank you, now it's working LOG its display actual temp.  But in OpenPLC Monitor its not update value, still 0 or one value. In ScadaBR i can on IW0 read a correct value, but only one times, its not updating. After first update scadaBR shows "17:34:38: '11': No response from slave 1" 

How can I repair Modbus connection to ScadaBR. 
//Update: i find solutions put two lines UP to while LOOP
2.jpg 


Second Q. It's possible to connect DS18B20 to ESP8266 SLAVE, to some way like now to raspberry?
Reply 0 0
thiagoralves
Throwing a pthread unlock right there is a dangerous move, it might eventually lock up everything since the unlock is being called without a proper lock. The reason for the lack of response on the Modbus might be that this while loop is taking too long to complete. I don't have a DS sensor to investigate this, but moving portions of the code to a separate space might be a good idea. I believe having the readings running on a separate thread is the perfect scenario.

About your ESP8266 question, yes that is totally possible, but it will require you to modify the firmware for the ESP8266 to be able to read the DS sensor and put the values in a modbus register
Reply 0 0
gwosmek
i am also trying to read multiple DS18B20 Sensors without luck. i used the code that someone had posted earlier in the thread with a few modifications to it. it seems to crash the whole thing when i uncomment the second half of the code. 


#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
//-----------------------------------------------------------------------------
// DISCLAIMER: EDDITING THIS FILE CAN BREAK YOUR OPENPLC RUNTIME! IF YOU DON'T
// KNOW WHAT YOU'RE DOING, JUST DON'T DO IT. EDIT AT YOUR OWN RISK.
//
// PS: You can always restore original functionality if you broke something
// in here by clicking on the "Restore Original Code" button above.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// These are the ignored I/O vectors. If you want to override how OpenPLC
// handles a particular input or output, you must put them in the ignored
// vectors. For example, if you want to override %IX0.5, %IX0.6 and %IW3
// your vectors must be:
// int ignored_bool_inputs[] = {5, 6}; //%IX0.5 and %IX0.6 ignored
// int ignored_int_inputs[] = {3}; //%IW3 ignored
//
// Every I/O on the ignored vectors will be skipped by OpenPLC hardware layer
//-----------------------------------------------------------------------------
int ignored_bool_inputs[] = {2}; //sensor is connected to pin %IX0.2 so we need to disable it
int ignored_bool_outputs[] = {-1};
int ignored_int_inputs[] = {1,3}; //we are writing 1-wire sensor readings to %IW0
int ignored_int_outputs[] = {-1};
char devPath0[128];
char devPath3[128];
char dev0[16];
char dev3[16];
//-----------------------------------------------------------------------------
// This function is called by the main OpenPLC routine when it is initializing.
// Hardware initialization procedures for your custom layer should be here.
//-----------------------------------------------------------------------------
void initCustomLayer()
{
unsigned char log_msg[1000];
DIR *dir0;
DIR *dir3;
struct dirent *dirent0;
struct dirent *dirent3;
char path[] = "/sys/bus/w1/devices";
dir0 = opendir(path);
dir3 = opendir(path);
//FIRST ANALOG SENSOR
if (dir0 != NULL)
{
while ((dirent0 = readdir(dir0)))
// 1-wire devices are links beginning with 28-
if (dirent0->d_type == DT_LNK && strstr(dirent0->d_name, "28-0300a279cec7") != NULL)
{
strcpy(dev0, dirent0->d_name);
sprintf(log_msg, "\nDevice: %s\n\n", dev0);
log(log_msg);
}
(void)closedir(dir0);
}
else
{
sprintf(log_msg, "Couldn't open the w1 devices directory\n");
log(log_msg);
}

//SECOND ANALOG SENSOR

if (dir3 != NULL)
{
while ((dirent3 = readdir(dir3)))
// 1-wire devices are links beginning with 28-
if (dirent3->d_type == DT_LNK && strstr(dirent3->d_name, "28-0300a2790f14") != NULL)
{
strcpy(dev3, dirent3->d_name);
sprintf(log_msg, "\nDevice: %s\n\n", dev3);
log(log_msg);
}
(void)closedir(dir3);
}
else
{
sprintf(log_msg, "Couldn't open the w1 devices directory\n");
log(log_msg);
}
// Assemble path to OneWire device
sprintf(devPath0, "%s/%s/w1_slave", path, dev0);
sprintf(devPath3, "%s/%s/w1_slave", path, dev3);
}
//-----------------------------------------------------------------------------
// This function is called by OpenPLC in a loop. Here the internal input
// buffers must be updated with the values you want. Make sure to use the mutex
// bufferLock to protect access to the buffers on a threaded environment.
//-----------------------------------------------------------------------------
void updateCustomIn()
{
// Example Code - Overwritting %IW3 with a fixed value
// If you want to have %IW3 constantly reading a fixed value (for example, 53)
// you must add %IW3 to the ignored vectors above, and then just insert this
// single line of code in this function:
// if (int_input[3] != NULL) *int_input[3] = 53;
unsigned char log_msg[1000];
char tmpData0[6];
char tmpData3[6];
ssize_t numRead0;
ssize_t numRead3;
char buf0[256];
char buf3[256];
int fd0 = open(devPath0, O_RDONLY);
int fd3 = open(devPath3, O_RDONLY);

if (fd0 == -1)
{
sprintf(log_msg, "Couldn't open the w1 device\n");
log(log_msg);
}
while ((numRead0 = read(fd0, buf0, 256)) > 0)
{
strncpy(tmpData0, strstr(buf0, "t=") + 2, 5);
float tempC = strtof(tmpData0, NULL);
float tempF = (tempC / 1000) * 9 / 5 + 32;
//save value in OpenPLC buffer
//if (int_input[0] != NULL) *int_input[0] = (uint16_t)(tempC / 10);
if (int_input[1] != NULL) *int_input[1] = (uint16_t)(tempF * 100);

//print values in Dashboard
//sprintf(log_msg, "Device: %s - Temp: %.3f F\n\n", dev0, tempF0);
//log(log_msg);
}
close(fd0);

//SECOND ANALOG SENSOR

if (fd3 == -1)
{
sprintf(log_msg, "Couldn't open the w1 device\n");
log(log_msg);
}
while ((numRead3 = read(fd3, buf3, 256)) > 0)
{
strncpy(tmpData3, strstr(buf3, "t=") + 2, 5);
float tempC = strtof(tmpData3, NULL);
float tempF = (tempC / 1000) * 9 / 5 + 32;
//**save value in OpenPLC buffer
//**if (int_input[0] != NULL) *int_input[0] = (uint16_t)(tempC / 10);
if (int_input[3] != NULL) *int_input[3] = (uint16_t)(tempF * 100);

//**print values in Dashboard
//**sprintf(log_msg, "Device: %s - Temp: %.3f F\n\n", dev3, tempF3);
//**log(log_msg);
}
close(fd3);
}
//-----------------------------------------------------------------------------
// This function is called by OpenPLC in a loop. Here the internal output
// buffers must be updated with the values you want. Make sure to use the mutex
// bufferLock to protect access to the buffers on a threaded environment.
//-----------------------------------------------------------------------------
void updateCustomOut()
{
// Example Code - Sending %QW5 value over I2C
// If you want to have %QW5 output to be sent over I2C instead of the
// traditional output for your board, all you have to do is, first add
// %QW5 to the ignored vectors, and then define a send_over_i2c()
// function for your platform. Finally you can call send_over_i2c() to
// send your %QW5 value, like this:
// if (int_output[5] != NULL) send_over_i2c(*int_output[5]);
//
// Important observation: If your I2C pins are used by OpenPLC I/Os, you
// must also add those I/Os to the ignored vectors, otherwise OpenPLC
// will try to control your I2C pins and your I2C message won't work.
}
Reply 0 0
NWT.Stuff

Strong Recommendation here. Move your Temperature Sensor Bus to an Arduino USB Drop from RPI (I use Arduino UNO).  Use the arduino library https://www.arduinolibraries.info/libraries/dallas-temperature and you should be pretty much away. 🙂

NOTE: There is an error in my terminology in the drawing. It is actually a digital input providing several analogue values 🙂


Attached Architecture Drawing. Kevin 

Reply 0 0
gwosmek
Here is the Method that i would like to do to read from DS18B20 Sensors:

Python Script running at startup doing the following:

import os
import glob
import time

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28-0300a279cec7')[0]
device_file = device_folder + '/w1_slave'
Text_to_Write = ' '

def read_temp_raw():
   f = open(device_file, 'r')
   lines = f.readlines()
   f.close()
   return lines

def read_temp():
   lines = read_temp_raw()
   while lines[0].strip()[-3:] != 'YES':
   time.sleep(0.1)
   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_f

while True:
   Text_to_Write = read_temp()
   #//print('calculated Temp',Text_to_Write)
   f = open("TempSensor1.txt", "w")
   f.write(repr(Text_to_Write) + '\n')
   f.close()
   time.sleep(2)

This Should create a file named TempSensor1.txt that is in the root Directory of the Raspberry Pi.
The contents of the File will be the Temperature in Deg F i can do with or without a return/newline at the end of the file (72.954 \n) vs (72.954)
This File will update every 2 seconds per the time.sleep() setting in Python Code. 


I would like the hardware layer code to read the file contents and move the value to %IW0.
I will repeat this for the rest of the sensors. 

if (int_input[0] != NULL) *int_input[0] = "FILE CONTENTS"


The Reason for doing it this way is because i tried the method in the thread and it seems to hang the hardware layer up really bad after adding more sensors. i would like to keep the OPENPLC side of things as simple and easy to execute as possible. And i gain the ability to have the update rate of the sensor data independent of the Scan time and hardware layer update rate.


any help is appreciated. 

Reply 0 0
thiagoralves

This method has some caveats if you’re running it on a Pi. Opening and closing files on an SD card is bad. Eventually it will destroy your card. Ideally you should create this file on a ramdisk to avoid wearing off your SD card.

In any case, I can’t avoid to think it is stupid to add this much complexity using a python script middleware just to read a couple sensors. It seems that your problem is that the code is taking too long to read the sensors and therefore is hanging OpenPLC main thread. Well, the solution is dead simple: just put the code to read the sensors in a separate, parallel thread. The code for this is also super simple:

On the init function in the HWLCB you create your thread and tie it to the read_sensors() function

pthread_t sensor_thread;
pthread_create(&sensor_thread, NULL, read_sensors, NULL);


Then you create the read_sensors function and place your code to read the sensors in there. The only difference is that instead of reading the values straight into OpenPLC’s *int_buffer[] you actually will read it into a temporary array, for example my_readings[].
void *read_sensors(void *args)
{
    uint16_t my_readings[10]; //10 or how many more sensors you want to read
    //initialize your sensors (file access, etc)
    while(1)
    {
        //read sensors into my_readings[]
    }
}


Then on the regular update input buffers function, instead of reading from the sensors, just read from my_readings, like:
if (int_input[0] != NULL) *int_input[0] = my_readings[0];

 

Reply 0 0
Reply