ラベル Raspberry PI の投稿を表示しています。 すべての投稿を表示
ラベル Raspberry PI の投稿を表示しています。 すべての投稿を表示

2016年6月19日日曜日

RaspberryPI3で照度センサー(TSL2561)を使ってみる

RaspberryPI3で照度センサー(TSL2561)を使ってみる

照度センサー(TSL2561)をRaspberryPI3に接続してみた。

1.Raspberry PI3でI2Cを有効にする

$ sudo raspi-config

Advance Option->I2Cで有効にするし、再起動。

$ lsmod

i2c_bcm2708,i2c_devが見れていればOK.

2.以下のようにRaspberry PI3と接続

GND (TSL2561) -> GPIO04 (Raspberry Piの9pin)
VCC (TSL2561) -> 3.3v (Raspberry Piの1pin)
SDA (TSL2561) -> GPIO08 SDA1(Raspberry Piの3pin)
SCL (TSL2561) -> GPIO09 SCL(Raspberry Piの5pin)
$ sudo apt-get install i2c-tools python-smbus
$ sudo i2cdetect -y 1
$ sudo apt install libi2c-dev

このようにでてくればOK
enter image description here

3.PythonからI2Cを叩く準備

1. wiringpiのインストール

以下を参考。
http://takashin10mura.blogspot.jp/2016/06/wiringpipython.html

2. SMBUSのインストール

python-smbusはよくでてくるがpython3で使うとなると少し手間がかかります。
以下のようにすればできました。

wget http://ftp.de.debian.org/debian/pool/main/i/i2c-tools/i2c-tools_3.1.1.orig.tar.bz2

tar -xf i2c-tools_3.1.1.orig.tar.bz2
cd i2c-tools-3.1.1/py-smbus
mv smbusmodule.c smbusmodule.c.orig # make backup
$ sudo wget https://gist.githubusercontent.com/sebastianludwig/c648a9e06c0dc2264fbd/raw/2b74f9e72bbdffe298ce02214be8ea1c20aa290f/smbusmodule.c
$ sudo vi setup.py
  /usr/bin/python3に修正
$ sudo python3 setup.py build
$ sudo python3 setup.py install

3. smbusの確認

$ python3
$ import smbus
ここでエラーがでなければOK

4.TSL2561の制御

データシートを参考に以下のコードで照度を取得できました。

#! /usr/bin/python3
#coding: UTF-8
#TSL2561 照度センサー

import smbus
import time
import math

bus = smbus.SMBus(1)        #I2cバス番号
address = 0x39              #I2Cアドレス
command = 0x00

#i2c データ出力 1byte
def write(regist, value):
    bus.write_byte_data(address, regist, value)

#i2c データ読み込み 1byte
def read(regist):
    value = bus.read_byte_data(address, regist)
    return value

#i2c データ読み込み ブロック
def blockread(regist, num):
    value = bus.read_i2c_block_data(address, regist, num)
    return value

def ratio_calc(ambient, ir):
    # Avoid division by zero
    if (float(ambient) == 0):
        ratio = 9999
    else:
        ratio = (ir / float(ambient))

    return ratio

def init():
    #read ID
    print("id_reg=0x{0:02x}".format(read(0x8A)))
    #device enable
    write(0x80,0x03)
    power = 0x03
    while power != 0x03:
        power = read(0x80) & 0x03
        print("{0:02x}".format(power))
    #print("reg=0x{0:02x}".format(read(0x80)))

    #gain setting
    write(0x81,0x11)
    print("reg=0x{0:02x}".format(read(0x81)))

def read_lux():
    value0 = blockread(0xAC,2)
    ch0 = 256*value0[1]+value0[0]
#    print("reg=0x{0:04x}".format(ch0))

    value1 = blockread(0xAE,2)
    ch1 = 256*value1[1]+value1[0]
#    print("reg=0x{0:04x}".format(ch1))

    ratio = ratio_calc(ch0,ch1)
    if ((ratio >= 0) & (ratio <= 0.52)):
        lux = (0.0315 * ch0) - (0.0593 * ch0 * (ratio**1.4))
    elif (ratio <= 0.65):
        lux = (0.0229 * ch0) - (0.0291 * ch1)
    elif (ratio <= 0.80):
        lux = (0.0157 * ch0) - (0.018 * ch1)
    elif (ratio <= 1.3):
        lux = (0.00338 * ch0) - (0.0026 * ch1)
    elif (ratio > 1.3):
        lux = 0

    return lux

def main():
    init()
    counter = 0
    while True:
        counter += 1
        if counter == 5:
            lux = read_lux()
            print("lux={0:f}".format(lux))
            counter = 0

        time.sleep(1.0)

if __name__ == '__main__':
    main()

2016年6月10日金曜日

RaspberryPI3でBlynk libraryを使ってみる

RaspberryPI3でBlynk libraryを使ってみる

IoT時代ということでここを参考にRaspberry PI3と温湿度センサーのDHT11を使って温度計測をしてみる。

スマホ側の準備

IFTTTの準備

1.IF by IFTTTをインストールし、アカウントは取得する。

2.IF by IFTTTを起動し、画面右上のすり鉢のようなアイコンをタップ

enter image description here

3.「My Recipes」を開いて「+」(プラス)アイコンをタップ

enter image description here

3.画面下の「Create a New Recipe」をタップ

enter image description here

4.If の右側の「+」をタップした後に、「Maker」を選択。
enter image description here

enter image description here

5.Trigger として 「Receive a web request」を選択し、Event Name に“alert-temp”と入力
※RaspberryPi側から送信する Event Name と同じ名称にする必要あり。

enter image description here  

6.then の右側の「+」をタップした後に、「IF Notifications」を選択。

enter image description here

enter image description here

7.Action として「Send a notification」を選択し、Notification に“異常温度が計測されました。”などと入力し、Continueをタップ。
enter image description here

8.「Finish」をタップすれば Recipe は完成し、My Receipesに登録されます。
enter image description here

9.「+」をタップし、Makerを選択し、
enter image description here

「設定」をタップ。
enter image description here

以下のキーをメモっておく。
enter image description here

Blynkの準備

1.Blynkをインストール
2.プロジェクトの作成
enter image description here

3.プロジェクト名を入れてHARDWARE MODELとして”Raspberry Pi 3B”を選択。
AUTH TOKENはメモしておくこと。

enter image description here

4.「+」をタップし、「Value Display S」を2つ、「History Graph」を 1 つ追加
enter image description here

enter image description here

4.「Value Display S」、「History Graph」はそれぞれ以下のように設定
[1つ目]
名称: “温度”
INPUT: “Virtual”の“V0”
FREQUENCY: “10sec”
enter image description here

[2つ目]
名称: “湿度”
INPUT: “Virtual”の“V1”
FREQUENCY: “10sec”
enter image description here

「History Graph」
上から順に、以下を設定。
“Virtual”の“V0”、“温度”
“Virtual”の“V1”、“湿度”、
SHOW LEGEND を“ON”
enter image description here

こんな感じになったら完成です。
enter image description here

Raspberry PI側の準備

Raspberry Pi 用の C言語で書かれた GPIOアクセスライブラリのWiringPiのインストール

$ git clone git://git.drogon.net/wiringPi
$ cd ./wiringPi
$ ./build

blynk-libraryのインストール

$ git clone https://github.com/blynkkk/blynk-library.git
$ cd blynk-library/linux
$ make clean all target=raspberry

Curlライブラリのインストール

$ sudo apt-get update
$ sudo apt-get install libcurl4-openssl-dev

ソースコードの編集

今回変更及び追加するファイル一覧は以下。
kuro-iotexp1.cpp 追加ソースコード
kuro-iotexp1.h 追加ヘッダファイル
Makefile 変更(パッチ適用)
main.cpp 変更(パッチ適用)

ソースファイルと差分ファイルをダウンロード

$ wget http://driver.cfd.co.jp/cfd-drv/files/kuro-iotexp_kit/kuro-iotexp1.cpp
$ wget http://driver.cfd.co.jp/cfd-drv/files/kuro-iotexp_kit/kuro-iotexp1.h
$ wget http://driver.cfd.co.jp/cfd-drv/files/kuro-iotexp_kit/Makefile.patch
$ wget http://driver.cfd.co.jp/cfd-drv/files/kuro-iotexp_kit/main.cpp.patch

パッチを適用

$ patch -u -b < Makefile.patch
$ patch -u -b < main.cpp.patch

main.cpp を編集

以下の行の xxxxxxxx の箇所を IFT

char url[] = "https://maker.ifttt.com/trigger/alart-temp/with/key/xxxxxxxxxxxxxxxxxxxxxx";

再ビルド

$ make clean all target=raspberry

実行

tokenはBlynkででてきたAUTH TOKENを入れる。

$ sudo ./blynk --token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[0] Blynk v0.3.7 on Linux
[5001] Connecting to blynk-cloud.com:8442
[5206] Ready (ping: 95ms).
[5692] Trouble detected: http://docs.blynk.cc/#troubleshooting-flood-error
Read DHT11
Temperature = 27 degree C, Humidity = 58 %

となったので動き出したし、Blynkのほうでもデータが取得できた。

しかし、IFTTTへのPushの動検ができていないため、
意図的にIFTTTにpushされる温度にしても、
“Push IFTTT”とでるがスマホ側でPushされない。

試しにhttps://ifttt.com/makerからHow to Trigger Eventsを
クリックし、evnet nameを入れるとちゃんとPushできたし、
Raspberry PIの端末で以下のcurlを実施してもPushできた。
enter image description here

IFTTTへの自動的にPushするのはもう少し別のサンプルを
見ながら理解を深めるとします。

2016年5月9日月曜日

ubuntu mateをraspberry pi3に再インストールしたらやること

ubuntu mateをraspberry pi3に再インストールしたらやること

VNCがgray screenのままうまくいかないないので、再インストールすることにしました。
忘れないように手順をメモしておきます。
ここまでやればRaspberry PIにディスプレイとマウス、キーボードを付けなくてもよくなります。

インストール
フォルダの日本語化
raspberry pi関連
言語サポート
黒枠対策
日本語入力
tightvncのインストール

インストール

1.ディスクでパーティションを削除して空き領域の状態でubuntu mateのイメージのリストア
enter image description here
2.raspberry pi3にSDカードを指して起動
 [注意事項]
 ・キーボードは日本語(98xx)
 ・自動的にログインにチェック

フォルダの日本語化

フォルダが日本語になっているので、以下で英語にする。
Bluetoothアプレットのローカルサービス->転送のIncoming FolderもDownloadsに変更すること。

LANG=C xdg-user-dirs-gtk-update

wifiの設定

パスワードを入れて接続しておく。
IPv4 SettingでManualとし、IPアドレスを固定しておく。
IP: 192.168.11.11
Netmask: 255.255.255.0
Gateway: 192.168.11.1
DNSサーバー:192.168.11.1

raspberry pi関連

Main MenuのRaspberry Pi Infomationで以下を実施。
1.Resizing the file systemでResize Nowをクリック
これをやらないとSDカードの容量を十分に使えない。
2.Kernel Updates

$ sudo rpi-update

3.X11のEnable化

$ sudo graphical enable

言語サポートとキーボード

これで日本語を設定しないとキーボードで日本語が打てない。
1.設定→ユーザー向け→言語サポートを選ぶとインストールするかと聞いてくるのでインストールする。
システム全体に適用をクリック。
2.再起動してもう一度、言語サポートを選択し、キーボード入力に使うIMシステムでfcitxとなっていることを確認。
3.ハードウエア→キーボードのレイアウトでキーボードの型式をPC-98xxシリーズを選択。
4.再起動すると画面上にキーボードのアイコンがでてくるので右クリックし、
 入力メソッドをMOZCにする。
 
 これでキーボードの半角を押すことで日本語が入力できるようになる。

黒枠対策

画面のまわりに黒枠ができて小さい状態になってました。
config.txtで以下の2つを実施することで回避できました。

$ sudo vi /boot/config.txt

①hdmi_group, hdmi_mode の先頭の ”#” を外して、
  hdmi_group=2
  hdmi_mode=82

②以下の4つがコメントアウトになっていたのではずす     
  overscan_left=0
  overscan_right=0
  overscan_top=0
  overscan_bottom=0

tightvncのインストール

$ sudo apt-get install tightvncserver
$ vncpasswd
#起動
$ vncserver :1
#ログの確認
$ less /home/rpi3/.vnc/rpi3-desktop\:1.log
Font directory '/usr/share/fonts/X11/75dpi/' not found - ignoring
Font directory '/usr/share/fonts/X11/100dpi/' not found - ignoring
xrdb: No such file or directory
xrdb: can't open file '/home/rpi3/.Xresources'

$ touch ~/.Xresources
$ sudo apt-get install xfonts-75dpi xfonts-100dpi


#自動起動の設定
$ sudo crontab -e
@reboot su -c “vncserver :1 -geometry 1920x1080 -depth 24” user

接続側のubuntuのremminaで接続(サーバーを192.168.11.11:5901)し、全画面にすると画面がでてくる。
その後、なぜかRaspberry Pi側でコンソールとTilda 1 Configが立ち上がるようになる。

Raspberry Pi側でシステム→設定→ユーザー向け→自動起動するアプリで
Tildaのチェックを外すして再起動。

2016年5月1日日曜日

Raspberry Pi3にAndroid6.0を入れてみる

Raspberry Pi3にAndroid6.0を入れてみる

Raspberry Pi3にAndroid6.0を入れてみました。
※Ubuntu14.04を使用

  1. 以下からimgをダウンロード
    http://www.mediafire.com/download/cabo6z8ky1adgsj/marshrpi3wifibt19042016.img.bz2

  2. SDカードを差し、ユティリティ−→ディスクでSDカードを初期化

  3. “端末”で先ほどダウンロードして解凍したフォルダに移動
  4. 先ほどのイメージを以下のコマンドでSDカードにコピーする

    sudo dd if=marshrpi3wifibt19042016img of=/dev/mmcblk0 bs=1M
  5. Raspberry Pi3にSDカードを入れる

Androidは起動はしましたが、特にやることはないのでここまで。

2015年4月19日日曜日

Raspberry piにVNCで接続してみる。(Ubuntu編)

Raspberry piにVNCで接続してみる。(Ubuntu編)

以前はVNCサーバーを立ち上げたRaspberry PiにWindows
からUltra VNCを使って接続にいきましたが、
今度はUbuntuから接続に行ってみました。

リモートデスクトップクライアントのRemminaで以下の設定
で接続できました。

ただし、以前Raspberry Pi側のIPアドレスを固定したはずなのに別のアドレスになっていたのが解せないですが。。。

enter image description here

IPアドレスを固定したつもりでしたが、
/etc/network/interfacesを見ると固定したのはeth0だけでしたので、
以下のようにwlan0もIPアドレスを固定しました。

auto lo

iface lo inet loopback
#iface eth0 inet dhcp
iface eth0 inet static
address 192.168.xx.xx
netmask 255.255.255.0
gateway 192.168.xx.1

allow-hotplug wlan0
iface wlan0 inet manual
#iface wlan0 inet static
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
#iface default inet dhcp
iface default inet static
address 192.168.xx.xx
netmask 255.255.255.0
gateway 192.168.xx.1

Raspberry Piに接続できたのでファイル転送もRemminaクライアントデスクトップで以下とすることでファイル転送できました。
接続後のSSHのパスワードはraspberryで接続できました。

enter image description here

Raspberry PiでVNCサーバーを立ち上げるのは以下を
参考にしました。

Raspberry Piで遊ぼう No.5:VNC接続をしよう

2015年3月28日土曜日

Raspberry PiでBluetoothを使う

Raspberry PiでBluetoothを使う

Raspberry PiにBluetoothドングルをつけて接続しました。

~ペアリング~

1.Bluetoothのパッケージの追加

$ sudo apt-get install bluetooth bluez-utils blueman

2.bluetooth-agentを自動起動する。

$sudo vim /etc/init.d/bluetooth-agent
$sudo chmod 755 /etc/init.d/bluetooth-agent
$sudo update-rc.d bluetooth-agent defaults

bluetooth-agentに以下を記載。

### BEGIN INIT INFO
# Provides: bluetooth-agent
# Required-Start: $remote_fs $syslog bluetooth pulseaudio
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Makes Bluetooth discoverable and connectable to 0000
# Description: Start Bluetooth-Agent at boot time.
### END INIT INFO
#! /bin/sh
# /etc/init.d/bluetooth-agent
USER=root
HOME=/root
export USER HOME
case "$1" in
        start)
                #echo "setting bluetooth discoverable"
                #sudo hciconfig hci0 piscan
                sudo hciconfig hci0 pscan
                start-stop-daemon -S -x /usr/bin/bluetooth-agent -b -- 0000
                echo "bluetooth-agent startet pw: 0000"
                ;;
        stop)
                echo "Stopping bluetooth-agent"
                start-stop-daemon -K -x /usr/bin/bluetooth-agent
                ;;
        *)
                echo "Usage: /etc/init.d/bluetooth-agent {start|stop}"
                exit 1
                ;;
esac
exit 0

3.PINコードではなくYes/Noで接続できるようにする。

$ sudo perl -i -pe 's/KeyboardDisplay/DisplayYesNo/' /usr/bin/bluez-simple-agent

4.スマホ(Xperia)で設定→Bluetoothで”周辺のすべてのBluetooth危機で検出可能”の状態にする。(ここではまりました。)

5.以下でRaspberry Piをスキャン状態にする

$ hcitool scan
  xx:xx:xx:xx:xx:xx   Xperia AX

6.接続

$ sudo bluez-simple-agent hci0 xx:xx:xx:xx:xx:xx

RequestConfirmation
Confirm passkey (yes/No):yes

ここでスマホ側にペアリングするかのメニューがでてくるのでペアリングする。

Creating device failed: org.bluez.Error.AlreadyExists: AlreadyExistsというエラーがでた場合は、以下で1回消す。

$ sudo bluez-test-device remove XX:XX:XX:XX:XX:XX

ペアリングできると以下がでる。
New device・・・

5.自動接続
次回から自動接続する場合は以下となります。

$ sudo bluez-test-device trusted XX:XX:XX:XX:XX:XX yes
$ sudo bluez-test-input connect XX:XX:XX:XX:XX:XX

参考
Raspberry PiでBluetoothを扱う
Raspberry PiからBluetoohを使ってiPhoneでテザリング

~シリアル通信してみる~

1.SDP(Service Directory Protocol)にSPP(Serial Port Profile)を追加する。

まず登録されているサービスを確認する。

$sdptool browse local

Service NameにSerial Portがないので、以下でSPPを登録する。

$sdptool add --channel=22 SP
Serial Port service registered

もう一回以下で確認。

$sdptool browse local

Service Name: Serial Port
Service Description: COM Port
が追加されている。

2.RFCOMMサーバーを起動

$sudo rfcomm listen /dev/rfcomm0 22

Waiting for connection on channel 22とでて待機状態になる。

3.Android側からBluetooth Terminalで接続
接続されるとRaspberry Pi側で、以下が表示され、/dev/rfcomm0が作成される。

Connection from XX:XX:XX:XX:XX:XX to /dev/rfcomm0
Press CTRL-C for hangup

受信データの確認

$ cat /dev/rfcomm0

送信

$ echo "hello" > /dev/rfcomm0

以下のように修正すると自動化できると書いてあったが、逆にうまくいっていない。。

sudo vim /etc/bluetooth/rfcomm.conf
rfcomm0 {
        # Automatically bind the device at startup
        bind yes;

        # Bluetooth address of the device
        device XX:XX:XX:XX:XX:XX;

        # RFCOMM channel for the connection
        channel 22;

        # Description of the connection
        comment "a comment";
}

起動後自動でSerial Portができるようにする

rc.localに以下を修正することで改善

sudo vim /etc/rc.local
sdptool add --channel=22 SP
hciconfig hci0 piscan
hciconfig hci0 namepi’
rfcomm listen /dev/rfcomm0 22 &
exit 0
$sudo chmod +x  /etc/rc.local

参考
Linux PCにUSB Bluetoothを付けてNexus7と通信
[GPSRCC] RaspberryPiでBluetooth QZPOD編
Raspberry Pi をA2DPのsinkにして携帯やタブレットから音楽を再生する
Bluetooth/rfcomm
Camp Hack Day 2014 喋るテントTipee ソース

2015年3月25日水曜日

パソコンとRaspberryPIがVNCで繋がらなくなった

パソコンとRaspberryPIがVNCで繋がらなくなった

パソコンにUltraVNC Viewerを入れてRaspberry PI側にtightVNCserverを入れてVNC接続ができていたのですが、急にできなくなりました。

調べてみるとWifi AdapterのIPv4アドレスが192.xx.xx.19となっていた。
19個も接続するものもないのに。。。

Wifi Adapterを電源を入れなおしたら
IPv4アドレスが192.xx.xx.4となり、無事VNC接続できるようになりました。