Qwiic_MAX3010x_Py¶
Python package for the SparkFun Photodetector Breakout - MAX30101 (Qwiic)
This package is a port of the existing SparkFun MAX3010x Sensor Arduino Library
This package can be used in conjunction with the overall SparkFun qwiic Python Package
New to qwiic? Take a look at the entire SparkFun qwiic ecosystem.
Supported Platforms¶
The qwiic Python package current supports the following platforms:
Dependencies¶
This driver package depends on the qwiic I2C driver: Qwiic_I2C_Py
Documentation¶
The SparkFun qwiic Max3010x module documentation is hosted at ReadTheDocs
Installation¶
PyPi Installation¶
This repository is hosted on PyPi as the sparkfun-qwiic-max3010x package. On systems that support PyPi installation via pip, this library is installed using the following commands
For all users (note: the user must have sudo privileges):
sudo pip install sparkfun-qwiic-max3010x
For the current user:
pip install sparkfun_qwiic_max3010x
Local Installation¶
To install, make sure the setuptools package is installed on the system.
Direct installation at the command line:
python setup.py install
To build a package for use with pip:
python setup.py sdist
A package file is built and placed in a subdirectory called dist. This package file can be installed using pip.
cd dist
pip install sparkfun_max3010x-<version>.tar.gz
Example Use¶
See the examples directory for more detailed use examples.
from __future__ import print_function
import qwiic_max3010x
import time
import sys
def runExample():
print("\nSparkFun MAX3010x Photodetector Sensor - Example 1\n")
sensor = qwiic_max3010x.QwiicMax3010x()
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
if sensor.setup() == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
while True:
print(\
'R[', sensor.getRed() , '] \t'\
'IR[', sensor.getIR() , '] \t'\
'G[', sensor.getGreen() , ']'\
)
time.sleep(0.1)
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 1")
sys.exit(0)
Table of Contents¶
API Reference¶
qwiic_max3010x¶
Python module for the [SparkFun Photodetector Breakout - MAX30101 (Qwiic)](https://www.sparkfun.com/products/16474)
This python package is a port of the existing [SparkFun MAX3010x Sensor Arduino Library](https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library)
This package can be used in conjunction with the overall [SparkFun qwiic Python Package](https://github.com/sparkfun/Qwiic_Py)
New to qwiic? Take a look at the entire [SparkFun qwiic ecosystem](https://www.sparkfun.com/qwiic).
-
class
qwiic_max3010x.
QwiicMax3010x
(address=None, i2c_driver=None)[source]¶ Parameters: - address – The I2C address to use for the device. If not provided, the default address is used.
- i2c_driver – An existing i2c driver object. If not provided a driver object is created.
Returns: The QwiicMax3010x device object.
Return type: Object
-
available
()[source]¶ Tell caller how many samples are available
Returns: number of samples available Return type: integer
-
begin
()[source]¶ Initialize the operation of the Qwiic MAX3010x module
Returns: Returns true of the initializtion was successful, otherwise False. Return type: bool
-
bit_mask
(reg, mask, thing)[source]¶ Given a register, read it, mask it, and then set the thing
Parameters: - reg – the register you’d like to effect
- mask – the mask needed to zero-out the portion of the register we’re interested in
- thing – the thing we are affecting aka the control bits of the register
Returns: Returns true of the register write was successful, otherwise False.
Return type: bool
-
check
()[source]¶ Polls the sensor for new data Call regularly If new data is available, it updates the head and tail in the main lists of data
Returns: number of new samples obtained Return type: integer
-
checkForBeat
(sample)[source]¶ Wrapper function to allow access to function within supporting heart_rate.py file
Parameters: sample – IR sample Returns: True if a beat is detected, otherwise False Return type: boolean
-
connected
¶ Determine if a device is conntected to the system..
Returns: True if the device is connected, otherwise False. Return type: bool
-
enableSlot
(slotNumber, device)[source]¶ Given a slot number assign a thing to it Devices are SLOT_RED_LED or SLOT_RED_PILOT (proximity) Assigning a SLOT_RED_LED will pulse LED Assigning a SLOT_RED_PILOT will ??
Parameters: - slotNumber – slot number as int 1,2,3,4
- device – which device (aka led) you’d like to assign to the given slot
Returns: Whether or not the configuration write was successful
Return type: bool
-
getFIFOGreen
()[source]¶ Report the next Green value in the FIFO
Returns: the next Green value in the FIFO Return type: integer
-
getFIFOIR
()[source]¶ Report the next IR value in the FIFO
Returns: the next IR value in the FIFO Return type: integer
-
getFIFORed
()[source]¶ Report the next Red value in the FIFO
Returns: the next Red value in the FIFO Return type: integer
-
getGreen
()[source]¶ Report the most recent GREEN value
Returns: value of GREEN light sensor from most recent sample Return type: integer
-
getINT1
()[source]¶ Returns the value of the INTSTAT1 Register
Returns: value of the INTSTAT1 Register Return type: integer
-
getINT2
()[source]¶ Returns the value of the INTSTAT2 Register
Returns: value of the INTSTAT2 Register Return type: integer
-
getIR
()[source]¶ Report the most recent IR value
Returns: value of IR light sensor from most recent sample Return type: integer
-
getReadPointer
()[source]¶ Read the FIFO Read Pointer
Returns: FIFO read pointer value Return type: integer
-
getRed
()[source]¶ Report the most recent red value
Returns: value of RED light sensor from most recent sample Return type: integer
-
getRevisionID
()[source]¶ Report Revision ID from current variable in this class
Returns: Revision ID Return type: integer
-
getWritePointer
()[source]¶ Read the FIFO Write Pointer
Returns: FIFO write pointer value Return type: integer
-
is_connected
()[source]¶ Determine if a device is conntected to the system..
Returns: True if the device is connected, otherwise False. Return type: bool
-
millis
()[source]¶ Returns the current time in milliseconds
Returns: Returns current system time in milliseconds Return type: int32_t
-
readRevisionID
()[source]¶ Report Revision ID from the sensor
Returns: Revision ID Return type: integer
-
safeCheck
(maxTimeToCheck)[source]¶ Check for new data but give up after a certain amount of time Returns true if new data was found Returns false if new data was not found
Parameters: maxTimeToCheck – milliseconds to timeout Returns: True if new data was found, otherwise False Return type: boolean
-
setADCRange
(adcRange)[source]¶ Set adcRange: one of MAX30105_ADCRANGE_2048, _4096, _8192, _16384
Parameters: adcRange – MAX30105_ADCRANGE_2048, _4096, _8192, _16384 Returns: no return value
-
setFIFOAlmostFull
(numberOfSamples)[source]¶ Set number of samples to trigger the almost full interrupt
Parameters: numberOfSamples – default is 32 samples. Note it’s reverse (0x00 is 32 samples, 0x0F is 17 samples) Returns: no return value
-
setFIFOAverage
(numberOfSamples)[source]¶ Set sample average
Parameters: numberOfSamples – MAX30105_SAMPLEAVG_1, _2, _4, _8, _16, _32 Returns: no return value
-
setLEDMode
(mode)[source]¶ Set which LEDs are used for sampling - Red only, RED+IR only, or custom
Parameters: mode – Red only, RED+IR only, or custom Returns: no return value
-
setProximityThreshold
(threshMSB)[source]¶ Set the IR ADC count that will trigger the beginning of particle-sensing mode. The threshMSB signifies only the 8 most significant-bits of the ADC count. Note, this is specific to the MAX30105, and not included in the MAX30101
Parameters: threshMSB – threshold of ADC count to cause trigger Returns: no return value
-
setPulseAmplitudeGreen
(amplitude)[source]¶ Set pulse amplitude (mA) of green LED
Parameters: amplitude – 0x00 = 0mA, 0x7F = 25.4mA, 0xFF = 50mA (typical) Returns: no return value
-
setPulseAmplitudeIR
(amplitude)[source]¶ Set pulse amplitude (mA) of IR LED
Parameters: amplitude – 0x00 = 0mA, 0x7F = 25.4mA, 0xFF = 50mA (typical) Returns: no return value
-
setPulseAmplitudeProximity
(amplitude)[source]¶ Set pulse aplitude while in proximity mode (only MAX30105) Note, this is specific to the MAX30105, and not included in the MAX30101
Parameters: amplitude – amplitude Returns: no return value
-
setPulseAmplitudeRed
(amplitude)[source]¶ Set pulse amplitude (mA) of red LED
Parameters: amplitude – 0x00 = 0mA, 0x7F = 25.4mA, 0xFF = 50mA (typical) Returns: no return value
-
setPulseWidth
(pulseWidth)[source]¶ Set pulseWidth: one of MAX30105_PULSEWIDTH_69, _188, _215, _411
Parameters: pulseWidth – MAX30105_PULSEWIDTH_69, _188, _215, _411 Returns: no return value
-
setSampleRate
(sampleRate)[source]¶ Set sampleRate: one of MAX30105_SAMPLERATE_50, _100, _200, _400, _800, _1000, _1600, _3200
Parameters: sampleRate – MAX30105_SAMPLERATE_50, _100, _200, _400, _800, _1000, _1600, _3200 Returns: no return value
-
setup
(powerLevel=31, sampleAverage=4, ledMode=3, sampleRate=400, pulseWidth=411, adcRange=4096)[source]¶ Setup the MAX3010x with default or custom settings
Parameters: - powerLevel – 0x00 = 0mA, 0x7F = 25.4mA, 0xFF = 50mA
- sampleAverage – int, 1,2,4,8,16,32, default is 4
- ledMode – 1 = RED, 2=RED+IR , 3=RED+IR+GREEN
- sampleRate – 0-3200
- pulseWidth – 0-411 (microseconds)
- adcRange – 2048,4096,8192,16384
Returns: no return value
Basic Readings Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# ex1_Basic_Readings.py
#
# Simple example for the qwiic MAX3010x device
# Outputs all Red/IR/Green values.
#
#------------------------------------------------------------------------
#
# Written by Pete Lewis
# SparkFun Electronics, May 2020
#
# Based on code from the SparkFun MAX3010x Sensor Arduino Library
# https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
# By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
#
# This python library supports the SparkFun Electroncis qwiic
# qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
# board computers.
#
# More information on qwiic is at https://www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
# Example 1
#
from __future__ import print_function
import qwiic_max3010x
import time
import sys
def runExample():
print("\nSparkFun MAX3010x Photodetector - Example 1\n")
sensor = qwiic_max3010x.QwiicMax3010x()
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
if sensor.setup() == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
while True:
print(\
'R[', sensor.getRed() , '] \t'\
'IR[', sensor.getIR() , '] \t'\
'G[', sensor.getGreen() , ']'\
)
time.sleep(0.1)
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 1")
sys.exit(0)
|
Presence Sensing Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# ex2_Presence_Sensing.py
#
# Simple example for the qwiic MAX3010x device
# This takes an average reading at power up and if the reading changes more than 100,
# then print 'Something is there!'.
#
#------------------------------------------------------------------------
#
# Written by Pete Lewis
# SparkFun Electronics, May 2020
#
# Based on code from the SparkFun MAX3010x Sensor Arduino Library
# https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
# By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
#
# This python library supports the SparkFun Electroncis qwiic
# qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
# board computers.
#
# More information on qwiic is at https://www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
# Example 2
#
from __future__ import print_function
import qwiic_max3010x
import time
import sys
def millis():
return int(round(time.time() * 1000))
def runExample():
print("\nSparkFun MAX3010x Photodetector - Example 1\n")
sensor = qwiic_max3010x.QwiicMax3010x()
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
# Setup to sense up to 18 inches, max LED brightness
ledBrightness = 0xFF # Options: 0=Off to 255=50mA
sampleAverage = 4 # Options: 1, 2, 4, 8, 16, 32
ledMode = 2 # Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
sampleRate = 400 # Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
pulseWidth = 411 # Options: 69, 118, 215, 411
adcRange = 2048 # Options: 2048, 4096, 8192, 16384
if sensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange) == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
sensor.setPulseAmplitudeRed(0) # Turn off Red LED
sensor.setPulseAmplitudeGreen(0) # Turn off Green LED
samplesTaken = 0 # Counter for calculating the Hz or read rate
unblockedValue = 0 # Average IR at power up
startTime = 0 # Used to calculate measurement rate
# Take an average of IR readings at power up
unblockedValue = 0
for i in range(0,32):
unblockedValue += sensor.getIR() # Read the IR value
unblockedValue /= 32
startTime = millis()
while True:
samplesTaken += 1
IRSample = sensor.getIR()
hertz = samplesTaken / ((millis() - startTime) / 1000)
currentDelta = (IRSample - unblockedValue)
hertz = round(hertz, 2)
currentDelta = round(currentDelta, 2)
message = ' ' # blank message
if currentDelta > 100:
message = 'Something is there!'
print(\
'IR[', IRSample , '] \t',\
'Hz[', hertz , '] \t',\
'delta[', currentDelta, ']',\
message
)
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 2")
sys.exit(0)
|
Temperature Sense Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# ex3_Temperature_Sesnse.py
#
# Simple example for the qwiic MAX3010x device
# This demo outputs the onboard temperature sensor.
# The temp sensor is accurate to +/-1 C but
# has an astonishing precision of 0.0625 C.
#
#------------------------------------------------------------------------
#
# Written by Pete Lewis
# SparkFun Electronics, May 2020
#
# Based on code from the SparkFun MAX3010x Sensor Arduino Library
# https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
# By: Nathan Seidle @ SparkFun Electronics, October 2016
#
# This python library supports the SparkFun Electroncis qwiic
# qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
# board computers.
#
# More information on qwiic is at https://www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
# Example 3
#
from __future__ import print_function
import qwiic_max3010x
import time
import sys
def runExample():
print("\nSparkFun MAX3010x Photodetector - Example 3\n")
sensor = qwiic_max3010x.QwiicMax3010x()
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
# Setup Sensor
# The LEDs are very low power and won't affect the temp reading much but
# we will call setup() with LEDs off, to avoid any local heating (ledMode = 0)
if sensor.setup(ledMode = 0) == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
sensor.enableDIETEMPRDY() # Enable the temp ready interrupt. This is required.
while True:
temperature = sensor.readTemperature()
temperatureF = sensor.readTemperatureF()
temperature = round(temperature, 4)
temperatureF = round(temperatureF, 4)
print(\
'temperatureC[', temperature , '] \t',\
'temperatureF[', temperatureF , ']',\
)
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 3")
sys.exit(0)
|
Heartbeat Plotter Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# ex4_HeartBeat_Plotter.py
#
# Simple example for the qwiic MAX3010x device
# Shows the user's heart beat on a graphical plotter
# Using Matplotlib
# To learn more about plotting data in python check out this tutorial:
# https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/
# The example code below was built using the code from the previously mentioned tutorial.
# Thanks Shawn Hymel!
#
# Instructions:
# 1) Install MatplotLib (see below)
# 2) Connect sensor to system via qwiic cable
# 3) Attach sensor to your finger with a rubber band (see below)
# 4) Run this python example
# 5) Checkout the blips!
# 6) Feel the pulse on your neck and watch it mimic the blips
#
# It is best to attach the sensor to your finger using a rubber band or other tightening
# device. Humans are generally bad at applying constant pressure to a thing. When you
# press your finger against the sensor it varies enough to cause the blood in your
# finger to flow differently which causes the sensor readings to go wonky.
#
# MatplotLib install
# Install Dependencies
# Like any good Linux project, we need to install a number of dependencies and libraries
# in order to get matplotlib to run properly. Make sure you have an Internet connection
# and in a terminal, enter the following commands. You may need to wait several minutes
# while the various packages are downloaded and installed.
#
# sudo apt-get update
# sudo apt-get install libatlas3-base libffi-dev at-spi2-core python3-gi-cairo
# sudo pip3 install cairocffi
# sudo pip3 install matplotlib
#
#------------------------------------------------------------------------
#
# Written by Pete Lewis
# SparkFun Electronics, May 2020
#
# Based on code from the SparkFun MAX3010x Sensor Arduino Library
# https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
# By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
#
# This python library supports the SparkFun Electroncis qwiic
# qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
# board computers.
#
# More information on qwiic is at https://www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
# Example 4
#
from __future__ import print_function
import qwiic_max3010x
import time
import sys
sensor = qwiic_max3010x.QwiicMax3010x()
#Plotter Stuff
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xlen= 100 #sample number, increments and is used for labeling x axis in plot
xs = list(range(0,xlen))
ys = [0]*xlen
line, = ax.plot(xs, ys)
plt.title('Heartbeat over time')
plt.ylabel('IR Value')
# This function is called periodically from FuncAnimation
def animate(i, ys):
# Read IR from MAX3010x
ir = sensor.getIR()
ys.append(ir)
ys = ys[-xlen:]
line.set_ydata(ys)
ax.set_ylim([min(ys),max(ys)])
return line,
def runExample():
print("\nSparkFun MAX3010x Photodetector - Example 4\n")
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
# Setup to sensor
ledBrightness = 0x1F # Options: 0=Off to 255=50mA
sampleAverage = 8 # Options: 1, 2, 4, 8, 16, 32
ledMode = 3 # Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
sampleRate = 100 # Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
pulseWidth = 411 # Options: 69, 118, 215, 411
adcRange = 4096 # Options: 2048, 4096, 8192, 16384
if sensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange) == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(ys,), interval=10, blit=True)
plt.show()
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 4")
sys.exit(0)
|
Heartrate Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# ex5_HeartRate.py
#
# Simple example for the qwiic MAX3010x device
# This is a demo to show the reading of heart rate or beats per minute (BPM) using
# a Penpheral Beat Amplitude (PBA) algorithm.
#
# It is best to attach the sensor to your finger using a rubber band or other tightening
# device. Humans are generally bad at applying constant pressure to a thing. When you
# press your finger against the sensor it varies enough to cause the blood in your
# finger to flow differently which causes the sensor readings to go wonky.
#
#------------------------------------------------------------------------
#
# Written by Pete Lewis
# SparkFun Electronics, May 2020
#
# Based on code from the SparkFun MAX3010x Sensor Arduino Library
# https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
# By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
#
# This python library supports the SparkFun Electroncis qwiic
# qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
# board computers.
#
# More information on qwiic is at https://www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
# Example 5
#
from __future__ import print_function
import qwiic_max3010x
import time
import sys
def millis():
return int(round(time.time() * 1000))
def runExample():
print("\nSparkFun MAX3010x Photodetector - Example 5\n")
sensor = qwiic_max3010x.QwiicMax3010x()
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
print("Place your index finger on the sensor with steady pressure.")
if sensor.setup() == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
sensor.setPulseAmplitudeRed(0x0A) # Turn Red LED to low to indicate sensor is running
sensor.setPulseAmplitudeGreen(0) # Turn off Green LED
RATE_SIZE = 4 # Increase this for more averaging. 4 is good.
rates = list(range(RATE_SIZE)) # list of heart rates
rateSpot = 0
lastBeat = 0 # Time at which the last beat occurred
beatsPerMinute = 0.00
beatAvg = 0
samplesTaken = 0 # Counter for calculating the Hz or read rate
startTime = millis() # Used to calculate measurement rate
while True:
irValue = sensor.getIR()
samplesTaken += 1
if sensor.checkForBeat(irValue) == True:
# We sensed a beat!
print('BEAT')
delta = ( millis() - lastBeat )
lastBeat = millis()
beatsPerMinute = 60 / (delta / 1000.0)
beatsPerMinute = round(beatsPerMinute,1)
if beatsPerMinute < 255 and beatsPerMinute > 20:
rateSpot += 1
rateSpot %= RATE_SIZE # Wrap variable
rates[rateSpot] = beatsPerMinute # Store this reading in the array
# Take average of readings
beatAvg = 0
for x in range(0, RATE_SIZE):
beatAvg += rates[x]
beatAvg /= RATE_SIZE
beatAvg = round(beatAvg)
Hz = round(float(samplesTaken) / ( ( millis() - startTime ) / 1000.0 ) , 2)
if (samplesTaken % 200 ) == 0:
print(\
'IR=', irValue , ' \t',\
'BPM=', beatsPerMinute , '\t',\
#'DCE', getDCE() , '\t',\
'Avg=', beatAvg , '\t',\
'Hz=', Hz, \
)
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 5")
sys.exit(0)
|
FIFO Readings Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# ex6_FIFO_Readings.py
#
# Simple example for the qwiic MAX3010x device
# Outputs all Red/IR/Green values at about 5Hz by polling the FIFO
# Note, the Hz is slowed down by printing to the python terminal,
# It can be drmatically speed up if printing is omitted or intermittent
#
#------------------------------------------------------------------------
#
# Written by Pete Lewis
# SparkFun Electronics, May 2020
#
# Based on code from the SparkFun MAX3010x Sensor Arduino Library
# https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library
# By: Nathan Seidle @ SparkFun Electronics, October 2nd, 2016
#
# This python library supports the SparkFun Electroncis qwiic
# qwiic sensor/board ecosystem on a Raspberry Pi (and compatable) single
# board computers.
#
# More information on qwiic is at https://www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2019 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
# Example 6
#
from __future__ import print_function
import qwiic_max3010x
import time
import sys
def millis():
return int(round(time.time() * 1000))
def runExample():
print("\nSparkFun MAX3010x Photodetector - Example 6\n")
sensor = qwiic_max3010x.QwiicMax3010x()
if sensor.begin() == False:
print("The Qwiic MAX3010x device isn't connected to the system. Please check your connection", \
file=sys.stderr)
return
else:
print("The Qwiic MAX3010x is connected.")
# Setup to sense up to 18 inches, max LED brightness
ledBrightness = 0xFF # Options: 0=Off to 255=50mA
sampleAverage = 4 # Options: 1, 2, 4, 8, 16, 32
ledMode = 2 # Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
sampleRate = 400 # Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
pulseWidth = 411 # Options: 69, 118, 215, 411
adcRange = 2048 # Options: 2048, 4096, 8192, 16384
if sensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange) == False:
print("Device setup failure. Please check your connection", \
file=sys.stderr)
return
else:
print("Setup complete.")
startTime = millis() # Used to calculate measurement rate
samplesTaken = 0 # Counter for calculating the Hz or read rate
while True:
sensor.check() # Check the sensor, read up to 3 samples
while (sensor.available() > 0): # do we have new data?
samplesTaken += 1
hertz = samplesTaken / ((millis() - startTime) / 1000)
hertz = round(hertz, 2)
print(\
'R[', sensor.getFIFORed() , '] \t'\
'IR[', sensor.getFIFOIR() , '] \t'\
'G[', sensor.getFIFOGreen() , '] \t'\
'Hz[', hertz , ']'\
)
sensor.nextSample() # We're finished with this sample so move to next sample
if __name__ == '__main__':
try:
runExample()
except (KeyboardInterrupt, SystemExit) as exErr:
print("\nEnding Example 6")
sys.exit(0)
|