Problems with GPIO push button on self build emonPi

Is this an EmonPi or a self build?

You need to run the script as root. The py GPIO module requires it

This is a self built unit and i am running it as root,what i did find was to change the GPIO pins to something else and that fixed the
problem

cat /var/log/emonpilcd/emonpilcd.log
2019-03-06 18:42:10,571 INFO Starting emonPiLCD V3.0.1
2019-03-06 18:42:10,664 INFO I2C LCD DETECTED 0x27
2019-03-06 18:42:11,077 INFO SD card image build version: emonSD-30Oct18
2019-03-06 18:42:11,078 INFO Attaching push button interrupt...
2019-03-06 18:42:11,108 INFO Attaching shutdown button interrupt...
2019-03-06 18:42:11,114 INFO Connecting to redis server...
2019-03-06 18:42:11,119 INFO Connected to redis
2019-03-06 18:42:11,120 INFO Connecting to MQTT Server: 127.0.0.1 on port: 1883 with user: emonpi
2019-03-06 18:42:11,124 INFO Connected to MQTT
2019-03-06 18:43:28,877 INFO Mode button SHORT press
2019-03-06 18:43:28,878 INFO Page: 4
2019-03-06 18:43:30,375 INFO Mode button SHORT press
2019-03-06 18:43:30,376 INFO Page: 6
2019-03-06 18:43:32,713 INFO Mode button SHORT press
2019-03-06 18:43:32,714 INFO Page: 7
2019-03-06 18:43:34,051 INFO Mode button SHORT press
2019-03-06 18:43:34,052 INFO Page: 8
2019-03-06 18:43:35,564 INFO Mode button SHORT press
2019-03-06 18:43:35,565 INFO Page: 9
2019-03-06 18:43:36,477 INFO Mode button SHORT press
2019-03-06 18:43:36,478 INFO Page: 10
2019-03-06 18:43:37,791 INFO Mode button SHORT press
2019-03-06 18:43:37,792 INFO Page: 11
2019-03-06 18:43:39,076 INFO Mode button SHORT press
2019-03-06 18:43:39,077 INFO Page: 0
2019-03-06 18:43:41,314 INFO Mode button SHORT press
2019-03-06 18:43:41,315 INFO Page: 2
2019-03-06 19:37:28,340 INFO Mode button SHORT press
2019-03-06 19:37:28,341 INFO Page: 4


cd emonpi
cd lcd
nano emonPiLCD.py

my new value excluding the stars 12 , 26

Anyone having the same problem, used the bottom circuit one. Also changed the GPIO PINS.

# Set up the buttons and install handlers

# emonPi LCD push button Pin 16 GPIO 23
# Uses gpiozero library to handle short and long press https://gpiozero.readthedocs.io/en/stable/api_input.html?highlight=button
# push_btn = Button(23, pull_up=False, hold_time=5, bounce_time=0.1)
# No bounce time increases responce time but may result in switch bouncing...
logger.info("Attaching push button interrupt...")
try:
   push_btn = Button(**12**, pull_up=False, hold_time=5)
   push_btn.when_pressed = buttonPress
   push_btn.when_held = buttonPressLong
except:
   logger.error("Failed to attach LCD push button interrupt...")

logger.info("Attaching shutdown button interrupt...")
try:
   shut_btn = Button(**26**, pull_up=False, hold_time=5)
   shut_btn.when_pressed = preShutdown
   shut_btn.when_held = shutdown

Interesting, in that case I can only guess the GPIO is in use by
something else.

Glad it’s fixed.

Just a quick one struggling, with this.
Any idea how i can get it to work,only have 1 (w1_slave ) though i can see the second sensor just does not show up in the feeds only 1 shows up : Code below

#!/usr/bin/python3

import glob
import time
import paho.mqtt.publish as publish

Broker = '127.0.0.1'
auth = {
    'username': 'emonpi',
    'password': 'emonpimqtt2016',
}

pub_topic = 'emon/DS18B20/Temperature/values'

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

def read_temp():
    valid = False
    temp = 0
    with open(device_file, 'r') as f:
        for line in f:
            if line.strip()[-3:] == 'YES':
                valid = True
            temp_pos = line.find(' t=')
            if temp_pos != -1:
                temp = float(line[temp_pos + 3:]) / 1000.0

    if valid:
        return temp
    else:
        return None


while True:
    temp = read_temp()
    if temp is not None:
        publish.single(pub_topic, str(temp),
                hostname=Broker, port=1883,
                auth=auth,)
    time.sleep(6)

Auto start up

[Formated by pb66 - Please wrap code clips inbetween three backticks ( ``` ) in the line before and the line after for better readability)

essentially this script is set up for a single sensor only and you need to convert it to loop through a number of sensors.

eg this line

device_folder = glob.glob(base_dir + '28-*')[0]

defines “device_folder” as the first item in a list of one of more items returned by glob.glob(base_dir + '28-*'). So changing that variable name to a plural and removing the [0] would give you a list of sensors eg

device_folders = glob.glob(base_dir + '28-*')

then the read_temp() function needs to be called multiple times and it needs to pass the temp sensor detail eg

while True:
    for device_folder in device_folders:
        device_file = device_folder + '/w1_slave'
        temp = read_temp(device_file)
        if temp is not None:

and by editing the read_temp function like so

def read_temp(device_file):

the device_file = device_folder + '/w1_slave' line is then no longer needed so can be deleted (or commented out).

For the publishing side you will also need to change the topic for each sensor , for example you could move the pub_topic variable inside the if temp is not None:


    if temp is not None:
        pub_topic = 'emon/' + device_file + '/Temperature/values'
        publish.single(pub_topic, str(temp),
                hostname=Broker, port=1883,
                auth=auth,)

or something similar.

All untested suggestions so if it doesn’t work first go I hope it at least points you to what you need.

Thank you for your help, I really do appreciate it very much. This is how far i got with the code unfortunately i am no python expert, and its still giving me hell :slight_smile:

#!/usr/bin/python3

import glob
import time
import paho.mqtt.publish as publish

Broker = '127.0.0.1'
auth = {
    'username': 'emonpi',
    'password': 'emonpimqtt2016',
}

#pub_topic = 'emon/DS18B20/Temperature/values'


while True:
    for device_folder in device_folders:
        base_dir = '/sys/bus/w1/devices/'
        device_file = device_folder + '/w1_slave'
        temp = read_temp(device_file)
        if temp is not None:

def read_temp(device_file):
    valid = False
    temp = 0
    with open(device_file, 'r') as f:
        for line in f:
            if line.strip()[-3:] == 'YES':
                valid = True
            temp_pos = line.find(' t=')
            if temp_pos != -1:
                temp = float(line[temp_pos + 3:]) / 1000.0

    if valid:
        return temp
    else:
        return None


while True:
    temp = read_temp()
    if temp is not None:
        pub_topic = 'emon/' + device_file + '/Temperature/values'
publish.single(pub_topic, str(temp),
                hostname=Broker, port=1883,
                auth=auth,)
    time.sleep(6) 

i dont think i have the code as you intended, but i think its close

when i run it it gives me

pi@emonpi:/usr/local/bin $ python mqtt-temp
  File "mqtt-temp", line 23
    def read_temp(device_file):
    ^
IndentationError: expected an indented block

When I apply my suggestions to your original file I end up with

#!/usr/bin/python3

import glob
import time
import paho.mqtt.publish as publish

Broker = '127.0.0.1'
auth = {
    'username': 'emonpi',
    'password': 'emonpimqtt2016',
}

pub_topic = 'emon/DS18B20/Temperature/values'

base_dir = '/sys/bus/w1/devices/'
device_folders = glob.glob(base_dir + '28-*')

def read_temp(device_file):
    valid = False
    temp = 0
    with open(device_file, 'r') as f:
        for line in f:
            if line.strip()[-3:] == 'YES':
                valid = True
            temp_pos = line.find(' t=')
            if temp_pos != -1:
                temp = float(line[temp_pos + 3:]) / 1000.0

    if valid:
        return temp
    else:
        return None


while True:
    for device_folder in device_folders:
        device_file = device_folder + '/w1_slave'
        temp = read_temp(device_file)
        if temp is not None:
            pub_topic = 'emon/' + device_file + '/Temperature/values'
            publish.single(pub_topic, str(temp),
                    hostname=Broker, port=1883,
                    auth=auth,)
    time.sleep(6)

which is different to yours (and still untested by me) , but the error you see could just be a copy and paste error, Python is very strict about indentation, they must be of the same size and style (ie multiples of 4 spaces verses tabs or other multiples of spaces.) some IDE’s will edit tabs to spaces etc but if manually editing you are better to use one method throughout the code.

I also only just noted you are using Python3, I still use 2 and whilst fairly sure the code should be ok, cannot say for certain due to very little experience of using 3. Try the above and see where that gets you.I have also attached a text file version you could try so as to avoid any copy and paste errors or line endings etc, just edit the name to remove the “.txt” (needed to upload as .py files are not allowed).

mqtt-temp.py.txt (1.1 KB)

I dont get any errors. it does create allot off (sys) temp looks like from a single sensor

This is where i initially got the code from and modified it a bit.

That’s odd, all I did was remove the hardcoded “ds18b20” you originally had and replaced that with the device_folder . .

Ahhhh! no I didn’t I used device_file by accident. try changing

pub_topic = 'emon/' + device_file + '/Temperature/values'

to

pub_topic = 'emon/' + device_folder + '/Temperature/values'

although that still doesn’t explain where the input names “sys” came from or where the “temperature” name went, perhaps the extra slash in the device_file name was trowing things out???

[edit] That said, that topic still doesn’t look right to me, but I don’t use MQTT (with emoncms). could someone else confirm what the topic structure should be?

and could you confirm what sort of result you are looking for, ie one node (eg Temperatures) with multiple inputs (eg temp1 temp2 or perhaps the device ids) or are you expecting a seperate node for each device, all with a single “temperature” input?

When I have previously done this I only read all the sensors and then passed the whole lot in one chunk as CSV.

[edit2] Looking at that page you linked I can see why things are going wrong! When I do this I usually create a list of device ID’s and then use those names much like how I have suggested in your script and that device id can be dropped into the device path, much like we have done with the mqtt topic. BUT the original code creates a list of full path and file names rather than just the ids, the script needs changing again.

temp1 temp2 temp3 temp4 ect really not fussy about the label

still no change keeps on creating sys every 5s

Yeah, see post above I now understand why that’s happening. I can try and change your code, but I don’t really have the time right now (belly’s rumbling then I have to pop out) .

IMO it would probably be better to hardcode a list of sensors, that is the main reason I prefer to use Python to read temp sensors over any arduino based device, it’s easier to maintain a list of id’s and that way you are in control rather than leaving the script to just report what it finds, but either is possible.

You go fill yourself up, really do appreciate your help, thank you so much, you a star