Affichage des articles dont le libellé est Raspberry Pi. Afficher tous les articles
Affichage des articles dont le libellé est Raspberry Pi. Afficher tous les articles

dimanche 24 septembre 2017

Capteurs I2C

I2C

Le protocole I2C est un bus de communication très simple, accessible depuis les GPIO d'une carte type Raspberry Pi ou BeagleBone Black.

BME280

Le BME280 est un capteur BOSCH de faible coût avec interfaces I2C et SPI, qui fournit des valeurs de:
  • température
  • pression
  • humidité relative.

Spécifications

  • Current consumption 1.8 μA @ 1 Hz humidity and temperature
  • Supply voltage VDD main supply voltage range: 1.71 V to 3.6 V
  • VDDIO interface voltage range: 1.2 V to 3.6 V
  • 2.8 μA @ 1 Hz pressure and temperature
  • 3.6 μA @ 1 Hz humidity, pressure and temperature
  • 0.1 μA in sleep mode
  • Operating range -40...+85 °C, 0...100 % rel. humidity, 300...1100 hPa
  • BME280 digital pressure sensor RoHS compliant, halogen-free, MSL1
  • Key parameters for humidity sensor1
  • Response time 1 s
  • Accuracy tolerance ±3 % relative humidity
  • Hysteresis ±1% relative humidity
  • Key parameters for pressure sensor
  • RMS Noise 0.2 Pa, equiv. to 1.7 cm
  • Offset temperature coefficient ±1.5 Pa/K, equiv. to ±12.6 cm at 1 °C temperature change
  • Material: Plastic
  • Size: approx.20mm*12mm*3mm
  • Color: Red
Package includes:
  • 1 x Barometric Pressure Sensor Board
  • 2 x Pin Header
Adress 0x77

Installation sur Rpi 1 A rev 2 (Wheezy)

La plupart des documentations font référence au protocole i2c, mais l'implémentation que l'on rencontre sur les systèmes monocartes sous Linux (Raspberry Pi, BeagleBone Black, etc.) est plutôt une spécialisation de ce protocole nommée SMBus (System Management Bus). Les différences essentielles sont des limitations dans les tensions autorisées (3.3V maxi.), ou les fréquences de communication (10 à 100 kHz seulement). Le protocole SMBus est plus particulièrement utilisé pour communiquer entre un microprocesseur et les périphériques annexes sur la carte-même (ventilateur, capteur de température, etc.). Ceci explique que de nombreuses fonctions de l'API Linux pour le sous-système i2c soient préfixées par smbus. L'accès depuis l'espace utilisateur est facilité par le module i2c-dev qui rend les bus i2c visibles dans le répertoire /dev sous forme de fichiers spéciaux représentant des périphériques en mode caractère.





Le protocole i2c est supporté par le noyau Linux depuis sa version 2.4. De nombreux périphériques sont reconnus par le kernel.
Il faut charger dans le noyau le module qui gère le contrôleur i2c inclus dans le system-on-chip (de la famille Broadcom 2708) du Raspberry Pi. Ce module est nommé i2c_bcm2708. On peut le charger automatiquement avec l'aide du menu raspi-config.

i2cdetect -l
i2c-1 i2c        20804000.i2c                     I2C adapter
Le bus i2c 0 est vide mais le BME280 est connecté sur le bus i2c 1 à l'adresse 0x77

Librarie python Adafruit

Python offre une interface pour la communication en i2c qui s'appuie sur les fonctionnalités i2c-dev. Il existe une bibliothèque permettant un accès simple aux périphériques qui supporte le sous-ensemble SMBus d'i2c. Les fonctions de haut-niveau permettent une communication avec le périphérique en dissimulant les multiples émissions/réceptions d'octets sous-jacentes.

apt-get update
apt-get install build-essential python-pip python-dev python-smbus git
git clone https://github.com/adafruit/Adafruit_Python_GPIO.git
cd Adafruit_Python_GPIO
sudo python setup.py install


git clone https://github.com/adafruit/Adafruit_Python_BME280.git

python ./Adafruit_BME280_Example.py
Temp      = 17.494 deg C
Pressure  = 904.30 hPa
Humidity  = 71.20 %

Client python influxDB

Installation du client influxdb: 
https://github.com/influxdata/influxdb-python

Install, upgrade and uninstall InfluxDB-Python with these commands:

$ pip install influxdb
$ pip install --upgrade influxdb
$ pip uninstall influxdb

Successfully installed influxdb python-dateutil pytz requests six chardet idna urllib3 certifi
Cleaning up...

Installation d'influxDB

Paquet  officiel désormais disponible pour Raspberry Pi (sur forme Linux Binaries - ARM) 
wget https://dl.influxdata.com/influxdb/releases/influxdb-1.3.5_linux_armhf.tar.gz
tar xvfz influxdb-1.3.5_linux_armhf.tar.gz


/usr/lib/influxdb/scripts# cp init.sh /etc/init.d/influxd
update-rc.d influxd defaults

useradd -m influxdb
groupadd  influxdb
usermod -a -G influxdb influxdb

influx
Connected to http://localhost:8086 version 1.3.5
InfluxDB shell version: 1.3.5
> create database domotic;

service influxd start

Visualisation

N'importe quel serveur Grafana peut publier des tableaux de bords à partir des données du capteur BME280 enregistrées dans InfluxDB

 
 

Beagle Bone Black




debian@bbb-tic:~$ ls -l /sys/bus/i2c/devices/i2c-*
lrwxrwxrwx 1 root root 0 Jan  1  2000 /sys/bus/i2c/devices/i2c-0 -> ../../../devices/ocp.3/44e0b000.i2c/i2c-0
lrwxrwxrwx 1 root root 0 Jan  1  2000 /sys/bus/i2c/devices/i2c-2 -> ../../../devices/ocp.3/4819c000.i2c/i2c-2
debian@bbb-tic:~$ 

apt-get update
apt-get install i2c-tools

root@bbb-tic:/home/debian# i2cdetect -l

i2c-0 i2c        OMAP I2C adapter                 I2C adapter
i2c-2 i2c        OMAP I2C adapter                 I2C adapter


root@bbb-tic:/home/debian# i2cdetect -y -r 2
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- UU UU UU UU -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --  

bug in device tree MUST: roollback to a previous kernel

To enable the I2c-1 on the BeagleBone Black Rev A, B and C:

    Rev A/B: Open the file /media/BEAGLEBONE/uEnv.txt in an editor (vim/nano)
    Rec C: Open the file /boot/uboot/uEnv.txt in an editor (vim/nano)
    Add the key "capemgr.enable_partno="
    Add the ports you want to enable, comma separated (BB-I2C0, BB-I2C1, etc)
    Reboot

I had the same problem (missing cape-manager ) in the newer kernel versions a few weeks ago.
Needed to switch back to kernel 3.8.13 to get the cape-manager working. I haven't had time to investigate more.

If you want to give it a try:

sudo apt-get update
sudo apt-get install linux-image-3.8.13-bone67
sudo reboot

/boot/uEnv.txt

#Docs: http://elinux.org/Beagleboard:U-boot_partitioning_layout_2.0

uname_r=3.14.33-ti-r50
#dtb=
cmdline=quiet init=/lib/systemd/systemd 

##Example
#cape_disable=capemgr.disable_partno=
cape_enable=capemgr.enable_partno=BB-I2C0,BB-I2C1,BB-I2C2 

##enable BBB: eMMC Flasher:
#cmdline=init=/opt/scripts/tools/eMMC/init-eMMC-flasher-v3.sh

uuid=5b9e0cf5-52b7-4bf3-8e38-c9c805d89105



i2cdetect -l
i2c-0 i2c        OMAP I2C adapter                 I2C adapter
i2c-1 i2c        OMAP I2C adapter                 I2C adapter
i2c-2 i2c        OMAP I2C adapter                 I2C adapter

root@bbb-tic:/home/debian# i2cdetect -y -r 0 
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- UU -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- UU -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: UU -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: UU -- -- -- -- -- -- --     

i2cdetect -y -r 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- UU UU UU UU -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- 77
              
root@bbb-tic:/home/debian# i2cdetect -y -r 2
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 

Attention:
BME280 connecté sur pins P9 19,20 soient i2C2
Inversion de l'énumération dans le kernel i2C2 est de dev 1

BBB avec lib python adafruit

Install de la lib python portable GPIO d'adafruit: https://xdevs.com/guide/thp_rpi/

apt-get update
apt-get install build-essential python-pip python-dev python-smbus git
git clone https://github.com/adafruit/Adafruit_Python_GPIO.git
cd Adafruit_Python_GPIO
sudo python setup.py install

git clone https://github.com/adafruit/Adafruit_Python_BME280.git

Install du client influxdb: 
https://github.com/influxdata/influxdb-python

Install, upgrade and uninstall InfluxDB-Python with these commands:
$ pip install influxdb
$ pip install --upgrade influxdb
$ pip uninstall influxdb

pip install influxdb

Successfully installed influxdb python-dateutil pytz requests six chardet idna urllib3 certifi
Cleaning up...

Tests

:~/bme280/Adafruit_Python_BME280$ python ./Adafruit_BME280_Example.py 
Temp      = 16.531 deg C
Pressure  = 914.29 hPa
Humidity  = 56.21 %

Code source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import json
import time
from collections import OrderedDict
from datetime import datetime
from Adafruit_BME280 import *
from influxdb import InfluxDBClient

def parse_args():
    parser = argparse.ArgumentParser(
        description='example code to play with InfluxDB')
    parser.add_argument('--host', type=str, required=False, default='localhost',
                        help='hostname of InfluxDB http API')
    parser.add_argument('--port', type=int, required=False, default=8086,
                        help='port of InfluxDB http API')
    return parser.parse_args()

def main(host='192.168.1.xxx', port=8086):

    user = 'xxxx'
    password = 'xxxx'
    dbname = 'xxxxx'
    query = 'select * from bureau;'

    measurement = OrderedDict()
    measurement['measurement']='Garage'
    tags = OrderedDict()
    tags['host']='bbb-tic'
    tags['sensor']='bme280'
    measurement['tags'] = tags

    fields = OrderedDict()

    #### get the values
    sensor = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8)

    while True:
        temp = sensor.read_temperature()
        pressure = sensor.read_pressure()
        humidity = sensor.read_humidity()
        #print 'Temp      = {0:0.3f} deg C'.format(temp)
        #print 'Pressure  = {0:0.2f} hPa'.format(pressure/100)
        #print 'Humidity  = {0:0.2f} %'.format(humidity)

        fields["Temp"] = temp
        fields["Pressure"] = pressure/100
        fields["Humidity"] = humidity
        measurement["fields"] = fields
        #### get the time
        ## UNIX timestamp
        ## measurement['time'] = int(time.time())
        current_time = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
        measurement['time'] = current_time
        json_body = json.dumps(measurement)
#        print("Result: {0}".format(json_body))

        client = InfluxDBClient(host, port, user, password, dbname)
#        client.write_points([measurement])

#        print("Queyring data: " + query)
#        result = client.query(query)
#        print("Result: {0}".format(result))
        break
        time.sleep(60)

if __name__ == '__main__':
    args = parse_args()
    main(host=args.host, port=args.port)
debian@bbb-tic:~/bme280/Adafruit_Python_BME280$ 

dimanche 9 août 2015

Domoticz sur Raspbian

Introduction


Cet article résume la procèdure de compilation et d'installation de Domoticz sur une carte Raspberry Pi (1 model B) configurée avec une distribution Linux Debian 7 (Wheezy).

Prérequis


  • Un serveur Linux/Debian
  • Les outils de compilation C++
  • La librairie open-zwave pour utiliser ce protocole
  • Un client git

Client git

Le client git s'installe depuis le repository de paquets Debian avec la commande suivante:
sudo apt-get install git

Outils de compilation C++

Les librairies nécessaires à la compilation s'installent avec les deux commandes suivantes:
sudo apt-get install build-essential -y
sudo apt-get install cmake libboost-dev libboost-thread-dev libboost-system-dev libsqlite3-dev curl libcurl4-openssl-dev libusb-dev zlib1g-dev libssl-dev

Compilation d'openZWave


Installer la dépendance libudev:
sudo apt-get install libudev-dev

Depuis le répertoire racine des compilations qui est par défaut /home/pi:
Récupérer les sources depuis github avec l'aide de la commande suivante:
git clone https://github.com/OpenZWave/open-zwave.git

Lancer la compilation:
cd open-zwave; make

La sortie standard de la commande make devrait ressembler aux lignes suivantes (noter la version 1.3.434):
make -C /home/pi/open-zwave/cpp/build/ -
make[1]: Entering directory '/home/pi/open-zwave/cpp/build'
Building OpenZWave Version 1.3-434-g09a092
...
Linking Static Library
Linking Shared Library
make[1]: Leaving directory '/home/pi/open-zwave/cpp/build'
make -C /home/pi/open-zwave/cpp/examples/MinOZW/ -
make[1]: Entering directory '/home/pi/open-zwave/cpp/examples/MinOZW'
Building Main.o
Linking /home/pi/open-zwave/.lib/MinOZW
g++ -o /home/pi/open-zwave/.lib/MinOZW /home/pi/open-zwave/.lib/Main.o /home/pi/open-zwave/libopenzwave.so -pthread
Creating Temporary Shell Launch Script
make[1]: Leaving directory '/home/pi/open-zwave/cpp/examples/MinOZW'

Création d'un lien vers libOpenZWave


La librairie OpenZwave compilée précedemment correspond à la version 1.3-434. Je recommande la création d'un lien symbolique vers cette librairie depuis le répertoire racine utilisé pour les compilations ((/home/pi):

ls -al
drwxr-xr-x 23 pi pi 4096 Aug 9 15:23 domoticz
drwxr-xr-x 11 pi pi 4096 Aug 9 16:07 open-zwave

mv open-zwave ozw-1.3.434
ln -s ozw-1.3.434 ozw 

ls -al
drwxr-xr-x 23 pi pi 4096 Aug 9 15:23 domoticz
lrwxrwxrwx 1 pi pi 11 Aug 9 16:13 ozw -> ozw-1.3.434
drwxr-xr-x 11 pi pi 4096 Aug 9 16:07 ozw-1.3.434

Compilation de domoticz


Depuis le répertoire racine des compilations (/home/pi).
Récupérer les sources depuis le git hub avec l'aide de la commande suivante:
git clone https://github.com/domoticz/domoticz.git domoticz

Aller dans le réperoire domoticz et modifier le chemin de recherche de la librarie openZWave dans le fichier CMakeLists.txt:

cd domoticz; vi  CMakeLists.txt:

# try to find open-zwave, if found, include supportfind_library(OpenZWave NAMES libopenzwave.a HINTS "../ozw" "../ozw/cpp/build")

Lancer la fabrication du makefile avec la commande suivante:
cmake -DCMAKE_BUILD_TYPE=Release .

La sortie standard de la commande cmake devrait ressembler aux lignes suivantes (noter la révision 2709 ainsi que la détection de libopenzwave):

-- Compiling Revision #2709
-- Boost version: 1.49.0
-- Found the following Boost libraries:
--   thread
--   date_time
--   system
-- Linking against boost static libraries
-- Found ZLIB: /usr/lib/arm-linux-gnueabihf/libz.so (found version "1.2.7")
-- ZLIB libraries found at: /usr/lib/arm-linux-gnueabihf/libz.so
-- ZLIB includes found at: /usr/include
-- Found CURL: /usr/lib/arm-linux-gnueabihf/libcurl.so (found version "7.26.0")
-- Curl libraries found at: /usr/lib/arm-linux-gnueabihf/libcurl.so
-- Curl includes found at: /usr/include
-- Found LIBUSB: /usr/lib/arm-linux-gnueabihf/libusb.so 
-- LIBUSB found at: /usr/lib/arm-linux-gnueabihf/libusb.so
-- Crypto library found at: /usr/lib/arm-linux-gnueabihf/libcrypto.so
-- /home/pi/ozw/libopenzwave.a
 

 Lancer la compilation de domoticz avec l'aide de la commande:
make

Création d'un lien vers domoticz


La version de domoticz compilée précedemment correspond à la révision  2709. Je recommande la création d'un lien symbolique vers cette librairie depuis le répertoire racine utilisé pour les compilations ((/home/pi):

ls -alh
drwxr-xr-x 25 pi   pi   4.0K Aug  9 19:35 domoticz
lrwxrwxrwx  1 pi   pi     11 Aug  9 16:13 ozw -> ozw-1.3.434
drwxr-xr-x 11 pi   pi   4.0K Aug  9 16:07 ozw-1.3.434
mv domoticz domoticz-2709
ln -s domoticz-2709 domoticz

ls -al
lrwxrwxrwx  1 pi   pi       13 Aug  9 19:39 domoticz -> domoticz-2709
drwxr-xr-x 25 pi   pi     4096 Aug  9 19:35 domoticz-2709
lrwxrwxrwx  1 pi   pi       11 Aug  9 16:13 ozw -> ozw-1.3.434
drwxr-xr-x 11 pi   pi     4096 Aug  9 16:07 ozw-1.3.434

Démarrage


Pour démarrer domoticz sous la fomre d'un service recopier le script  domoticz.sh sous le répertoire /etc/init.d:
sudo cp domoticz.sh /etc/init.d 
sudo chmod +x /etc/init.d/domoticz.sh 
sudo update-rc.d domoticz.sh defaults 

Editer le script afin de mettre à jour le chemin d'accès au programme domoticz: 
sudo vi /etc/init.d/domoticz.sh DAEMON=/home/pi/domoticz/domoticz

Le script permet aussi de changer le port utilisé par l'interface Web:
OPTIONS=-www 8080

domoticz peut maintenant être supervisé avec les commandes suivantes:
sudo service domoticz.sh start
sudo service domoticz.sh stop
sudo service domoticz.sh status

Gestion des services


La commande update-rc.d permet d'ajouter, modifier ou supprimer un service.

Ajout

La commande update-rc.d [-n] domoticz.sh defaults ajoute le service domoticz (l’option -n permet de tester la commande sans la jouer).

Suppression

La commande update-rc.d domoticz.sh remove desactive le service domoticz. Cependant, si on souhaite réactiver le service ultérieurement, on pourra exécuter de nouveau la commande suivante: update-rc.d domoticz.sh defaults.