WRITE A CODE THAT MEASURES HEART RATE FROM 60-100 AND SHOWS THE DATA ON THE OLED SCREEN.…
- User
WRITE A CODE THAT MEASURES HEART RATE FROM 60-100 AND SHOWS THE DATA ON THE OLED SCREEN. ADD PIOTIMER AND ENCODER CAPABILITIES. HERE IS THE SOURCE CODE: import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306
Set up I2C, OLED display, and other pins
i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) heart_rate = 0 peaks = [] peak_intervals = []
encoder_pin_a = Pin(10, Pin.IN, Pin.PULL_UP) encoder_pin_b = Pin(11, Pin.IN, Pin.PULL_UP) encoder_button = Pin(12, Pin.IN, Pin.PULL_UP)
led1_pin = 20 led2_pin = 21 led3_pin = 22
led1_pwm = PWM(Pin(led1_pin)) led2_pwm = PWM(Pin(led2_pin)) led3_pwm = PWM(Pin(led3_pin))
Set up ADC and sampling
sampling_freq = 60 # Hz, default sampling frequency sampling_period_ms = 1000 // sampling_freq adc_pin = ADC(Pin(26, Pin.IN)) samples = Fifo(50)
Set up timer for sampling at precise intervals
timer = machine.Timer()
def on_timer_tick(timer): sample = adc_pin.read_u16() samples.put(sample)
timer.init(freq=sampling_freq, mode=machine.Timer.PERIODIC, callback=on_timer_tick)
Find peaks in the data
def find_peaks(data, threshold): peaks = [] for i in range(1, len(data) - 1): if data[i] > threshold and data[i] > data[i - 1] and data[i] > data[i + 1]: peaks.append(i) return peaks
Main program loop
window_size = 60 # 1 second of data at 60 Hz window = [] prev_encoder_state = 0 encoder_state = 0 encoder_counter = 0 try:
while True: # Read encoder state and adjust sampling frequency accordingly encoder_state = (encoder_pin_a.value() << 1) | encoder_pin_b.value() if encoder_state != prev_encoder_state: if (prev_encoder_state == 0b00 and encoder_state == 0b01) or (prev_encoder_state == 0b01 and encoder_state == 0b11) or (prev_encoder_state == 0b11 and encoder_state == 0b10) or (prev_encoder_state == 0b10 and encoder_state == 0b00): encoder_counter += 1 else: encoder_counter -= 1 encoder_counter = max(min(encoder_counter, 40), -40) sampling_freq = max(min(100, 60 + encoder_counter), 60) sampling_period_ms = 1000 // sampling_freq timer.init(freq=sampling_freq, mode=machine.Timer.PERIODIC, callback=on_timer_tick) prev_encoder_state = encoder_state if not samples.empty(): sample = samples.get() window.append(sample) # Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: peaks = find_peaks(window, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] if len(peak_intervals) > 0: avg_peak_interval = sum(peak_intervals) / len(peak_intervals) heart_rate = 60 * sampling_freq / avg_peak_interval # Adjust the sampling frequency based on encoder input encoder_delta = 0 if encoder_pin_a.value() != encoder_pin_b.value(): encoder_delta += 1 else: encoder_delta -= 1 sampling_freq += encoder_delta if sampling_freq < 60: sampling_freq = 60 elif sampling_freq > 100: sampling_freq = 100 sampling_period_ms = 1000 // sampling_freq timer.init(freq=sampling_freq, mode=machine.Timer.PERIODIC, callback=on_timer_tick) # Draw the graph oled.fill(0) oled.text("Heart rate: {:.1f}".format(heart_rate), 0, 0) oled.text("BPM: {:.1f}".format(heart_rate), 0, 10) prev_x, prev_y = 0, 0 for i, value in enumerate(window[-128:]): x = i y = 63 - int((value / 65535) * 32) # Scale the sample value to fit the OLED screen if i != 0: oled.line(prev_x, prev_y, x, y, 1) prev_x, prev_y = x, y oled.show() if not peaks: print("No peaks detected.") - Assistant
- User
FIX THE ERROR: File "", line 10, in AttributeError: 'ADC' object has no attribute 'width'
IN THIS FOLLOWING CODE; import machine import ssd1306 import time from machine import PWM, Pin, ADC
i2c = machine.I2C(1, scl=machine.Pin(15), sda=machine.Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c)
adc = machine.ADC(machine.Pin(26)) adc.width(machine.ADC.WIDTH_12BIT) adc.atten(machine.ADC.ATTN_11DB)
buffer_size = 1000 buffer = bytearray(buffer_size)
while True: for i in range(buffer_size): buffer[i] = adc.read()
ppg = sum(buffer) // buffer_size # Display the PPG value on the OLED screen oled.fill(0) oled.text("Heart Rate: ", 0, 0) oled.text(str(ppg), 0, 16) oled.show() # Wait for a short period to sample the PPG signal again time.sleep_ms(20) - Assistant
It appears you are using the MicroPython
ADCobject, which has slightly different syntax for specifying the width and attenuation than what you provided. The correct way to set the width and attenuation using MicroPython is to set the attributes directly, like this:import machine import ssd1306 import time from machine import PWM, Pin, ADC i2c = machine.I2C(1, scl=machine.Pin(15), sda=machine.Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) adc = machine.ADC(machine.Pin(26)) adc.init(bits=12, atten=ADC.ATTN_11DB) # Set the width and attenuation here. buffer_size = 1000 buffer = bytearray(buffer_size) while True: for i in range(buffer_size): buffer[i] = adc.read() ppg = sum(buffer) // buffer_size # Display the PPG value on the OLED screen oled.fill(0) oled.text("Heart Rate: ", 0, 0) oled.text(str(ppg), 0, 16) oled.show() # Wait for a short period to sample the PPG signal again time.sleep_ms(20)In this updated code, I have removed the lines with
adc.width()andadc.atten(), and replaced them with a single line to initialize the ADC object with the desired number of bits and attenuation. Everything else in the code should work as expected. - User
Fix this File "", line 10, in AttributeError: 'ADC' object has no attribute 'init' in this code: import machine import ssd1306 import time from machine import PWM, Pin, ADC
i2c = machine.I2C(1, scl=machine.Pin(15), sda=machine.Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c)
adc = machine.ADC(machine.Pin(26)) adc.init(bits=12, atten=ADC.ATTN_11DB) # Set the width and attenuation here.
buffer_size = 1000 buffer = bytearray(buffer_size)
while True: for i in range(buffer_size): buffer[i] = adc.read()
ppg = sum(buffer) // buffer_size # Display the PPG value on the OLED screen oled.fill(0) oled.text("Heart Rate: ", 0, 0) oled.text(str(ppg), 0, 16) oled.show() # Wait for a short period to sample the PPG signal again time.sleep_ms(20) - Assistant
Apologies for the confusion. The
init()function is not available in the MicroPython ADC implementation. You should set thebits()andatten()attributes using their respective functions for MicroPython. Here's the corrected code:import machine import ssd1306 import time from machine import PWM, Pin, ADC i2c = machine.I2C(1, scl=machine.Pin(15), sda=machine.Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) adc = machine.ADC(machine.Pin(26)) adc.atten(ADC.ATTN_11DB) # Set the attenuation here adc.width(ADC.WIDTH_12BIT) # Set the width here buffer_size = 1000 buffer = bytearray(buffer_size) while True: for i in range(buffer_size): buffer[i] = adc.read() ppg = sum(buffer) // buffer_size # Display the PPG value on the OLED screen oled.fill(0) oled.text("Heart Rate: ", 0, 0) oled.text(str(ppg), 0, 16) oled.show() # Wait for a short period to sample the PPG signal again time.sleep_ms(20)In the updated code, I have removed the
adc.init()line and added theadc.atten()andadc.width()functions to set the attenuation and width settings as intended. - User
- Assistant
The code you provided does not include any filtering, which is necessary for accurate detection of the heart rate from ECG or PPG data. The noise present in the raw data may cause the peak detection function to detect false peaks or miss actual peaks, causing incorrect heart rate values. One solution to this is to low-pass filter the data to remove high-frequency noise. Butterworth filters are commonly used to filter ECG/PPG signals. Unfortunately, MicroPython does not include a built-in function to apply a Butterworth filter. You may consider using a moving average or exponential moving average filter as an alternative.
- User
in line 13, there is a TypeError: function takes 2 positional arguments but 1 were given. please fix: import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306
Set up I2C, OLED display, and other pins
i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c)
… (keep the rest of the code the same until the main program loop)
samples = Fifo() window_size = 100 window = []
Exponential moving average function
def exponential_moving_average(window, alpha=0.1): avg = window[0] for value in window[1:]: avg = alpha * value + (1 - alpha) * avg return avg
try: while True: if not samples.empty(): sample = samples.get() window.append(sample)
# Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: filtered_signal = [exponential_moving_average(window[:i+1]) for i in range(len(window))] peaks = find_peaks(filtered_signal, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] # … (keep the rest of the code the same) try: utime.sleep_ms(sampling_period_ms) except KeyboardInterrupt: print("Interrupted during sleep. Continuing...") - Assistant
My apologies for the oversight. It seems the
Fifo()initialization is incorrect in the code. To correct the error, you need to addsize=50while initializing the Fifo buffer. Here is the updated code:import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306 # Set up I2C, OLED display, and other pins i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) # ... (keep the rest of the code the same until the main program loop) samples = Fifo(size=50) window_size = 100 window = [] # Exponential moving average function def exponential_moving_average(window, alpha=0.1): avg = window[0] for value in window[1:]: avg = alpha * value + (1 - alpha) * avg return avg try: while True: if not samples.empty(): sample = samples.get() window.append(sample) # Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: filtered_signal = [exponential_moving_average(window[:i+1]) for i in range(len(window))] peaks = find_peaks(filtered_signal, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] # ... (keep the rest of the code the same) try: utime.sleep_ms(sampling_period_ms) except KeyboardInterrupt: print("Interrupted during sleep. Continuing...") except KeyboardInterrupt: print("Exiting program...") - User
NameError: name 'sampling_period_ms' isn't defined in line 42: import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306
Set up I2C, OLED display, and other pins
i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c)
… (keep the rest of the code the same until the main program loop)
samples = Fifo(size=50) window_size = 100 window = []
Exponential moving average function
def exponential_moving_average(window, alpha=0.1): avg = window[0] for value in window[1:]: avg = alpha * value + (1 - alpha) * avg return avg
try: while True: if not samples.empty(): sample = samples.get() window.append(sample)
# Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: filtered_signal = [exponential_moving_average(window[:i+1]) for i in range(len(window))] peaks = find_peaks(filtered_signal, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] # … (keep the rest of the code the same) try: utime.sleep_ms(sampling_period_ms) except KeyboardInterrupt: print("Interrupted during sleep. Continuing…") - Assistant
Apologies once again for the oversight. I have missed adding the
sampling_period_msvalue in the code. Here is the updated code:import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306 # Set up I2C, OLED display, and other pins i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) # ... (keep the rest of the code the same until the main program loop) samples = Fifo(size=50) window_size = 100 window = [] sampling_period_ms = 4 # Update this value as desired # Exponential moving average function def exponential_moving_average(window, alpha=0.1): avg = window[0] for value in window[1:]: avg = alpha * value + (1 - alpha) * avg return avg try: while True: if not samples.empty(): sample = samples.get() window.append(sample) # Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: filtered_signal = [exponential_moving_average(window[:i+1]) for i in range(len(window))] peaks = find_peaks(filtered_signal, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] # ... (keep the rest of the code the same) try: utime.sleep_ms(sampling_period_ms) except KeyboardInterrupt: print("Interrupted during sleep. Continuing...") except KeyboardInterrupt: print("Exiting program...") - User
The code has no visible errors but the code does nothing now: import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306
Set up I2C, OLED display, and other pins
i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c)
… (keep the rest of the code the same until the main program loop)
samples = Fifo(size=50) window_size = 100 window = [] sampling_period_ms = 4 # Update this value as desired
Exponential moving average function
def exponential_moving_average(window, alpha=0.1): avg = window[0] for value in window[1:]: avg = alpha * value + (1 - alpha) * avg return avg
try: while True: if not samples.empty(): sample = samples.get() window.append(sample)
# Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: filtered_signal = [exponential_moving_average(window[:i+1]) for i in range(len(window))] peaks = find_peaks(filtered_signal, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] # … (keep the rest of the code the same) try: utime.sleep_ms(sampling_period_ms) except KeyboardInterrupt: print("Interrupted during sleep. Continuing…") - Assistant