Guest

Untitled 1059

Apr 5th, 2026
9
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
None 3.56 KB | None | 0 0
  1. import smbus2
  2. import time
  3.  
  4. # I2C Setup
  5. MAX30102_ADDR = 0x57
  6. bus = smbus2.SMBus(1)
  7.  
  8. # Basic Setup
  9. bus.write_byte_data(MAX30102_ADDR, 0x09, 0x40) # Reset
  10. time.sleep(0.1)
  11. bus.write_byte_data(MAX30102_ADDR, 0x09, 0x03) # HR + SpO2
  12. bus.write_byte_data(MAX30102_ADDR, 0x0A, 0x27)
  13. bus.write_byte_data(MAX30102_ADDR, 0x0C, 0x24) # Red LED
  14. bus.write_byte_data(MAX30102_ADDR, 0x0D, 0x24) # IR LED
  15.  
  16. ir_list = []
  17. last_beat = time.time()
  18. bpm = 0
  19.  
  20. print("Place your finger steadily on the sensor...")
  21.  
  22. try:
  23. while True:
  24. data = bus.read_i2c_block_data(MAX30102_ADDR, 0x07, 6)
  25. ir = (data[3] << 16 | data[4] << 8 | data[5]) & 0x3FFFF
  26.  
  27. # Simple Peak Detection Logic
  28. ir_list.append(ir)
  29. if len(ir_list) > 50: ir_list.pop(0) # Keep last 50 samples
  30.  
  31. # Check for a beat (when current IR is significantly higher than average)
  32. avg_ir = sum(ir_list) / len(ir_list)
  33. if ir > avg_ir + 500: # Threshold for a peak
  34. now = time.time()
  35. if now - last_beat > 0.5: # Max 120 BPM limit to avoid noise
  36. time_diff = now - last_beat
  37. bpm = 60 / time_diff
  38. last_beat = now
  39. if 40 < bpm < 180: # Filter realistic BPM
  40. print(f"BPM: {int(bpm)} | (Raw IR: {ir})")
  41.  
  42. time.sleep(0.02) # Fast sampling for accuracy
  43.  
  44. except KeyboardInterrupt:
  45. print("Stopped.")
  46. finally:
  47. bus.close()
RAW Paste Data Copied