FLiR Dev Kit を試す その1
FLiR Dev Kit を試します。
これなに?
FLiR とは、前方監視型赤外線(forward looking infra-red)の略称らしいです。
モノ
スイッチサイエンスから購入しました。
電源電圧: 3~5V センサ形式: LWIR(8 ~ 14 μm) 画角: 水平視野51度、対角63.5度 解像度: 80 × 60 最小感度: 50mK インターフェース(映像): MIPIもしくはSPI インターフェース(制御): I2C 素早い応答性 (< 0.5 sec) 省電力: 通常150mW、最大160mW未満
メーカのガイド
FLIR Lepton Hookup Guide - learn.sparkfun.com
参考コード
GitHub - groupgets/LeptonModule: Code for getting started with the FLIR Lepton breakout board
斜め読みメモ
動作が不安定でも、モジュールの物理的な抜き差しはしない。
CSの接続先を 40PIN → 38PIN に変えればOKらしい。(未確認)
NFCリーダーライター PaSoRi を試す
手元にあるのは RC-S370で、現在は生産が終了しているモデルですね。
認識
$ lsusb Bus 001 Device 004: ID 041e:323d Creative Technology, Ltd Bus 001 Device 005: ID 054c:02e1 Sony Corp. FeliCa S330 [PaSoRi] Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Sony Corp. FeliCa S330 [PaSoRi]
と認識されています。
nfcpy
nfcpy を使います。
ドキュメントはこちら
Getting started — nfcpy 0.13.0 documentation
インストール
$ sudo pip install nfcpy ・・・ Successfully installed nfcpy ndeflib pydes libusb1 Cleaning up...
動作確認
$ python -m nfc This is the 0.13.0 version of nfcpy run in Python 2.7.9 on Linux-4.9.28-v7+-armv7l-with-debian-8.0 I'm now searching your system for contactless devices ** found usb:054c:02e1 at usb:001:005 but access is denied -- the device is owned by 'root' but you are 'kiyo' -- also members of the 'root' group would be permitted -- you could use 'sudo' but this is not recommended -- better assign the device to the 'plugdev' group sudo sh -c 'echo SUBSYSTEM==\"usb\", ACTION==\"add\", ATTRS{idVendor}==\"054c\", ATTRS{idProduct}==\"02e1\", GROUP=\"plugdev\" >> /etc/udev/rules.d/nfcdev.rules' sudo udevadm control -R # then re-attach device I'm not trying serial devices because you haven't told me -- add the option '--search-tty' to have me looking -- but beware that this may break other serial devs Sorry, but I couldn't find any contactless device
指示が出ているので従う。
$ sudo sh -c 'echo SUBSYSTEM==\"usb\", ACTION==\"add\", ATTRS{idVendor}==\"054c\", ATTRS{idProduct}==\"02e1\", GROUP=\"plugdev\" >> /etc/udev/rules.d/nfcdev.rules' $ sudo udevadm control -R
もう一度・・・
$ python -m nfc This is the 0.13.0 version of nfcpy run in Python 2.7.9 on Linux-4.9.24-v7+-armv7l-with-debian-8.0 I'm now searching your system for contactless devices I'm not trying serial devices because you haven't told me -- add the option '--search-tty' to have me looking -- but beware that this may break other serial devs Sorry, but I couldn't find any contactless device
おや?
RC-S380/P でやりなおす
特に対応から外れているわけでも無いので、手元にあるPaSoRiが壊れていのかもしれない、、、ということで、新しい PaSoRi を買い直しました。
RC-S380/P を刺して、、、
This is the 0.13.0 version of nfcpy run in Python 2.7.9 on Linux-4.9.28-v7+-armv7l-with-debian-8.0 I'm now searching your system for contactless devices ** found SONY RC-S380/P NFC Port-100 v1.11 at usb:001:010 I'm not trying serial devices because you haven't told me -- add the option '--search-tty' to have me looking -- but beware that this may break other serial devs
よし。
やはり、手元の S370 は、古くて壊れていたのかな?
git のサンプルを動かす
スイカを乗せて・・・
$ git clone https://github.com/nfcpy/nfcpy.git $ cd nfcpy $ python examples/tagtool.py [nfc.clf] searching for reader on path usb [nfc.clf] using SONY RC-S380/P NFC Port-100 v1.11 at usb:001:010 ** waiting for a tag ** Type3Tag 'FeliCa Standard (RC-S915)' ID=*** PMM=*** SYS=***
データを読み書きする
まず、メディア?を入手します。
アマゾンで買ったこれは、素直に動いてくれました。
先に書くと、フォーマットをして、NDEF 対応にしないと NDEF のやり取りが来ません。
NDEFフォーマットに成功したメディア達
フォーマット
format.py
import nfc def on_connect(tag): print("format:", tag.format()) clf = nfc.ContactlessFrontend('usb') if clf: print("Clf: {}".format(clf)) clf.connect(rdwr={ 'on-connect': on_connect }) clf.close()
実行
$ python format.py Clf: SONY RC-S380/P on usb:001:010 ('format:', True)
データの読み取り
messageに入っているデータを読み込みます。
フォーマットしただけだと、空っぽです。
import nfc def on_startup(targets): print("on_startup()") return targets def on_connect(tag): print("Tag: {}".format(tag)) print("Tag type: {}".format(tag.type)) #print '\n'.join(tag.dump()) if tag.ndef: print tag.ndef.message.pretty() #return True def on_release(tag): print("on_release()") if tag.ndef: print(tag.ndef.message.pretty()) clf = nfc.ContactlessFrontend('usb') if clf: print("Clf: {}".format(clf)) clf.connect(rdwr={ 'on-startup': on_startup, 'on-connect': on_connect, 'on-release': on_release }) clf.close()
実行
$ python 001.py Clf: SONY RC-S380/P on usb:001:010 on_startup() Tag: Type3Tag 'FeliCa Lite-S (RC-S966)' ID=_ID_ PMM=_PMM_ SYS=88B4 Tag type: Type3Tag record 1 type = '' name = '' data = ''
書き込み
書き込んで、確認してみる。
import nfc def on_startup(targets): print("on_startup()") return targets def on_connect(tag): print("Tag: {}".format(tag)) print("Tag type: {}".format(tag.type)) #print '\n'.join(tag.dump()) if tag.ndef: record = nfc.ndef.TextRecord("Hello World!") tag.ndef.message = nfc.ndef.Message(record) print tag.ndef.message.pretty() #return True def on_release(tag): print("on_release()") if tag.ndef: print(tag.ndef.message.pretty()) clf = nfc.ContactlessFrontend('usb') if clf: print("Clf: {}".format(clf)) clf.connect(rdwr={ 'on-startup': on_startup, 'on-connect': on_connect, 'on-release': on_release }) clf.close()
実行
$ python 002.py Clf: SONY RC-S380/P on usb:001:010 on_startup() Tag: Type3Tag 'FeliCa Lite-S (RC-S966)' ID=__ID__ PMM=__PMM__ SYS=88B4 Tag type: Type3Tag record 1 type = 'urn:nfc:wkt:T' name = '' data = '\x02enHello World!'
今回は、いつ買ったわからない RC-370 が動かなかったけれども、買い直した RC-S380/P では動いた点、
フォーマットしないと NDEF でのやり取りができない点でつまずきました!
Raspberry pi でロボットアームを動かす その8 別マシンから動画ストリームを使う
ロボットアームを制御している(直結してある)ラズパイ以外で、映像を取得したい。
どうやったら簡単に実現できるか。
Opencv 2.4.8 でやる
別のubuntu マシンの Python プログラムからロボットアームの映像を取得してみる。
まず、入っている opencv のバージョンを確認してみる。
$ python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '2.4.8'
2.4.8 だ。
API を確認する。
Reading and Writing Images and Video — OpenCV 2.4.8.0 documentation
Python: cv2.VideoCapture() →
Parameters: filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, …) device – id of the opened video capturing device (i.e. a camera index). If there is a single camera connected, just pass 0.
ということで、ダイレクトにURLを指定はでき無さそう。
ということで、2種類の書き方を探せた。
Opencv 2.4.8 ストリームで、終了記号を探す方法?
#!/usr/bin/env python # -*- coding: UTF-8 -*- import cv2 import urllib import numpy as np stream=urllib.urlopen('http://192.168.100.86:8080/?action=stream') bytes='' while True: bytes+=stream.read(16384) a = bytes.find('\xff\xd8') b = bytes.find('\xff\xd9') if a!=-1 and b!=-1: jpg = bytes[a:b+2] bytes= bytes[b+2:] i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR) cv2.imshow('i',i) if cv2.waitKey(30) & 0xFF == ord('q'): exit(0)
Opencv 2.4.8 画像を取得し続ける方法
#!/usr/bin/env python # -*- coding: UTF-8 -*- import base64 import time import urllib2 import cv2 import numpy as np req = urllib2.Request('http://192.168.100.86:8080/?action=snapshot'); while True: response = urllib2.urlopen(req) img_array = np.asarray(bytearray(response.read()), dtype=np.uint8) frame = cv2.imdecode(img_array, 1) cv2.imshow('frame', frame) if cv2.waitKey(30) & 0xFF == ord('q'): break
opencv 3.2
APIがことなる。
OpenCV: cv::VideoCapture Class Reference
§ VideoCapture() [2/4] cv::VideoCapture::VideoCapture ( const String & filename ) Open video file or a capturing device or a IP video stream for video capturing. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Same as VideoCapture(const String& filename, int apiPreference) but using default Capture API backends
とのことで、いかにも直接 URL を指定できそうだ。
※未確認※
Raspberry pi zero w を動かす
手元に Raspberry pi zero w が届いたので、OSを入れて動かしてみます。
OS
RASPBIAN JESSIE LITE の Release date:2017-03-02
を入れてみます。
SDformatter でフォーマットして、 lite を win32diskimager で焼きます。
初期設定
とりあえず、USBから有線LANを繋いで、rpi-update をインストールして、ファームウェアをアップデートして、再起動。
Wifi設定
上記記事に従う。
ifconfig から、 wlan0 が有ることを確認する。
wpa_passphrase コマンドで wifi 設定をする。
接続を確認できた。
日本語化
jfbterm は、ログアウトする際にフリーズする。
fbterm を入れる。
fbterm -s 20 など
補足
バンドルされていたマイクロSDに、Noobsが入っていたので、試しに起動した所、当初、 Wifiの設定等々が出てきませんでした。
そこで、rpi-update して、再起動したら、 Wifi の設定が出てきました。
USBシリアル通信を試す
何かの役に立つかもしれないから、シリアル通信に挑戦してみる。
Pi Zero をつかいました。
Raspberry pi の設定
raspi-config から、シリアルログインをONにします。
5 Interfacing Options > P6 Serial
で、 ON にします。
配線
物理的につなぎます。
ケーブルその1
まず、手元に有ったこのケーブルで試しました。
赤5V、黒GND、緑Tx(3.3V)、白Rx(3.3V)
私の場合は、電源は別途供給していたので、 赤は繋がず、
ケーブル | RPI |
---|---|
GND | GND |
緑Tx | UART_RXD |
白Rx | UART_TXD |
につなぎました。
PCにUSBをさして、teraTermで、COOM4指定して、、、
Rpi Boot…
文字化けする・・・
ケーブルその2
つぎに、同じく、いつかかったこれを使ってみた。
(多分これ・・・)
アダプタ | RPI |
---|---|
GND | GND |
Tx | UART_RXD |
Rx | UART_TXD |
成功した!
圧力センサー FSR406 を試す
FSR406 と ADコンバーター MCP3008
配線
FSR406 が、圧力によって変化するタイプのスイッチ的な性格なので、プルダウン抵抗的な配線にする、、、のだと思います。
皆様の例に習いました。
抵抗が CH0(1) と Vdd(16) を繋いでいます。
MCP3008 Vdd(16), Vref(15) > RPI 3.3v MCP3008 AGND(14),DGND(9) > RPI GND MCP3008 CLK(13) > RPI GPIO 11 (SCLK) MCP3008 DOUT(12) > RPI GPIO 9 (MISO) MCP3008 DIN(11) > RPI GPIO 10 (MOSI) MCP3008 CS/SHDN(10) > RPI GPIP 8 (CE0) MCP3008 CH0(1) > RPI GPIP 8 (CE0)
に配線します。
コーディング
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import sys import spidev spi = spidev.SpiDev() spi.open(0,0) def readAdc(channel): adc = spi.xfer2([1,(8+channel)<<4,0]) data = ((adc[1]&3) << 8) + adc[2] return data def convertVolts(data): volts = (data * 3.3) / float(1023) volts = round(volts,4) return volts def convertPressure(data): pressure = 1023 - data return pressure if __name__ == '__main__': try: while True: data = readAdc(0) volts = convertVolts(data) pressure = convertPressure(data) print("adc: {:4}, volts : {:.2f}, pressure : {:.2f}".format(data, volts, pressure)) time.sleep(1) except KeyboardInterrupt: pass spi.close() sys.exit(0)
接触を感知できれば何でも良かったので、面積の大きい FSR406 を購入したのですが、重さへの演算は、出来ないタイプのセンサーだと思う。
どのような仕組みで抵抗が変わるのか調べていませんが、分銅の置き方で数値が変わります。
Raspberry pi でロボットアームを動かす その7 カメラモジュールv2に変更
カメラを、WEBカメラからカメラモジュールv2に変更しました。
それにともなってコードも少しだけ変わりました。
コーディング
#!/usr/bin/python # coding: utf-8 import sys import io import cv2 import numpy as np import pprint as pp import picamera def capture_camera(): blue_min = np.array([110, 100, 100], np.uint8) blue_max = np.array([140, 255, 255], np.uint8) green_min = np.array([40, 70, 70], np.uint8) green_max = np.array([80, 255, 255], np.uint8) with picamera.PiCamera() as camera: camera.hflip = True camera.vflip = True camera.resolution = (640, 480) camera.framerate = 10 stream = io.BytesIO() while True: camera.capture(stream, format="jpeg", use_video_port=True) frame = np.fromstring(stream.getvalue(), dtype=np.uint8) stream.seek(0) frame = cv2.imdecode(frame, 1) # 2値化 image_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # HSV, range of Hue is 0-180 h = image_hsv[:, :, 0] s = image_hsv[:, :, 1] v = image_hsv[:, :, 2] width = h[0,:].size height = h[:,0].size # print( 'width %s, height %s' % (width, height) ) threshold_green_img = cv2.inRange(image_hsv, green_min, green_max) # 輪郭抽出 contours, hierarchy = cv2.findContours(threshold_green_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # pp.pprint( contours ) cv2.drawContours(frame, contours, -1, (0,255,0), 3) if len(contours) > 0 : rects = [] for contour in contours: approx = cv2.convexHull(contour) rect = cv2.boundingRect(approx) # x,y,w,h rects.append(rect) pp.pprint( len(rects) ) max_rect = getBiggestRect( rects ) center_x = max_rect[0] + max_rect[2]/2 center_y = max_rect[1] + max_rect[3]/2 # 囲む cv2.rectangle(frame, (max_rect[0], max_rect[1]), (max_rect[0]+max_rect[2], max_rect[1]+max_rect[3]), (0, 0, 255), 3) # 線を引く cv2.line(frame, (center_x, 0), (center_x, height), (0, 0, 255)) # Draw Red Line cv2.line(frame, (0, center_y), (width, center_y), (0, 0, 255)) # Draw Red Line cv2.imshow('threshold_green_img', frame) #frameを表示 #cv2.imshow('camera capture', frame) #10msecキー入力待ち k = cv2.waitKey(10) #Escキーを押されたら終了 if k == 27: break def getBiggestRect( rects ): pre_area = 0 biggest_index = 0 for i, rect in enumerate(rects): area = rect[2] * rect[3] if area > pre_area: pre_area = area biggest_index = i return rects[biggest_index] if __name__ == '__main__': try: while True: capture_camera() break except KeyboardInterrupt: pass #キャプチャを終了 cv2.destroyAllWindows()
実行