import smbus2 import time # I2C Setup MAX30102_ADDR = 0x57 bus = smbus2.SMBus(1) # Basic Setup bus.write_byte_data(MAX30102_ADDR, 0x09, 0x40) # Reset time.sleep(0.1) bus.write_byte_data(MAX30102_ADDR, 0x09, 0x03) # HR + SpO2 bus.write_byte_data(MAX30102_ADDR, 0x0A, 0x27) bus.write_byte_data(MAX30102_ADDR, 0x0C, 0x24) # Red LED bus.write_byte_data(MAX30102_ADDR, 0x0D, 0x24) # IR LED ir_list = [] last_beat = time.time() bpm = 0 print("Place your finger steadily on the sensor...") try: while True: data = bus.read_i2c_block_data(MAX30102_ADDR, 0x07, 6) ir = (data[3] << 16 | data[4] << 8 | data[5]) & 0x3FFFF # Simple Peak Detection Logic ir_list.append(ir) if len(ir_list) > 50: ir_list.pop(0) # Keep last 50 samples # Check for a beat (when current IR is significantly higher than average) avg_ir = sum(ir_list) / len(ir_list) if ir > avg_ir + 500: # Threshold for a peak now = time.time() if now - last_beat > 0.5: # Max 120 BPM limit to avoid noise time_diff = now - last_beat bpm = 60 / time_diff last_beat = now if 40 < bpm < 180: # Filter realistic BPM print(f"BPM: {int(bpm)} | (Raw IR: {ir})") time.sleep(0.02) # Fast sampling for accuracy except KeyboardInterrupt: print("Stopped.") finally: bus.close()