🌈 ESP32-S3 Rainbow: ZX Spectrum Emulator Board! Get it on Crowd Supply →
View All Posts
read
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi

I’ve had a few emails asking for information on how my app Heart Rate - Free works.

There’s nothing particularly clever about it, it just uses the camera to pick up the slight change in the colour of the light coming from the flash as the blood flows in and out of the finger.

You can make a few modifications to the code posted in the Augmented Reality Post or download the demo code.

Setting up the capture session is pretty much the same as usual. The main differences are that we don’t need to preview the image (it’s not very interesting to look at…) and that we need to turn on the flash to illuminate the finger.

// switch on the flash in torch mode
if([camera isTorchModeSupported:AVCaptureTorchModeOn]) {
 [camera lockForConfiguration:nil];
 camera.torchMode=AVCaptureTorchModeOn;
 [camera unlockForConfiguration];
}

We’ll also set the frame size to low as we don’t need high resolution images:

[session setSessionPreset:AVCaptureSessionPresetLow];

The capture setup code looks like this now:

// Create the AVCapture Session
session = [[AVCaptureSession alloc] init];
 
// Get the default camera device
AVCaptureDevice* camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if([camera isTorchModeSupported:AVCaptureTorchModeOn]) {
 [camera lockForConfiguration:nil];
 camera.torchMode=AVCaptureTorchModeOn;
 [camera unlockForConfiguration];
}
// Create a AVCaptureInput with the camera device
NSError *error=nil;
AVCaptureInput* cameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:camera error:&error];
if (cameraInput == nil) {
 NSLog(@"Error to create camera capture:%@",error);
}
 
// Set the output
AVCaptureVideoDataOutput* videoOutput = [[AVCaptureVideoDataOutput alloc] init];
 
// create a queue to run the capture on
dispatch_queue_t captureQueue=dispatch_queue_create("catpureQueue", NULL);
 
// setup our delegate
[videoOutput setSampleBufferDelegate:self queue:captureQueue];
 
// configure the pixel format
videoOutput.videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey,
         nil];
// cap the framerate
videoOutput.minFrameDuration=CMTimeMake(1, 10);
// and the size of the frames we want
[session setSessionPreset:AVCaptureSessionPresetLow];
 
// Add the input and output
[session addInput:cameraInput];
[session addOutput:videoOutput];
 
// Start the session
[session startRunning];

In out capture callback we’ll pull out the RGB values from the preview image:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
 // this is the image buffer
 CVImageBufferRef cvimgRef = CMSampleBufferGetImageBuffer(sampleBuffer);
 // Lock the image buffer
 CVPixelBufferLockBaseAddress(cvimgRef,0);
 // access the data
 int width=CVPixelBufferGetWidth(cvimgRef);
 int height=CVPixelBufferGetHeight(cvimgRef);
 // get the raw image bytes
 uint8_t *buf=(uint8_t *) CVPixelBufferGetBaseAddress(cvimgRef);
 size_t bprow=CVPixelBufferGetBytesPerRow(cvimgRef);
 // get the average red green and blue values from the image
 float r=0,g=0,b=0;
 for(int y=0; y<height; y++) {
  for(int x=0; x<width*4; x+=4) {
   b+=buf[x];
   g+=buf[x+1];
   r+=buf[x+2];
  }
  buf+=bprow;
 }
 r/=255*(float) (width*height);
 g/=255*(float) (width*height);
 b/=255*(float) (width*height);

 NSLog(@"%f,%f,%f", r, g, b);
}

If we run this and plot the values for red and green (blue is pretty uninteresting as it’s almost zero) we can see that there’s definitely some kind of change when the heart beats:

The peaks in both the red and green values correspond to your pulse. We can combine the values into something a lot more convenient if we convert the RGB values to HSV (hue, saturation, value) and just use the value of hue.

We can now see a definite pattern that corresponds to the heart beat. You’ll probably want to do some filtering on the results from this - I’d suggest running it through a simple notch filter (highpass and lowpass filter) to get rid of DC component and apply a bit of smoothing to isolate the heart beat:

You can then pass these values into whatever mechanism you plan to use to detect and measure the beats.

Here’s the sample project in action:

You can download it from here. You’ll need to replace the filtering with something a bit more sensible, the code I’ve put there is purely for demo purposes.

Related Posts

Heart Rate Free - just released on the iPhone - Just found an iPhone app that creatively measures your heart rate simply using the flash on your phone. Thought I'd try the neat little tool and was fascinated with it. Can't wait to share more on how it works in an upcoming post.
iAds Report - In this post, I'm sharing performance stats from a free Heart Rate app which has been live for just over two weeks, and has been downloaded around 40k-50k times worldwide. It was categorized under Entertainment instead of Health and Fitness which may have affected downloads and advertising revenue. It's been relatively successful and was built with iAds and AdMob adverts. Revenue generated from the US was substantial with fill rates at nearly 50% and an amazing eCPM of almost $30, compared to Admob's $2.2. Despite the revenue's rapid decline correlating with downloads, I believe there may be a strong case for ads in apps.
MAX30102 $3 Heart Rate Monitor - One of those AliExpress impulse buys finally earned its keep: I paired an ESP32-C3 with a MAX30102 and a tiny OLED to build a pocket pulse oximeter. A bit of I2C wiring, a ring-buffered sampler, and the MAX30102 HR/SpO2 algorithm later, the onboard LED is thumping along with my heartbeat and the readings match a commercial unit (~70 BPM, 99% SpO2). It’s a little finicky about finger placement, but for a few bucks it works brilliantly.
Augmented reality on the iPhone with iOS4.0 - Hey guys! Just updated my earlier blog post on creating Augmented Reality (AR) on iPhones using the new iOS4.0 features. I’ve also moved away from the 'UIGetScreenImage' function as it’s no longer supported. Now, we access the camera using the AV Foundation framework with the help of AVCaptureSession. As always, you're free to download and fiddle with my code available in this blog. Happy Programming!
Augmented Reality on the iPhone - how to - Hey there tech enthusiasts! So, you used to rely on my old methods for employing augmented reality on an iPhone? Well, those days are past. With the release of iOS4, accessing the camera has become a breeze. Check out my latest blog post where I share the specially updated code that works seamlessly with iOS4.

Related Videos

M5Stack CORE2 - Can't remember why I got this, but it looks nice! - Hey guys! So today, I'm testing out this really cool app. It's pretty interesting - I think it could be really handy if you're into tech stuff. Let's dive in and see what it can do!
$3 AliExpress Heart Rate and Oxygen Sensor Module - You know how it is—you grab one cute little AliExpress module, then another… so I finally put an ESP32-C3 to work. Under the microscope it looks solid (nice 3.3V reg, ceramic antenna I’m not trusting for Wi‑Fi), and I paired it with a MAX30102 heart-rate/SpO2 sensor. Wired up I2C (SCL pin 6, SDA pin 5, INT to pin 2, 5V in), ran a scan, and boom—two devices found. After some finger-fiddling, the readings matched a commercial oximeter. Code’s on GitHub—cheap, fun, and it works.
256 Shades of Grey – Adventures in Image Processing - In this enlightening video, I delve into the deep and fascinating world of image processing. Forget everything you thought you knew about pixels – they’re not squares or rectangles and they definitely aren’t discs. All pixels are, my friends, are point samples, each capturing brightness or color at a particular position. Curious to know how to manipulate them? I also unravel this mysterious tapestry, familiarizing you with the technicalities of grayscale, RGB, HSB, YUV, and a fleeting mention of CMYK. And if you think that's all, hold tight! Did you know we could apply Fourier transforms, akin to graphic equalisers used in audio, to our good old two-dimensional images? Strap in as I guide you through this potentially overwhelming realm with a pinch of humor, lots of simplicity, and oodles of practical examples.
I Made a Digital Twin for my PCB - IMU Visualiser - Hey everyone! In this video, I’m diving into testing the cool functionality of my new board that I designed, and demonstrating how to use both an accelerometer and gyroscope with my favorite little tool. The board is rocking an LSM 6DS3 sensor, which works like a charm, despite the tiny LED snafu from before (watch my 'ninja repair' in the previous video, haha). I walk through the different modes, including a fusion mode that magically blends sensor data for accuracy. Also, there's some cool 3D modeling in play where you can bring any model to life on my public website – yes, even a teapot! Plus, it's all open source on GitHub, ready for you to get hands-on and maybe even add your enhancements. Enjoy!
Forget the Arduino Serial Plotter - try this instead! - Hey everyone! So, you're probably familiar with the Arduino serial plotter, right? It's useful for basic stuff, but I wanted something better, more cross-platform, and runs right in the browser. Enter the web serial plotter, using the web serial API! It's super flexible with zoom, export options, and light/dark mode. You can even pan through history or switch to absolute time. Plus, it's all secure and runs locally. It's open source, and I'd love your contributions or bug reports on GitHub. It's still a work in progress, but I think you'll find it pretty handy!
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
Blog Logo

Chris Greening


Published

> Image

atomic14

A collection of slightly mad projects, instructive/educational videos, and generally interesting stuff. Building projects around the Arduino and ESP32 platforms - we'll be exploring AI, Computer Vision, Audio, 3D Printing - it may get a bit eclectic...

View All Posts