I want to get ppg value to max30105.
But i can't find ppg value in code.
Just i find heart rate.
How to get ppg value?
#!/usr/bin/env python
# NOTE! This code should not be used for medical diagnosis. It's
# for fun/novelty use only, so bear that in mind while using it.
import time
from max30105 import MAX30105, HeartRate
max30105 = MAX30105()
max30105.setup(leds_enable=2)
max30105.set_led_pulse_amplitude(1, 0.2)
max30105.set_led_pulse_amplitude(2, 12.5)
max30105.set_led_pulse_amplitude(3, 0)
max30105.set_slot_mode(1, 'red')
max30105.set_slot_mode(2, 'ir')
max30105.set_slot_mode(3, 'off')
max30105.set_slot_mode(4, 'off')
def display_heartrate(beat, bpm, avg_bpm):
print("{} BPM: {:.2f} AVG: {:.2f}".format("<3" if beat else " ",
bpm, avg_bpm))
hr = HeartRate(max30105)
print("""
NOTE! This code should not be used for medical diagnosis. It's
for fun/novelty use only, so bear that in mind while using it.
This example shows a readout of your heart rate in BPM (beats per
minute) and heartbeats detected using a heart emoticon <3.
It's best to hold the sensor against your fingertip (the fleshy side)
using a piece of wire or a rubber band looped through the mounting
holes on the breakout, as the sensor is very sensitive to small
movements and it's hard to hold your finger against the sensor with
even pressure.
If you're using your MAX30105 Breakout with Breakout Garden, then
we'd recommend using one of our Breakout Garden Extender Kits with
some female-to-female jumper jerky.
https://shop.pimoroni.com/products/breakout-garden-extender-kit
""")
delay = 10
print("Starting readings in {} seconds...\n".format(delay))
time.sleep(delay)
try:
hr.on_beat(display_heartrate, average_over=4)
except KeyboardInterrupt:
pass
In this code, can get heartrate.
But, I want get PPG value.
I using this library.
https://github.com/pimoroni/max30105-python
I've been analyzing library.
Thanks.
Related
I have some troubles handling interruptions with my Raspberry Pi 4, using Python.
I have a DC motor with an encoder , I would like to make a speed control of this motor. But I have some issues with reading the encoder values with my Raspberry.
Here is the code I run :
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
HallA = 5 # GPIO pin for Hall A
HallB = 6 # GPIO pin for Hall B
GPIO.setup(HallA, GPIO.IN) #set up the input
GPIO.setup(HallB, GPIO.IN)
incmot = 0 # set up the counter
def encodeur_inc(channel) : #function of the interruption
B = GPIO.input(HallB) #read the second signal
global incmot
if B == 1 :
incmot = incmot +1
else :
incmot = incmot -1
GPIO.add_event_detect(HallA, GPIO.RISING, callback = encodeur_inc) #setting up the interruption
try :
while True :
print(incmot)
except :
GPIO.cleanup()
The problem is that, for the same number of revolutions, I get a different number of pulses each time (from 480 to 650 pulses per revolution, while the manufacturer announces 690). I tried to identify where the problem could come from:
It does not come from the encoder, I displayed on an oscilloscope the signals of the two outputs of the encoder, they were indeed phase quadrature rectangle waves
The raspberry does not miss interrupts, by rising a pin high when entering the interrupt then low when leaving, I displayed on the oscilloscope the inputs and outputs of the interrupt.
GPIO.output(20, GPIO.HIGH) #at the beginning of the function
GPIO.output(20, GPIO.LOW) #at the end of the function
So I don't see where the inconsistencies I see could come from. I you have any clue that could help me don't hesitate.
Thanks for your help !
Thanks to #quamrana, I understood where the problem came from. When the program was interrupted, the time taken to execute the interrupt was variable and, going clockwise, Hall B could be at 1 or 0, instead of 1 all the time.
To get around this problem, using a D latch allows Python time to execute the interrupt and correctly read whether the engine is moving forward or backward. Hall A is the clock of the latch and Hall B is the data.
I want to detect multiple type of flag patterns from the Stock market the first one that I want to identify is the Bull Flag Pattern. I have tried some formula's but they all missed the point and gave me lot of stock name which did not have the pattern.
In the recent way I did
find the continuous rise and then check that the following values are lying between the mean of the continuous rise.
I'm also wondering if I plot this data in graph using matplot or plotly and then apply machine learning to it will that be a solution or not.
The code to get the data is as below
from pprint import print
from nsepy import get_history
from datetime import date
from datetime import datetime, timedelta
import matplotlib
from nsetools import Nse
nse = Nse()
old_date=date.today()-timedelta(days=30)
for stock in nse.get_stock_codes():
print("Stock",stock)
stock_data = get_history(symbol=stock,
start=date(old_date.year,old_date.month,old_date.day),
end=date(datetime.now().year,datetime.now().month,datetime.now().day)))
Any help will be useful. Thanks in advance.
Bull flag pattern matcher for your pattern day trading code
Pseudocode:
Get the difference between the min() and max() close price over the last n=20 timeperiods, here called flag_width. Get the difference between the min() and max() close price over the last m=30 timeperiods, here called poll_height.
When the relative gain percentage between poll_height and flag_width is over some massive threshold like (thresh=0.90) then you can say there is a tight flag in the last n=20 timeperiods, and a tall flag pole on period -20 to -30.
Another name for this could be: "price data elbow" or "hokey stick shape".
macd does a kind of 12,26 variation on this approach, but using 9,12,26 day exponential moving average.
Code Jist:
#movingMax returns the maximum price over the last t=20 timeperiods
highest_close_of_flag = movingMax(closeVector, 20);
lowest_close_of_flag = movingMin(closeVector, 20);
#movingMin returns the minimum price over the last t=20 timeperiods
highest_close_of_poll = movingMax(closeVector, 30);
lowest_close_of_poll = movingMin(closeVector, 30);
#We want poll to be much longer than the flag is wide.
flag_width = highest_close_of_flag - lowest_close_of_flag;
poll_height = highest_close_of_poll - lowest_close_of_poll;
# ((new-old)/old) yields percentage gain between.
bull_flag = (poll_height - flag_width ) ./ flag_width;
#Filter out bull flags who's flagpole tops go too high over the flapping flag
bull_flag -= (highest_close_of_poll -highest_close_of_flag ) ./ highest_close_of_flag;
thresh = 0.9;
bull_flag_trigger = (bull_flag > thresh);
bull_flag_trigger interpretation
A whale (relatively speaking) bought a green candle flagpole by aggressively hitting bids, or covering a prior naked short position via market options from timeperiod -30 to -20. The fish fought over the new higher price in a narrow horizontal band from timeperiod -20 to 0 at the top of the range.
The bull flag pattern is one of the most popular false flags, because it's so good, which means the other end of your trade spent money to paint that structure, so that you would happily scoop up their unwanted distribution of scrip at a much higher price, and now you're bag-holding a scrip at an unrealistic price that nobody wants to buy. You are playing a game of Chess/Checkers against very strong AI designed by corporations who pull trillions of dollars per year out of this constant sum game, and your losses are their gains make your time.
Drawbacks to this approach:
This approach doesn't take into account other desirable properties of a bull flags, such as straightness of the poll, high volume in the poll or flag, gain in trading range in the poll, the squareness/triangularness/resonant sloped-ness of the flag, or 10 other variations on what cause people with lots of money to a pattern day trade on appearance of this arbitrary structure. This is financial advice, you will lose all of your money to other people who can write better AI code in skyscrapers who get $1*10^9 annual pay packages in exchange for isolated alpha with math proofs and code demos.
Bull Flag Pattern is a pattern that is visible after plotting the chart. This pattern is hard to find at the data level.
According to me finding pattern in an image using Deep Learning(object detection) is a better choice. By doing so you can find other types of patterns also such as Bearish Flag, etc.
I am trying to make an LCD display to display both the current temperature and the humidity at the same time in different lines. I have a sample code as below. The problem is that when the temperature goes above say 50C, I want the humidity reading to stop as well. I have 2 thread running at the same time, reading from both sensors.
#all important imports are here
def main():
# Very simplified code, not actual.
tempP = Process(target=temperature)
humidP = Process(target=humidity)
tempP.start()
humidP.start()
def temperature():
while True:
#ADC printing to LCD code is here
temperatureReading = ADC.channel(0)
if temperatureReading > 50:
humidP.terminate() # Does not work, I still see the humidity on
the screen with overlapping characters
I have a MCP3008 connected to RPi and 2 x Force Sensitive Resistor - Square connected to the MCP3008. The sensors are laying side by side horisontal on my desk and I can read and print the data (0-100) from both sensors (sensor1 and sensor2) separately. I just can't come up with any idea of python code to detect when I touch sensor1 (left) and move my finger to sensor2 (right).
In addition I need to know how many milliseconds it takes from that I touch sensor1 until I lifted from sensor2.
from time import sleep
from gpiozero import MCP3008
sensor1 = MCP3008(1) # Pin 2 on the ADC
sensor2 = MCP3008(2) # Pin 3 on the ADC
# Read data from the ADC
def getData(readSensor):
value = readSensor
rawValue = value.value
return rawValue
while True:
print('Sensor1 = {0:.0f}'.format(getData(sensor1)*100))
print('Sensor2 = {0:.0f}'.format(getData(sensor2)*100))
print('')
sleep(0.1)
You are going to need to timestamp the events and then use the time stamps to determine what action to take. Something like the below might help you.
if getData(sensor1) > TOUCH_THRESHOLD:
sensor1LastPressedAt = time.time()
Do the same for sensor2 and compare the time stamps.
(TOUCH_THRESHOLD is the value that you measure to be someone touching the button)
I actually want to use this waterproof ultrasonic sensor DYP-ME007Y-PWM (http://hanjindata.lgnas.com:10000/myweb/P0400/P0400.pdf) on my raspberry PI Compute Module on a classic Raspbian OS. It has 4 pin's (gnd,Trig,Echo and 5V).
Here is my schematic:
Raspberry Pi | Sensor
GND | GND
5V | 5V
22 | Trig
23 | Echo
I've found some tutorials that explain how ultrasonic sensors works and mannage to have good results with other kind of ultrasonic sensors like this one for exemple (http://www.micropik.com/PDF/HCSR04.pdf)
Here is my code :
# Import required Python libraries
import time
import RPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_TRIGGER = 22
GPIO_ECHO = 23
print "Ultrasonic Measurement"
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# Allow module to settle
time.sleep(0.5)
# Send 10us pulse to trigger
while True:
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
# That was the distance there and back so halve the value
distance = (elapsed * 34000)/2
print "Distance : %.1f" % distance
time.sleep(0.05)
# Reset GPIO settings
GPIO.cleanup()
I doesn't work, i obtain always the same output whatever i do with my sensor
Does anybody has alreeady play with this sensor ? As you can see, the datasheet is pretty ligth, so maybe you will see something my poor electronics skills have missed
Greetings !
You are expecting GPIO_ECHO to be 1 from the start. According to the documentation it is first 0, then 1, and then back to
1.
Maybe
while GPIO.input(GPIO_ECHO)==0:
# some short sleep might be better
pass
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
pass
while GPIO.input(GPIO_ECHO)==0:
pass
stop = time.time()
There are methods available for detecting rising edge and falling edge, see for example raspi.tv arcticle. It might be better to use those methods.
According to:
https://forum.arduino.cc/index.php?topic=153700.30
the sensor is quite sensitive to getting enough power - Check that your 5V doesn't drop too much.
Also the Raspberry Pi GPIO pins are 3V3 - They might not like the output from the sensor (which presumably is 5V), and the sensor might not trigger on the 3V3 output from the Raspberry pi.