Wednesday 30 December 2020

Set up humidity and temperature sensor on Rasp Pi

 Having just purchased a new dehumidifier, I wanted to keep a check on the humidity in the property. I have couple of Raspberry Pi's spare so decided it would be a good idea to use these along with the DHT11 sensor. The sensor can be bought reasonably cheaply.

Set up of the sensor is really simple - I bought a pack of 5 from Amazon, I don't know how accurate with regard to humidity they are, but figured once I get a few readings I can work out the ideal time to remotely switch on the dehumidifier. For me the actual humidity was not as important as to the pattern the humidity was following.

There are 3 pins out on the sensor I bought, they are marked quite clearly, main thing to remember is the pin used for the data - I went for pin number 7, or gpio pin 4. 

I wanted to make the setup as small as possible so used a Pi 0, also wanted to use up a couple of 2gb cards I've had for ages, which really are to small and slow for much now - however by using the Raspberry Pi OS lite from here I managed to get everything working on the 2gb disk, with room to spare!!

I set up using ssh

To set up python3 and pip and the adafruit_dht library I followed instruction from this page;
https://github.com/adafruit/Adafruit_Python_DHT
sudo apt update
sudo apt install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
Then install the Adafruit_DHT library
sudo pip3 install Adafruit_DHT
Now to install python3 rpi.gpio control
sudo apt install python3-dev python3-rpi.gpio
I struggled with receiving the data in a useable form until after many searches I came upon;
https://electronut.in/dht11-rpi-cloud-plot/ 
this did exactly what I required, it was easy to set up and I could view the results online from wherever I happened to be. Thank you so much for taking the time to share it.

I've changed the code slightly, you need to make sure you put the correct pin number in this line;

 RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4) Pin number is the last number here.
Also original script stopped if the internet connection went down, I've changed it so that the program sleeps for a while then rechecks again. 
I've also set the time for each reading at 10 minutes, this is shown at the sleep(600) change the number to suit your own needs

"""

dht11_thingspeak.py

Temperature/Humidity monitor using Raspberry Pi and DHT11.
Data is displayed at thingspeak.com

Author: Mahesh Venkitachalam
Website: electronut.in

"""

import sys
import RPi.GPIO as GPIO
from time import sleep  
import Adafruit_DHT
import urllib.request, urllib.error, urllib.parse

def getSensorData():
    RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4)
    # return dict
    return (str(RH), str(T))

# main() function
def main():
    # use sys.argv if needed
    if len(sys.argv) < 2:
        print('Usage: python tstest.py PRIVATE_KEY')
        exit(0)
    print('starting...')

    baseURL = 'https://api.thingspeak.com/update?api_key=%s' % sys.argv[1]

    while True:
        try:
            RH, T = getSensorData()
            f = urllib.request.urlopen(baseURL +
                                "&field1=%s&field2=%s" % (RH, T))
            print(f.read())
            f.close()
            sleep(600)
        except:
            sleep(300)
            

# call main
if __name__ == '__main__':
    main()

That is most of it set up, you need to visit Thingspeak to set up your channels there, once you've done that go back to your pi and at the command prompt do;
 sudo python3 dht11_thingspeak.py YOURWRITEAPIKEY 
As I have ssh'd in, it will stop when I close the connection, so I used the nohup to keep it alive;
 sudo nohup python3 dht11_thingspeak.py YOURWRITEAPIKEY
To ensure the sensor is almost always on, I put a line in crontab so on reboot the script starts automatically
sudo crontab -e
scroll to last line and paste
@reboot sleep 200 && nohup /usr/bin/python3 /home/pi/dht11_thingspeak.py YOURWRITEAPIKEY
I found it would only work if I put the whole address in.

You can view the results of your sensor at

https://api.thingspeak.com/channels/YOUR_CHANNEL_ID



The only snag with the original code is that it's written in Python2 which is being stopped, although I got it working, I eventually used 2to3 to convert the original code to python3. 
sudo apt install 2to3
then point at your file and 
2to3 -w my_file.py 
this will overwrite the original file.

Sunday 8 November 2020

Lirc and Mopidy for Raspberry Pi with Buster

Lirc  seems a lot easier to set up with Buster - if you are using it to control Mopidy it's a doddle to set up.

Set up is assuming you have set up Mopidy on a Raspberry Pi with Buster, you will also need to have installed mpc (sudo apt install mpc)

First of all you need to get your IR receiver, the kit here is what I've used.

To connect up to the GPIO pins there are lots of images here, I used pin 2 for 5v power, pin 6 for Ground and pin 12 (GPIO 18) for data/input. You can choose whichever pins suit, but remember which one you use for the data/input as you'll need to enter it in the conf later.

If using a similar receiver to the one in the link, the wiring is as follows, with the X on the receiver facing away from you;

Pin 1 is Ground, Pin 2 is Power and Pin 3 is Data/input.

If you have a lot of info etc on the sd card I would recommend backing up the card. 

Once you have the hardware in place and if relevant you've backed up the sd card.

Start here, ssh or open a terminal window, then;

sudo nano /boot/config.txt

Scroll down to this line, remove the # and enter the gpio pin number.

# Uncomment this to enable infrared communication.
dtoverlay=gpio-ir,gpio_pin=18
#dtoverlay=gpio-ir-tx,gpio_pin=17

ctrl x to save and close

sudo reboot

Once it's restarted

sudo apt update
sudo apt install lirc

Installation might fail on Buster here because of the .dist suffix, if so the following will help, then run the install lirc again.

sudo cp /etc/lirc/lirc_options.conf.dist /etc/lirc/lirc_options.conf
sudo apt install lirc

Once installed, open,

sudo nano /etc/lirc/lirc_options.conf

and change the following lines

driver = default
device = /dev/lirc0

ctrl + x to save and exit.

Now to set up the remote config files with the scan codes;

sudo nano ~/lircd.conf

If you are using the Keyes or similar remote you can try the codes below - if not you can either use irrecord to record your own, search sourceforge for similar brand or search google.

-------------------------

# brand:                      KEYES

# model no. of remote control:
# devices being controlled by this remote:

begin remote
  name  KEYES
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100

  header       9281  4484
  one           622  1657
  zero          622   513
  ptrail        622
  repeat       9241  2236
  pre_data_bits   16
  pre_data       0xFF
  gap          109259
  toggle_bit_mask 0x0

      begin codes
          KEY_VOLUMEUP                   0x629D
          KEY_VOLUMEDOWN                 0xA857
          KEY_PREVIOUSSONG                 0x22DD
          KEY_NEXTSONG             0xC23D
          KEY_PAUSE                 0x02FD
          KEY_1                    0x6897
          KEY_2                    0x9867
          KEY_3                    0xB04F
          KEY_4                    0x30CF
          KEY_5                    0x18E7
          KEY_6                    0x7A85
          KEY_7                    0x10EF
          KEY_8                    0x38C7
          KEY_9                    0x5AA5
          KEY_0                    0x4AB5
          KEY_SHUFFLE         0x42BD
          KEY_NUMERIC_POUND        0x52AD
      end codes

end remote
--------------------------------------------------------------------
ctrl and x to save and exit

Now replace the original lircd.conf with the new one;

sudo cp ~/lircd.conf /etc/lirc/lircd.conf

and reboot
sudo reboot

Now test the remote by using irw, type irw at the command prompt, then point and press remote buttons, with a bit of luck you'll get something similar to this.


ctrl + c to exit irw 

Hopefully you've produced a similar result to the screenshot above.

Now to instruct what each button will do, if you use my existing file as a temp measure then adapt to your own needs using mpc, you will also need to run irexec.
Open a new file;

sudo nano /home/pi/.lircrc
and paste in the following
-----------------------------------

begin        
        prog = irexec
        button = KEY_PAUSE
        config = mpc toggle
end
begin
        prog = irexec
        button = KEY_NEXTSONG
        config = mpc next
end
begin
        prog = irexec
        button = KEY_PREVIOUSSONG
        config = mpc prev
end
begin
        prog = irexec
        button = KEY_NUMERIC_POUND
        config = shutdown –h now
end
begin
        prog = irexec
        button = KEY_SHUFFLE
        config = mpc shuffle
end
begin
        prog = irexec
        button = KEY_VOLUMEUP
        config = mpc volume +10
end
begin
        prog = irexec
        button = KEY_VOLUMEDOWN
        config = mpc volume -10
end
# insert your playlist name between the " " 
begin
        prog = irexec
        button = KEY_1
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end
# insert your playlist name between the " " 
begin
        prog = irexec
        button = KEY_2
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_3
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_4
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_5
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_6
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_7
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_8
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_9
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end

begin
        prog = irexec
        button = KEY_0
        config = mpc stop; mpc clear; mpc load "Your playlist here";mpc play;
end
---------------------------
ctrl + x and y to save and exit

Need to make sure irexec starts on reboot, easiest way I found was to add it to cron

sudo crontab -e
scroll to the bottom and add
irexec
ctrl + x then y to save and exit

Reboot

When it comes back up, open your chosen web client for mopidy, start a track playing then try and control it using the remote. Good luck