Adding new i2c sensors

Posted on
Thu Mar 09, 2017 1:53 pm
andarv offline
Posts: 126
Joined: Jun 28, 2015
Location: Stockholm, Sweden

Adding new i2c sensors

Hi Karl,

I have bought a few different i2c sensors that aren't currently supported by the plugin. My question is if its possible to add them manually in the plugin files? This way others could contribute to the database of sensors.
This one has address 40
This (I think) is the sensor I'm currently trying to add. https://github.com/elechouse/SHT21_Arduino

Anders

Posted on
Fri Mar 10, 2017 12:19 am
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

You could try the module mysensor.py
And add a device with type mysensor

But that requires that you have to do the i2c communication yourself.

I will look at the description. And see if I can do that remotely without having it.




Sent from my iPhone using Tapatalk

Posted on
Fri Mar 10, 2017 12:36 am
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

actually here is a nice source for python on the RPI.
https://github.com/jsilence/python-i2c-sensors/blob/master/sht21.py.. should take me 1-2 hours to put it in, but as I don't have the sensor, I can not test it.. are you ok to test it?

would be nice to do an interactive session (team viewer) after i have a version 0.

Karl

Posted on
Fri Mar 10, 2017 1:16 am
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

https://www.dropbox.com/s/rw9p3cazcsdqtsu/piBeacon-v-7-42-63.zip?dl=1

this version should work.. but as I said, have not tested it.. it has still some debug statements in there..

1. add the sensor to the RPI
2. check its i2c number
3. add device type=pibeacon model=i2cSHT21 sensor select the RPI, put in I2c #... temp/ hum ... offsets ...

rest """"should"""" work ...

Karl

Posted on
Fri Mar 10, 2017 3:07 pm
andarv offline
Posts: 126
Joined: Jun 28, 2015
Location: Stockholm, Sweden

Re: Adding new i2c sensors

Thank you Karl, that was fast.

I just installed one and it works, displays both temp and hum in state.
Code: Select all
sensor input  pi1; data {u'i2cTCS34725': {u'35706789': {u'blue': 38, u'lux': 31, u'clear': 182, u'colorTemp': 2177, u'green': 56, u'red': 90}}, u'i2cSHT21': {u'966937994': {u'hum': u'37.0', u'temp': u'22.1'}}}

Of course we can do a teamviewer session. I'm in GMT+1 timezone and usually I can find some time in the evenings.

Anders

Posted on
Fri Mar 10, 2017 4:49 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

wow , works without testing.. thats a first ..


so I guess we don't need a session..

i have added a function that allows to add your own program in a simple way.


1. add an indigo device type myprogram, set "freeParameter" to e.g. the i2c number.
Screen Shot 2017-03-10 at 16.33.16.png
Screen Shot 2017-03-10 at 16.33.16.png (67.28 KiB) Viewed 3712 times

2. then on the RPI the file in ~/pibeaco/: cp renameMeTo_myprogram.py myprogram.py and edit it with e.g. nano
here an example code included that should do your SHT21 sensor
Code: Select all
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# by Karl Wachs
# march 10 2017
# example program to get data to indigo through myprogram
#
#
import sys
import os
import time
import json
import datetime
import subprocess
import copy
import smbus

sys.path.append(os.getcwd())
import  piBeaconUtils   as U
import  piBeaconGlobals as G
G.program = "myprogram"

# ===========================================================================
# utils do not change
#  ===========================================================================


def readParams():
    inp,inpRaw = U.doRead()
    if inp == "": return
    try:
        if "debugRPI"           in inp:  G.debug=             int(inp["debugRPI"]["debugRPImystuff"])
    except:
        pass


### example how to read sensor and send it back to getsensorvalues
# ===========================================================================
# SHT21
# ===========================================================================
class SHT21:
    """Class to read temperature and humidity from SHT21.
      Ressources:
      http://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/Humidity/Sensirion_Humidity_SHT21_Datasheet_V3.pdf
      https://github.com/jaques/sht21_python/blob/master/sht21.py
      Martin Steppuhn's code from http://www.emsystech.de/raspi-sht21"""

    def __init__(self, i2cAdd):
        self._I2C_ADDRESS = i2cAdd
        self._SOFTRESET   = 0xFE
        self._TRIGGER_TEMPERATURE_NO_HOLD = 0xF3
        self._TRIGGER_HUMIDITY_NO_HOLD = 0xF5
        """According to the datasheet the soft reset takes less than 15 ms."""
        self.bus = smbus.SMBus(1)
        self.bus.write_byte(self._I2C_ADDRESS, self._SOFTRESET)
        time.sleep(0.015)

    def read_temperature(self):   
        """Reads the temperature from the sensor.  Not that this call blocks
        for 250ms to allow the sensor to return the data"""
        data = []
        self.bus.write_byte(self._I2C_ADDRESS, self._TRIGGER_TEMPERATURE_NO_HOLD)
        time.sleep(0.250)
        data.append(self.bus.read_byte(self._I2C_ADDRESS))
        data.append(self.bus.read_byte(self._I2C_ADDRESS))
        """This function reads the first two bytes of data and
        returns the temperature in C by using the following function:
        T = =46.82 + (172.72 * (ST/2^16))
        where ST is the value from the sensor
        """
        unadjusted = (data[0] << 8) + data[1]
        unadjusted *= 175.72
        unadjusted /= 1 << 16 # divide by 2^16
        unadjusted -= 46.85
        return unadjusted
       

    def read_humidity(self):   
        """Reads the humidity from the sensor.  Not that this call blocks
        for 250ms to allow the sensor to return the data"""
        data = []
        self.bus.write_byte(self._I2C_ADDRESS, self._TRIGGER_HUMIDITY_NO_HOLD)
        time.sleep(0.250)
        data.append(self.bus.read_byte(self._I2C_ADDRESS))
        data.append(self.bus.read_byte(self._I2C_ADDRESS))
        """This function reads the first two bytes of data and returns
        the relative humidity in percent by using the following function:
        RH = -6 + (125 * (SRH / 2 ^16))
        where SRH is the value read from the sensor
        """
        unadjusted = (data[0] << 8) + data[1]
        unadjusted *= 125
        unadjusted /= 1 << 16 # divide by 2^16
        unadjusted -= 6
        return unadjusted

def getSHT21(i2c=0):
        global cAddress
        global sensorSHT21, SHT21started
        t,h ="",""

        i2cAdd = 0x40
        if i2c != 0 :
            i2cAdd = int(i2c)

        try:
            ii= SHT21started
        except:   
            SHT21started=1
            sensorSHT21 ={}

        if str(i2cAdd) not in sensorSHT21:
            sensorSHT21[str(i2cAdd)]= SHT21(i2cAdd=i2cAdd)

        try:
            t =("%5.1f"%float(sensorSHT21[str(i2cAdd)].read_temperature())).strip()
            h =("%3d"%sensorSHT21[str(i2cAdd)].read_humidity()).strip()
            return t,h
        except  Exception, e:
                U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
                U.toLog(-1, u"return  value: t="+ unicode(t)+";  h="+ unicode(h)  )
                U.toLog(-1, u"i2c address used: "+ unicode(i2cAdd) )
        return "",""   




####################### main start ###############

readParams()

# ===========================================================================
# Main, should wong ok as is
# ===========================================================================

###
###  do not use PRINT !!! any  sys out stuff goes as return message to the calling program
###


readParams()           # get parameters send from indigo
U.toLog(-1,"input params: " +unicode(sys.argv))
   
try:
    params = sys.argv[1]
    params = json.loads(params)
except  Exception, e :
    U.toLog (-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
    params ={"devId":"","freeParameter":""}
deviceID      = params["devId"]
freeParameter = params["freeParameter"]


# assuming freeParameter is the i2c number:
##  t,h =getSHT21(i2c=int(freeParameter))  ## remove the ## at the beginning of the line
#set dummy variables, delete when above works
t=55
h=33
   
returnMessage = {"INPUT_0":t,"INPUT_1":h,"INPUT_2":55,"INPUT_3":10,"INPUT_9":"abc"}
sys.stdout.write(json.dumps(returnMessage))

# you find the logoutput in /var/log/myprogram.log, if U.toLog(1 > debug setting
U.toLog(1, u"returning message:"+ json.dumps(returnMessage))
   
sys.exit(0)       



this will (if your remove the "## " infront of t,h =getS...) populate INPUT_) and INPUT_1 states in the device you setup in step1
Screen Shot 2017-03-10 at 16.45.23.png
Screen Shot 2017-03-10 at 16.45.23.png (50.64 KiB) Viewed 3712 times

I will post that plugin version later tonight.


Karl

Posted on
Sun Mar 12, 2017 3:14 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

Andvar,
I got a SHT21 sensor and I can't get mine to work. I can read one byte but trying to read more I get a read error.
Could you confirm that your works? if yes I will return mine,

Karl

Posted on
Sun Mar 12, 2017 3:39 pm
andarv offline
Posts: 126
Joined: Jun 28, 2015
Location: Stockholm, Sweden

Re: Adding new i2c sensors

I read parts of your previous post but haven't had time this weekend to try it out. Will definitely do it later.

Regarding the sht 21, funny enough it works fine for me. Haven't checked the accuracy of the sensor yet but it reports.

Attached some screenshot from domoPad (can't access my mac right now).
All my sensors from that rPi stopped reporting at 11mars 22.30 but that is another issue.


Screenshot_20170312-223715.png
Screenshot_20170312-223715.png (65.8 KiB) Viewed 3647 times
Screenshot_20170312-222107.png
Screenshot_20170312-222107.png (40.19 KiB) Viewed 3647 times
Screenshot_20170312-222051.png
Screenshot_20170312-222051.png (67.38 KiB) Viewed 3647 times

Screenshot_20170312-222042.png
Screenshot_20170312-222042.png (95.78 KiB) Viewed 3647 times

Posted on
Sun Mar 12, 2017 3:56 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Adding new i2c sensors

looks good, what was the other sensor you bought?

I returned the sensor.. thats where amazon prime is good.. takes 5 minutes..
and I ordered a new one on eBay from china for $2.30 incl shipping.. still don't understand how they make money on that .. but it will take 3 weeks


Karl

ps there is an error in the error handling.. I copied from the BME280 and it has a variable p it wants to print when there is an error but no pressure is defined ..
will post an updated version


at line ~ 120
U.toLog(-1, u"return value: t="+ unicode(t)+"; p=" + unicode(p)+"; h="+ unicode(h) )
should be
U.toLog(-1, u"return value: t="+ unicode(t)+"; h="+ unicode(h) )

Posted on
Mon Mar 13, 2017 2:43 pm
andarv offline
Posts: 126
Joined: Jun 28, 2015
Location: Stockholm, Sweden

Re: Adding new i2c sensors

I'm sorry the pics was so large, I was on the run.

This sensor was the first unsupported.

Others arriving that I haven't checked compatibility for:
LCD1602 - LCD display
LM75A - not sure what I'll use this one for, the accuracy is +-2 deg and it has no other selling point.
AM2320 - Have high hopes for this one, it's cheap and accurate and I like i2c interface.
APDS-9960 - Is a swipe (and RGB) sensor, that one is a longshoot but getting it to work would be really cool. On the bedstand setting the house to do different things depending on a swipe :)

Otherwise I have tried with mostly good result.
BMP280 -
TSL2561 - It was the first sensor I tried, but had some troubles getting stable values?
TCS34725 - Will control all of my awnings this summer.
DS18B20
DHT 22
HC-SR501 - Have just installed this one, but haven't figured it out yet I think it's abit unreliable? Have I done something wrong?

I have ordered alot of sensors from China, given that they are so cheap i figured i could try them out before settling on a few sensor to equip all of my rPi with.
Like you I can't understand how on earth they can make any money from a sensor for 1-4 dollar including shipping...

Posted on
Mon Mar 13, 2017 4:32 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

Andarv,

looking at the devices:

LM75A: very easy:
SR501: I bought 4 and 2 did not work well., the other 2 did.
LCD1602 display... The plugin supports 5+ displays.. have not done that one.. doable.. but ~ 2 days of work.. each display is completely different and the pixel mappings are a bear.. why don't you try one of the already implemented ones..
AM2320: have python example, easy
TSL2561: mine works fine
APDS-9960: complicated... that's a good challenge, Have not found a python example and translating the Arduino codes to python . is a lot of work .. anyway ordered one

For temperature I strongly suggest to go with the BME280. very accurate and you can now get them for $3 (T+P+H)

Karl

Posted on
Mon Mar 13, 2017 5:04 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

https://www.dropbox.com/s/b7wrcfqyfjf9olf/piBeacon-v-7-43-65.zip?dl=1

this should work with the LM35A .. not tested. But no error running it.. as I don't have the sensor, no real test.

Karl

Posted on
Mon Mar 13, 2017 8:54 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

https://www.dropbox.com/s/hi2a4jn4hs7ca57/piBeacon-v7-44-65.zip?dl=1

and this one should also do the AM2320 as i2c

Karl

a pretty good comparison of all the temp/humidyt/.. sensors ==> BME280 beats them all and with ~ <$5 .. i guess thats it.
http://www.kandrsmith.org/rjs/misc/hygrometers/calib_many.html

Posted on
Tue Mar 14, 2017 1:23 am
andarv offline
Posts: 126
Joined: Jun 28, 2015
Location: Stockholm, Sweden

Re: Adding new i2c sensors

Reading that article it's clear that BME is the sensor I should order as a base sensor for all rPi.

As I said, I just ordered a lot of sensors without any real analysis.

Regarding the LCD, I'm not sure whether it will come to any use. I already have a bunch of Oled. But next winter will show if they will survive in the sub-zero temp for extended periods.

The swipe would be nice, but I had no real expectation.

Posted on
Tue Mar 14, 2017 7:59 am
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: Adding new i2c sensors

the swipe is cool .. not just the simple code is a little challenge. it is not just a simple read. one has to interpret the signals.. it will require its own section .. like the ultrasound distance device, but a bit more complicated.. looking forward to that..

anyway once you have the LM35A & AM2320 could you try them?

Karl

Who is online

Users browsing this forum: No registered users and 3 guests