class HeartMonitor: def __init__(self): self.p = Pulsesensor() def startbeat(self): self.p.startAsyncBPM() def getheartrate(self): return self.p.BPM def stopbeat(self): self.p.stopAsyncBPM()
def heartBeat(): # Pulse Sensor로 심박수를 측정하는 함수. global fileName global deviceID p = Pulsesensor() p.startAsyncBPM() count = 0 bpmSum = 0 tryNum = 0 Done = False startTime = time.time() while not Done: # 측정이 정확하게 될 때까지 반복. nowTime = time.time() while int(nowTime - startTime) <= 12: # 12초 동안 측정. bpm = p.BPM if bpm >= 50 and bpm <= 85: # Pulse Sensor가 비정상적인 값을 인식할 때, 평균 계산에 적용하지 않기 위함. bpmSum += bpm count += 1 # 정확한 측정이 몇 번 수행되었는지 확인. nowTime = time.time() continue if count is not 0: # 정확한 측정이 한 번이라도 수행되었을 때. p.stopAsyncBPM() # 측정 중단. value = bpmSum / count # 평균 값 계산. Done = True # 측정 완료를 알림. intvalue = str(round( value, 1)).split('.')[0] # 소수점 첫째 자리에서 반올림 하여 int형으로 변환. else: fileName = "PulseAgain.mp3" # 측정이 정확하지 않을 때 다시 측정하겠다는 알림 출력. playMP3File() tryNum += 1 startTime = time.time() Send('pulse', intvalue) # 측정 값을 서버에 전송. global msg_flag while not msg_flag: continue
def sensors(): final_ret = dict() ###########DHT-11#############################DATA-PIN = 20 humidity, temperature = Adafruit_DHT.read_retry(11,20) print("DHT done") #print("H = "+str(humidity)+" T = "+str(temperature)) ############################################## ##############DS18b20##########################DATA-PIN = 04 body_temperature = probetemp.read_temp() print("DS18B20 done") ########################################## #############MQ-135##########################DATA-PIN = 1(analog) mq = MQ() perc = mq.MQPercentage() print("MQ135 done") '''sys.stdout.write("\r") sys.stdout.write("\033[K") sys.stdout.write("LPG: %g ppm, CO: %g ppm, Smoke: %g ppm" % (perc["GAS_LPG"], perc["CO"], perc["SMOKE"])) sys.stdout.write("\n") sys.stdout.flush()''' #################################################### ##############Pulse Sensor#######################DATA-PIN = 0(analog) p = Pulsesensor() p.startAsyncBPM() while True: #bpm = p.BPM bpm = random.randint(50,70) if bpm > 0: #print("BPM: %d" % bpm) p.stopAsyncBPM() break else: #print("No Heartbeat found") time.sleep(1) print("Pulse done") ###################################### ###################GPS#################### gps = GPSget() ######################################### final_ret["ambient_temp"] = temperature final_ret["humidity"] = humidity final_ret["body_temp"] = body_temperature final_ret["LPG"] = perc["GAS_LPG"] final_ret["CO"] = perc["CO"] final_ret["Smoke"] = perc["SMOKE"] final_ret["Pulse"] = int(bpm) final_ret["loc_lat"] = gps[0] final_ret["loc_lng"] = gps[1] return final_ret
def pulse_sensor(): p = Pulsesensor() p.startAsyncBPM() try: while True: bpm = p.BPM if bpm > 0: print("BPM: %d" % bpm) else: print("No Heartbeat found") time.sleep(1) except: p.stopAsyncBPM() return data
def pulse(): global BPM global exit p = Pulsesensor() p.startAsyncBPM() while exit: BPM = p.BPM if BPM > 0: print("BPM: %d" % BPM) else: print("No Heartbeat found") time.sleep(1) p.stopAsyncBPM() print("pulse finished")
def readHeartBeat(): p = Pulsesensor() p.startAsyncBPM() try: while True: # print(p.channel); # print(p.adc); bpm = p.BPM if bpm > 0: print(bpm) else: print("-1") time.sleep(1) except: p.stopAsyncBPM()
def updateBPM(self): self.bpmText.set_text("Test") p = Pulsesensor() p.startAsyncBPM() try: while True: bpm = p.BPM self.bpmText.set_text(str(int(bpm)) + " bpm") if bpm > 0: if bpm > 150: self.bpmText.modify_fg(Gtk.StateType.NORMAL, Gdk.Color(65535, 13535, 15535)) self.messages.set_text("HIGH HEARTRATE") elif bpm > 90: self.bpmText.modify_fg(Gtk.StateType.NORMAL, Gdk.Color(65535, 33535, 15535)) else: self.bpmText.modify_fg(Gtk.StateType.NORMAL, Gdk.Color(0, 0, 0)) else: self.bpmText.set_text("-") time.sleep(1) except: p.stopAsyncBPM()
from pulsesensor import Pulsesensor import time p = Pulsesensor() p.startAsyncBPM() try: while True: bpm = p.BPM if bpm > 0: print("BPM: %d" % bpm) else: print("BPM: %d" %bpm) print("No Heartbeat found") time.sleep(1) except: p.stopAsyncBPM()
def read_word_2c(adr): val = read_word(adr) if (val >= 0x8000): return -((65535 - val) + 1) else: return val def dist(a,b): return math.sqrt((a*a)+(b*b)) def get_y_rotation(x,y,z): radians = math.atan2(x, dist(y,z)) return -math.degrees(radians) def get_x_rotation(x,y,z): radians = math.atan2(y, dist(x,z)) return math.degrees(radians) bus = smbus.SMBus(1) address = 0x68 #MPU6050 I2C adresi #MPU6050 ilk calistiginda uyku modunda oldugundan, calistirmak icin asagidaki komutu veriyoruz: bus.write_byte_data(address, power_mgmt_1, 0) while True: time.sleep(0.1) #Jiroskop register'larini oku gyro_xout = read_word_2c(0x43) gyro_yout = read_word_2c(0x45) gyro_zout = read_word_2c(0x47) print "Jiroskop X : ", gyro_xout, " olcekli: ", (gyro_xout / 131) print "Jiroskop Y : ", gyro_yout, " olcekli: ", (gyro_yout / 131) print "Jiroskop Z: ", gyro_zout, " olcekli: ", (gyro_zout / 131) #Ivmeolcer register'larini oku accel_xout = read_word_2c(0x3b) accel_yout = read_word_2c(0x3d) accel_zout = read_word_2c(0x3f) accel_xout_scaled = accel_xout / 16384.0 accel_yout_scaled = accel_yout / 16384.0 accel_zout_scaled = accel_zout / 16384.0 print "Ivmeolcer X: ", accel_xout, " olcekli: ", accel_xout_scaled print "Ivmeolcer Y: ", accel_yout, " olcekli: ", accel_yout_scaled print "Ivmeolcer Z: ", accel_zout, " olcekli: ", accel_zout_scaled print "X dondurme: " , get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled) print "Y dondurme: " , get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled) time.sleep(0.5) # **************************************************************************************** # MCP3008 ADC KODU NABIZ ÖLÇER İÇİN (MCP3008.PY) # *************************************************************************************** from spidev import SpiDev class MCP3008: def __init__(self, bus = 0, device = 0): self.bus, self.device = bus, device self.spi = SpiDev() self.open() def open(self): self.spi.open(self.bus, self.device) def read(self, channel = 0): self.spi.max_speed_hz = 1000000 adc = self.spi.xfer2([1, (8 + channel) << 4, 0]) data = ((adc[1] & 3) << 8) + adc[2] return data def close(self): self.spi.close() # ***************************************************************************** # NABIZ ÖLÇERİ DİJİTALE DÖNÜŞTÜREN ALGORİTMA (PULSESENSOR.PY) # ****************************************************************************** import time import threading from MCP3008 import MCP3008 class Pulsesensor: def __init__(self, channel = 0, bus = 0, device = 0): self.channel = channel self.BPM = 0 self.adc = MCP3008(bus, device) def getBPMLoop(self): # init variables rate = [0] * 10 # array to hold last 10 IBI values sampleCounter = 0 # used to determine pulse timing lastBeatTime = 0 # used to find IBI P = 512 # used to find peak in pulse wave, seeded T = 512 # used to find trough in pulse wave, seeded thresh = 525 # used to find instant moment of heart beat, seeded amp = 100 # used to hold amplitude of pulse waveform, seeded firstBeat = True # used to seed rate array so we startup with reasonable BPM secondBeat = False # used to seed rate array so we startup with reasonable BPM IBI = 600 # int that holds the time interval between beats! Must be seeded! Pulse = False # "True" when User's live heartbeat is detected. "False" when not a "live beat". lastTime = int(time.time()*1000) while not self.thread.stopped: Signal = self.adc.read(self.channel) currentTime = int(time.time()*1000) sampleCounter += currentTime - lastTime lastTime = currentTime N = sampleCounter - lastBeatTime # find the peak and trough of the pulse wave if Signal < thresh and N > (IBI/5.0)*3: # avoid dichrotic noise by waiting 3/5 of last IBI if Signal < T: # T is the trough T = Signal # keep track of lowest point in pulse wave if Signal > thresh and Signal > P: P = Signal # signal surges up in value every time there is a pulse if N > 250: # avoid high frequency noise if Signal > thresh and Pulse == False and N > (IBI/5.0)*3: Pulse = True # set the Pulse flag when we think there is a pulse IBI = sampleCounter - lastBeatTime # measure time between beats in mS lastBeatTime = sampleCounter # keep track of time for next pulse if secondBeat: # if this is the second beat, if secondBeat == TRUE secondBeat = False; # clear secondBeat flag for i in range(len(rate)): # seed the running total to get a realisitic BPM at startup rate[i] = IBI if firstBeat: # if it's the first time we found a beat, if firstBeat == TRUE firstBeat = False; # clear firstBeat flag secondBeat = True; # set the second beat flag continue # keep a running total of the last 10 IBI values rate[:-1] = rate[1:] # shift data in the rate array rate[-1] = IBI # add the latest IBI to the rate array runningTotal = sum(rate) # add upp oldest IBI values runningTotal /= len(rate) # average the IBI values self.BPM = 60000/runningTotal # how many beats can fit into a minute? that's BPM! if Signal < thresh and Pulse == True: # when the values are going down, the beat is over Pulse = False # reset the Pulse flag so we can do it again amp = P - T # get amplitude of the pulse wave thresh = amp/2 + T # set thresh at 50% of the amplitude P = thresh # reset these for next time T = thresh if N > 2500: # if 2.5 seconds go by without a beat thresh = 512 # set thresh default P = 512 # set P default T = 512 # set T default lastBeatTime = sampleCounter # bring the lastBeatTime up to date firstBeat = True # set these to avoid noise secondBeat = False # when we get the heartbeat back self.BPM = 0 time.sleep(0.005) # Start getBPMLoop routine which saves the BPM in its variable def startAsyncBPM(self): self.thread = threading.Thread(target=self.getBPMLoop) self.thread.stopped = False self.thread.start() return # Stop the routine def stopAsyncBPM(self): self.thread.stopped = True self.BPM = 0 return # *************************************************************************************************** # NABIZ SENSÖRÜNDEKİ BİLGİYİ TERMİNALDE GÖSTEREN KOD (EXAMPLE.PY) # ******************************************************************************************** from pulsesensor import Pulsesensor import time import subprocess p = Pulsesensor() p.startAsyncBPM() try: while True: bpm = p.BPM if bpm > 0: print("BPM: %d" % bpm) else: print("No Heartbeat found") time.sleep(1) except: p.stopAsyncBPM()
help="The port the OSC server is listening on") args = parser.parse_args() # client = udp_client.SimpleUDPClient(args.ip, args.port) client = udp_client.UDPClient(args.ip, args.port) # msg.add_arg(4.0) # # Add 4 messages in the bundle, each with more arguments. # bundle.add_content(msg.build()) # print("\n\nargs\n", bundle.add_content) # print("\n\n") # bundle = bundle.build() # You can now send it via a client as described in other examples. ## set up pulse sensor p = Pulsesensor() p.startAsyncBPM() p2 = Pulsesensor(channel=1) p2.startAsyncBPM() ## setup neo pixels pixels = neopixel.NeoPixel(board.D18, 8) ## Regular led led_pin = 21 # Initializing the GPIO pin 21 for LED hrm_pin = 26 GPIO.setmode(GPIO.BCM) # We are using the BCM pin numbering GPIO.setup(led_pin, GPIO.OUT) # Declaring pin 21 as output pin GPIO.setup(hrm_pin, GPIO.IN)
ts = generateTimestamp() basePath = '/home/pi/bluetooth_pi_2-master/little_blue_pi/files' pathName = basePath + '/' + ts os.mkdir(pathName) baseFileName = ts fileName = baseFileName fullPath = pathName + '/' + fileName + '.csv' writeFile(fullPath) lines = '' p = Pulsesensor() # p.startAsyncBPM() threading.Thread(target=signal_user_input).start() try: while True: p.getBPMLoop() bpm = p.BPM dataTS = generateTimestamp() if os.path.getsize(fullPath) > 39990000: fileName = generateTimestamp() fullPath = pathName + '/' + fileName + '.csv' writeFile(fullPath) appendToFile(fullPath, dataTS, bpm, annotation) annotation = ''
from pulsesensor import Pulsesensor import time p = Pulsesensor() p.startAsyncBPM() try: while True: bpm = p.BPM if bpm > 0: print("BPM: %d" % bpm) else: print("No Heartbeat found") time.sleep(1) except: p.stopAsyncBPM()
def __init__(self): self.p = Pulsesensor()
print ("CONNECTED") ''' BLUETOOTH CONNECTION ESTABLISHED ''' ''' Setup ''' threshold = 1015 # Threshold value for pressure to count for step. step = 0 # Global step count state = "STANDING" # Global User State cap = MPR121.MPR121() # Initiating Capacitive Touch cap.begin() p = Pulsesensor() # Initiating Heart Rate Sensor p.startAsyncBPM() ''' LOOP ''' while True: # Flag for Developer print("Loop Begins") adc = MCP3008(0, 0) # Channel 1 for velostat reading. velostat = adc.read(1) # Count the number of steps and the find the state.
from pulsesensor import Pulsesensor import time import threading import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(13, GPIO.OUT) GPIO.setup(12, GPIO.OUT) GPIO.setup(26, GPIO.OUT) p = Pulsesensor() class ThreadPulse: def __init__(self): self.Raw = 0 self.PulseRate = 0 def pulse_loop(self): p.startAsyncBPM() while not self.thread.stopped: self.PulseRate = p.BPM self.Raw = p.RAW_DATA #print(self.Raw) time.sleep(1) p.stopAsyncBPM() def start_thread(self): self.thread = threading.Thread(target=self.pulse_loop) self.thread.stopped = False GPIO.output(13, 1)
from pulsesensor import Pulsesensor #import pulse sensor library import time #import time library p = Pulsesensor() #store pulse sensor in variable p (tidies code up) p.startAsyncBPM() #starts the BPM (beats per minute) monitoring try: #allows you to cancel with Ctrl-C while True: #loops forever bpm = p.BPM #stores BPM in bpm variable if bpm > 0: #checks for pulse print("BPM: " + str(bpm)) #this prints the BPM to screen else: #this happens if no beats per minute register print("No Heartbeat found") time.sleep(1) #waits for 1 second except: p.stopAsyncBPM() #stops BPM monitoring if Ctrl-C is pressed
import os from math import fabs #sys.path.append('/home/pi/Adafruit_Python_MCP3008/examples/') from pulsesensor import Pulsesensor from imutils.video import VideoStream from imutils import face_utils import numpy as np import argparse import imutils import time import dlib import cv2 import RPi.GPIO as GPIO from time import sleep #---------------------------CONFIGURATION FOR HEARTBEAT SENSOR-------------------- p = Pulsesensor() #The class that reads the value from ADC p.startAsyncBPM() #Start reading the value periodically in a different thread buzzer_pin = 18 #Pin number to which the buzzer is connected [BCM,Raspberry Pi Model B] led_pin = 14 #Pin number to which the LED light is connected. It remains on when the eyes are closed min_bpm = 50 #Minimum BPM threshold below which the buzzer will sound max_bpm = 200 #mum BPM threshold above which the buzzer will sound #This parameters filter noise value by accepting fixed number of BPM values #which exists within a valid range last_bpm = 0 #The Last BPM read from the Sensor class bpm_in_range = 0 #Number of BPM value detected which is within the range bpm_max_val = 3 #Number of consecutive BPM values that must exist within a valid range #Maximum difference between last value read and current value read range_val = 20 #Maximum difference between last and current BPM value that validates range processing = False #The detected BPM value was obtained while calculating BPM or from the sensor #---------------------------CONFIGURATION FOR HEARTBEAT SENSOR-------------------- GPIO.setmode(GPIO.BCM)