Raspberry Pi – Arduino間でシリアル通信を行う

シリアル通信を行うことが可能なscreenコマンドと、
Pythonでシリアル通信を行うことが可能なpython-serialモジュールを
apt-getを利用してRaspberry Piにインストールする

sudo apt-get install screen
sudo apt-get install python-serial

次に、Pythonでシリアル通信スクリプトを作成する

vi serial-arduino.py

このときにファイル名をserial.pyとかいう名前にしてしまうと、
Pythonのserialモジュールと名前が重複してしまい、

AttributeError: ‘module’ object has no attribute ‘Serial’

というエラーがでてしまうので、他の名前にするのが良い。

USBでRaspberry PiとArduinoを接続し、
なんというデバイス名称で認識されているか確認する

dmesg
lsusb

シリアル通信でArduinoから定期的に送られてくるデータをもとに、
JSONファイルを作成するサンプルは以下の通り。

  • カンマ区切りデータの場合
import serial

    def main():
            # デバイス名: /dev/ttyACM0 通信速度: 9600bps
            con=serial.Serial('/dev/ttyACM0', 9600)
            # デバイス名を出力する
            print con.portstr
            while 1:
                    # 1行ごとにデータを取得する
                    str=con.readline()
                    # ファイルに書き込み
                    f = open('/tmp/data.json', 'w')
                    f.write("[{\"data_1\":" + str + "}]")
                    f.close()

    if __name__ == '__main__':
            main()
  • JSON形式の場合
import serial
    import json

    def main():
            # デバイス名: /dev/ttyACM0 通信速度: 9600bps
            con=serial.Serial('/dev/ttyACM0', 9600)
            # デバイス名を出力する
            print con.portstr
            while 1:
                    try:
                            # strという変数名は使用できない
                            strs=con.readline()
                            dec=json.loads(strs)

                            f = open('/tmp/data.json', 'w')
                            f.write(strs)
                            f.close()
                    except KeyError:
                            print "KeyError"
                    except ValueError:
                            print "ValueError"
                    except NameError:
                            print "NameError"

    if __name__ == '__main__':
                    main() 

実行してJSONが吐き出されるか確認する

python serial-arduino.py

Raspberry Pi + Motion + WebCamで動体検知を行う

Raspberry Piに接続したWebCamから映像を取得可能なパッケージはいくつか有名なものが存在するようだが、今回はMotionという動体検知を行うことのできるパッケージを用いて、WebCamの映像を取得してみる。

パッケージのインストール

apt-getから取得することができる

sudo apt-get install motion

設定

今回はMotionをデーモン起動させて常時稼働させる。設定ファイルは以下のように変更した。

# Image width
width 640
# Image height
height 480
# Maximum number of frames to be captured per second.
# フレーム数を大きくしすぎるとRaspberry Piで処理しきれなくなる
framerate 3
# Output 'normal' pictures when motion is detected
# 動体検知時に画像を出力しない
output_pictures off
# Use ffmpeg to encode movies in realtime
# 動体検知時に動画を出力しない
ffmpeg_output_movies off
# Make automated snapshot every N seconds
snapshot_interval 1
# Locate and draw a box around the moving object.
# 動体マーカ
locate_motion_mode on
# Target base directory for pictures and films
target_dir /var/www/html
# File path for snapshots (jpeg or ppm) relative to target_dir
snapshot_filename snapshot
# Restrict stream connections to localhost only
# ローカルホスト以外からのアクセスを許可する
stream_localhost off
# Restrict control connections to localhost only
# ローカルホスト以外からのアクセスを許可する
webcontrol_localhost off

サービスの開始

USBカメラを繋ぎ、認識されていることを確認する。

lsusb

Bus 001 Device 015: ID 0c45:62e0 Microdia MSI Starcam Racer

設定ができたらサービスを開始する。でも正常にサービス開始しない。

sudo service motion start
Apr 20 18:42:55 raspberrypi motion[1410]: Not starting motion daemon, disabled via /etc/default/motion ... (warning).

/etc/default/motionも変更しないといけないらしい。

sudo vi /etc/default/motion

# set to 'yes' to enable the motion daemon
start_motion_daemon=yes

再度、サービス開始。
今度はちゃんと開始された。

sudo service motion start

以下のエラーが発生する場合は、画像の出力先のパーミッションに問題ある場合があるので、パーミッションを変更する。

Apr 20 19:28:15 raspberrypi motion[7929]: [1] [ERR] [ALL] put_picture: Can't write picture to file /var/www/html/snapshot.jpg - check access rights to target directory
                                          Thread is going to finish due to this fatal error:
Apr 20 19:28:15 raspberrypi motion[7929]: [1] [ERR] [EVT] event_image_snapshot: Could not create symbolic link [snapshot.jpg]: