11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RaspberryPiで脈拍データをCSV出力(アナログ入力をpythonで確認)

Last updated at Posted at 2015-10-14

手順とリンク

1.準備と基礎編
http://qiita.com/tkyko13/items/62ff91bce7d9e555c434
2.アナログ入力確認編
http://qiita.com/tkyko13/items/981989a006a95821ccde
3.pythonで確認
ここ
4.脈拍センサ
http://qiita.com/tkyko13/items/e4afc73add81d7bbb426
5.csv出力
http://qiita.com/tkyko13/items/9c0eb46c1b65129d2556

環境

ラズパイでどのようにpythonコードを書くのかのメモ
・ラズパイのデスクトップでIDLEで作成
(ディスプレイやキーボードが必要)
・ラズパイでviコマンド
(ディスプレイやキーボードが必要、マウスはなくてもよくなる)
・ラズパイにリモートデスクトップ、IDLEで作成
(ラズパイのネット接続とIPを確認出来る手段が必要)
・ラズパイにssh接続からvi
(ネット接続とIP確認できたら)
・ラズパイにftpでpythonファイル送信
(ネット接続とIP確認できたら
あと、自分のPCの開発環境で書けるよ、sublime textなど)

自分は臨機応変に使い分けています
基本はリモート接続しています
IP確認できる手段として同じネットワーク内から「arp -a」コマンドなどある
macのftpソフトはあまり使ってないですが、いいがない気がしますね
winの時はwinscp+puttyがすごくいい感じで、teratermも好きだったんですがね
ターミナルは好きです

サンプルコードその1

とりあえず最もシンプルなコードの一つを乗せます
前回の「アナログ入力確認編」でのI2Cのアドレスを使用しています
まずは実行するたびに値を見ています

sample1.py
import smbus

I2C_ADDRESS = 0x48
bus = smbus.SMBus(1)

bus.write_byte(I2C_ADDRESS, 0xFF)
value=bus.read_byte(I2C_ADDRESS)
print value

サンプルコードその2

繰り返し文で常に見れるようにします

sample2.py
import smbus
import time

I2C_ADDRESS = 0x48

bus = smbus.SMBus(1)

while True:
  bus.write_byte(I2C_ADDRESS, 0xFF)
  value=bus.read_byte(I2C_ADDRESS)
  print value
  time.sleep(0.1)

サンプルコードその3

最終的に脈拍を取る目的なので、スレッドを利用し1ミリ秒ごとの処理にします

sample3.py
import threading
import smbus
import time

I2C_ADDRESS = 0x48

bus = smbus.SMBus(1)

def loop():
	bus.write_byte(I2C_ADDRESS, 0xFF)
	value=bus.read_byte(I2C_ADDRESS)
	print value
	t=threading.Timer(0.1, loop)
	t.start()

t=threading.Thread(target=loop)
t.start()

サンプルコードその4(追記)

今回は10秒間だけ測って終了にしたいので、100回スレッドが実行されたら終わる処理を書きます。
スレッドの引数に与える値がどんどん増えていくようにしました。
もっと単純にできるやり方を考えたのですが、思いつかなかった。
何か存じていたらコメントお願いします。
(のちにファイル操作も行うので処理終了時にファイルを閉じる処理を行う必要があり、追記させて頂きました)

sample4.py
import smbus
import time
import threading
import csv

I2C_ADDRESS = 0x48

bus = smbus.SMBus(1)
f = open('data.csv', 'w')

def loop(count):

    # count = count+1
    bus.write_byte(I2C_ADDRESS, 0xFF)
    value = bus.read_byte(I2C_ADDRESS)
    print value

    writer = csv.writer(f, lineterminator='\n')
    writer.writerow([value])

    if count < 100 :
        t = threading.Timer(0.1, loop, [count])
        t.start()
    else :
        f.close()
        print 'finish'

t = threading.Thread(target=loop, args=(0,))
t.start()

次回は最後のサンプルコードを利用していきます

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?