.
HMC5883L on the GY-80 module Reviewed by Unknown on 23:20 Rating: 4.5

HMC5883L on the GY-80 module

Description

In this tutorial, I will show you how to configure and extract data from the magnetometer (HMC5883L) sensor on the GY-80 10DOF module from ICStation. While there are some very good libraries on the internet which will give you full access to this sensor, I will show you what you need to know without using a library. This means that it may get a bit technical at times, but I will hold your hand along the way and provide explanations as required. I would also recommend that you watch the complete video from start to finish - as the video provides really useful information.


 

HMC5883L Magnetometer Datasheet:

You can find the datasheet for the HMC5883L pretty easily by searching on the internet. Here are a couple of sources:


 

Arduino Libraries

This tutorial does not use any external libraries.
It does use the Wire library for I2C communication.
However, there is no extra download required to access the Wire library.
If you are looking for a library specific for the HMC5883L sensor, then I would recommend one of these:

Like I said - you do not need an HMC5883L library for this tutorial. The libraries above are listed for those who wish to learn more about this particular sensor.

Arduino IDE

The Arduino IDE can be downloaded from the Arduino website. Visit the Arduino IDE download page.

I generally use the ZIP file for Windows and never seem to have any issues.
There are downloads available for all the major operating systems.


 

ARDUINO CODE:

I have created a Gist for the Arduino code to configure and extract data from the HMC5883L sensor. However, I also have a GitHub repository which aims to capture the code for all of the sensors on the GY-80 module. Code for the other sensors will become available in due time. Meanwhile, have a look at the code below for the HMC5883L sensor:

This code will set all axis values to 1000 upon startup. Moving the GY-80 module around will result in a value greater or less than 1000, however, returning the sensor back to it's original position, should result in values very close to 1000 on each axis. I chose to introduce this calibration in order to avoid negative values, and I liked the fact that I could set a heading with values that were easy to remember.
 
The magSetting function was created to easily configure the magnetometer.
Make sure to look at the video and also the datasheet for further information about calibrating the magnetometer.
 
The getReadings function was created to easily retrieve the magnetometer axis data. I chose to use Single measurement mode in this tutorial.


 
 

Hooking it up:

You can communicate with any of the sensors on the GY-80 module using I2C. The HMC5883L magnetometer sensor is no different. You will need four connections between the Arduino UNO and the GY-80 module. Have a look at the diagram below for the connection diagram and table.

Fritzing diagram



 
 

Project pictures












Concluding comments

The HMC5883L sensor on the GY-80 module is quite interesting and works relatively well. There are a number of other sensors on the GY-80 module which can provide complementary positional data. At some point, I plan to come back and explain some of the other sensors on this module, but first I would like to create a real-life project using the magnetometer. So stay tuned. You may want to subscribe to my social networks or to this blog to be notified of that project when I complete it.

I would like to thank ICStation for their collaborative efforts. Their contribution was invaluable to this tutorial's existence.

If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.

Description: HMC5883L on the GY-80 module Rating: 3.5 Reviewer: Unknown ItemReviewed: HMC5883L on the GY-80 module
NeoPixel Heart Beat Display Reviewed by Unknown on 01:11 Rating: 4.5

NeoPixel Heart Beat Display


Project Description


In this project, your heart will control a mesmerising LED sequence on a 5 metre Neopixel LED strip with a ws2812B chipset. Every heart beat will trigger a LED animation that will keep you captivated and attached to your Arduino for ages. The good thing about this project is that it is relatively easy to set up, and requires no soldering. The hardest part is downloading and installing the FastLED library into the Arduino IDE, but that in itself is not too difficult. The inspiration and idea behind this project came from Ali Murtaza, who wanted to know how to get an LED strip to pulse to his heart beat.
 
Have a look at the video below to see this project in action.
 
 
 

The Video


 


 
 

Parts Required:


 

Power Requirements

Before you start any LED strip project, the first thing you will need to think about is POWER. According to the Adafruit website, each individual NeoPixel LED can draw up to 60 milliamps at maximum brightness - white. Therefore the amount of current required for the entire strip will be way more than your Arduino can handle. If you try to power this LED strip directly from your Arduino, you run the risk of damaging not only your Arduino, but your USB port as well. The Arduino will be used to control the LED strip, but the LED strip will need to be powered by a separate power supply. The power supply you choose to use is important. It must provide the correct voltage, and must able to supply sufficient current.
 

Operating Voltage (5V)

The operating voltage of the NeoPixel strip is 5 volts DC. Excessive voltage will damage/destroy your NeoPixels.

Current requirements (9.0 Amps)

OpenLab recommend the use of a 5V 10A power supply. Having more Amps is OK, providing the output voltage is 5V DC. The LEDs will only draw as much current as they need. To calculate the amount of current this 5m strip can draw with all LEDs turned on at full brightness - white:

30 NeoPixel LEDs x 60mA x 5m = 9000mA = 9.0 Amps for a 5 metre strip.

Therefore a 5V 10A power supply would be able to handle the maximum current (9.0 Amps) demanded by a 5m NeoPixel strip containing a total of 150 LEDs.
 
 


Arduino Libraries and IDE


Before you start to hook up any components, upload the following sketch to the Arduino microcontroller. I am assuming that you already have the Arduino IDE installed on your computer. If not, the IDE can be downloaded from here.
 
The FastLED library is useful for simplifying the code for programming the NeoPixels. The latest "FastLED library" can be downloaded from here. I used FastLED library version 3.0.3 in this project.
 
If you have a different LED strip or your NeoPixels have a different chipset, make sure to change the relevant lines of code to accomodate your hardware. I would suggest you try out a few of the FastLED library examples before using the code below, so that you become more familiar with the library, and will be better equipped to make the necessary changes. If you have a 5 metre length of the NeoPixel 30 LED/m strip with the ws2812B chipset, then you will not have to make any modification below.
 

ARDUINO CODE:


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
/* ================================================================================================ Project: NeoPixel Heart Beat Display Neopixel chipset: ws2812B (30 LED/m strip) Author: Scott C Created: 8th July 2015 Arduino IDE: 1.6.4 Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html Description: This sketch will display a heart beat on a 5m Neopixel LED strip. Requires a Grove Ear-clip heart rate sensor and a Neopixel strip. This project makes use of the FastLED library: http://fastled.io/ You may need to modify the code below to accomodate your specific LED strip. See the FastLED library site for more details. ================================================================================================== */ //This project needs the FastLED library - link in the description. #include "FastLED.h" //The total number of LEDs being used is 150 #define NUM_LEDS 150 // The data pin for the NeoPixel strip is connected to digital Pin 6 on the Arduino #define DATA_PIN 6 //Attach the Grove Ear-clip heart rate sensor to digital pin 2 on the Arduino. #define EAR_CLIP 2 //Initialise the LED array CRGB leds[NUM_LEDS]; //Initialise the global variables used to control the LED animation int ledNum = 0; //Keep track of the LEDs boolean beated = false; //Used to identify when the heart has beated int randomR = 0; //randomR used to randomise the fade-out of the LEDs //================================================================================================ // setup() : Is used to initialise the LED strip //================================================================================================ void setup() { FastLED.addLeds<NEOPIXEL,DATA_PIN>(leds, NUM_LEDS); //Set digital pin 2 (Ear-clip heart rate sensor) as an INPUT pinMode(EAR_CLIP, INPUT);} //================================================================================================ // loop() : Take readings from the Ear-clip sensor, and display the animation on the LED strip //================================================================================================ void loop() { //If the Ear-clip sensor moves from LOW to HIGH, call the beatTriggered method if(digitalRead(EAR_CLIP)>0){ //beatTriggered() is only called if the 'beated' variable is false. //This prevents multiple triggers from the same beat. if(!beated){ beatTriggered(); } } else { beated = false; //Change the 'beated' variable to false when the Ear-clip heart rate sensor is reading LOW. } //Fade the LEDs by 1 unit/cycle, when the heart is at 'rest' (i.e. between beats) fadeLEDs(5);} //================================================================================================ // beatTriggered() : This is the LED animation sequence when the heart beats //================================================================================================ void beatTriggered(){ //Ignite 30 LEDs with a red value between 0 to 255 for(int i = 0; i<30; i++){ //The red channel is randomised to a value between 0 to 255 leds[ledNum].r=random8(); FastLED.show(); //Call the fadeLEDs method after every 3rd LED is lit. if(ledNum%3==0){ fadeLEDs(5); } //Move to the next LED ledNum++; //Make sure to move back to the beginning if the animation falls off the end of the strip if(ledNum>(NUM_LEDS-1)){ ledNum=0; } } //Ignite 20 LEDS with a blue value between 0 to 120 for(int i = 0; i<20; i++){ //The blue channel is randomised to a value between 0 to 120 leds[ledNum].b=random8(120); FastLED.show(); //Call the fadeLEDs method after every 3rd LED is lit. if(ledNum%3==0){ fadeLEDs(5); } //Move to the next LED ledNum++; //Make sure to move back to the beginning if the animation falls off the end of the strip if(ledNum>(NUM_LEDS-1)){ ledNum=0; } } //Change the 'beated' variable to true, until the Ear-Clip sensor reads LOW. beated=true;} //================================================================================================ // fadeLEDs() : The fading effect of the LEDs when the Heart is resting (Ear-clip reads LOW) //================================================================================================ void fadeLEDs(int fadeVal){ for (int i = 0; i<NUM_LEDS; i++){ //Fade every LED by the fadeVal amount leds[i].fadeToBlackBy( fadeVal ); //Randomly re-fuel some of the LEDs that are currently lit (1% chance per cycle) //This enhances the twinkling effect. if(leds[i].r>10){ randomR = random8(100); if(randomR<1){ //Set the red channel to a value of 80 leds[i].r=80; //Increase the green channel to 20 - to add to the effect leds[i].g=20; } } } FastLED.show();}


 

NeoPixel Strip connection

The NeoPixel strip is rolled up when you first get it. You will notice that there are wires on both sides of the strip. This allows you to chain LED strips together to make longer strips. The more LEDs you have, the more current you will need. Connect your Arduino and power supply to the left side of the strip, with the arrows pointing to the right. (i.e. the side with the "female" jst connector).
 



NeoPixel Strip Wires

There are 5 wires that come pre-attached to either side of the LED strip.
 

 
You don't have to use ALL FIVE wires, however you will need at least one of each colour: red, white & green.
 

 

Fritzing sketch

The following diagram will show you how to wire everything together
 
(click to enlarge)

Arduino Power considerations

Please note that the Arduino is powered by a USB cable.
If you plan to power the Arduino from your power supply, you will need to disconnect the USB cable from the Arduino FIRST, then connect a wire from the 5V line on the Power supply to the 5V pin on the Arduino. Do NOT connect the USB cable to the Arduino while the 5V wire is connected to the Arduino.
 

 

Large Capacitor

Adafruit also recommend the use of a large capacitor across the + and - terminals of the LED strip to "prevent the initial onrush of current from damaging the pixels". Adafruit recommends a capacitor that is 1000uF, 6.3V or higher. I used a 4700uF 16V Electrolytic Capacitor.
 

 

Resistor on Data Pin

Another recommendation from Adafruit is to place a "300 to 500 Ohm resistor" between the Arduino's data pin and the data input on the first NeoPixel to prevent voltage spikes that can damage the first pixel. I used a 330 Ohm resistor.
 

 

Grove Ear-clip heart rate sensor connection

The Grove Base shield makes it easy to connect Grove modules to the Arduino. If you have a Grove Base shield, you will need to connect the Ear-clip heart rate sensor to Digital pin 2 as per the diagram below.
 

 

Completed construction

Once you have everything connected, you can plug the USB cable into the Arduino, and turn on the LED power supply. Attach the ear-clip to your ear (or to your finger) and allow a few seconds to allow the sensor to register your pulse. The LED strip will light up with every heart beat with an animation that moves from one end of the strip to the other in just three heart beats. When the ear-clip is not connected to your ear or finger, the LEDs should remain off. However, the ear clip may "trigger" a heart beat when opening or closing the clip.
 
Here is a picture of all the components (fully assembled).
 


Concluding comments


This very affordable LED strip allows you to create amazing animations over a greater distance. I thought that having less LEDs per metre would make the animations look "jittery", but I was wrong, they look amazing. One of the good things about this strip is the amount of space between each Neopixel, allowing you to easily cut and join the strip to the size and shape you need.
 
This LED strip is compatible with the FastLED library, which makes for easy LED animation programming. While I used this LED strip to display my heart beat, you could just as easily use it to display the output of any other sensor attached to the Arduino.
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             

 
This project would not have been possible without OpenLab's collaborative effort.
Please visit their site for more cool projects.



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.




Description: NeoPixel Heart Beat Display Rating: 3.5 Reviewer: Unknown ItemReviewed: NeoPixel Heart Beat Display
Arduino Heart Rate Monitor Reviewed by Unknown on 15:32 Rating: 4.5

Arduino Heart Rate Monitor


Project Description


Heart Rate Monitors are very popular at the moment.
There is something very appealing about watching the pattern of your own heart beat. And once you see it, there is an unstoppable urge to try and control it. This simple project will allow you to visualize your heart beat, and will calculate your heart rate. Keep reading to learn how to create your very own heart rate monitor.


 

Parts Required:


Fritzing Sketch


 

 
 
 

Grove Base Shield to Module Connections


 


 

Arduino Sketch


 

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
/* =================================================================================================
      Project: Arduino Heart rate monitor
       Author: Scott C
      Created: 21st April 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This is a simple sketch that uses a Grove Ear-clip Heart Rate sensor attached to an Arduino UNO,
               which sends heart rate data to the computer via Serial communication. You can see the raw data
               using the Serial monitor on the Arduino IDE, however, this sketch was specifically
               designed to interface with the matching Processing sketch for a much nicer graphical display.
               NO LIBRARIES REQUIRED.
=================================================================================================== */

#define Heart 2                            //Attach the Grove Ear-clip sensor to digital pin 2.
#define LED 4                              //Attach an LED to digital pin 4

boolean beat = false; /* This "beat" variable is used to control the timing of the Serial communication
                                           so that data is only sent when there is a "change" in digital readings. */

//==SETUP==========================================================================================
void setup() {
  Serial.begin(9600); //Initialise serial communication
  pinMode(Heart, INPUT); //Set digital pin 2 (heart rate sensor pin) as an INPUT
  pinMode(LED, OUTPUT); //Set digital pin 4 (LED) to an OUTPUT
}


//==LOOP============================================================================================
void loop() {
  if(digitalRead(Heart)>0){ //The heart rate sensor will trigger HIGH when there is a heart beat
    if(!beat){ //Only send data when it first discovers a heart beat - otherwise it will send a high value multiple times
      beat=true; //By changing the beat variable to true, it stops further transmissions of the high signal
      digitalWrite(LED, HIGH); //Turn the LED on
      Serial.println(1023); //Send the high value to the computer via Serial communication.
    }
  } else { //If the reading is LOW,
    if(beat){ //and if this has just changed from HIGH to LOW (first low reading)
      beat=false; //change the beat variable to false (to stop multiple transmissions)
      digitalWrite(LED, LOW); //Turn the LED off.
      Serial.println(0); //then send a low value to the computer via Serial communication.
    }
  }
}


 
 
 
 

Processing Sketch


 
  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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

/* =================================================================================================
       Project: Arduino Heart rate monitor
        Author: Scott C
       Created: 21st April 2015
Processing IDE: 2.2.1
       Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
   Description: A Grove Ear-clip heart rate sensor allows an Arduino UNO to sense your pulse.
                The data obtained by the Arduino can then be sent to the computer via Serial communication
                which is then displayed graphically using this Processing sketch.
                
=================================================================================================== */

import processing.serial.*; // Import the serial library to allow Serial communication with the Arduino

int numOfRecs = 45; // numOfRecs: The number of rectangles to display across the screen
Rectangle[] myRecs = new Rectangle[numOfRecs]; // myRecs[]: Is the array of Rectangles. Rectangle is a custom class (programmed within this sketch)

Serial myPort;                                         
String comPortString="0"; //comPortString: Is used to hold the string received from the Arduino
float arduinoValue = 0; //arduinoValue: Is the float variable converted from comPortString
boolean beat = false; // beat: Used to control for multiple high/low signals coming from the Arduino

int totalTime = 0; // totalTime: Is the variable used to identify the total time between beats
int lastTime = 0; // lastTime: Is the variable used to remember when the last beat took place
int beatCounter = 0; // beatCounter: Is used to keep track of the number of beats (in order to calculate the average BPM)
int totalBeats = 10; // totalBeats: Tells the computer that we want to calculate the average BPM using 10 beats.
int[] BPM = new int[totalBeats]; // BPM[]: Is the Beat Per Minute (BPM) array - to hold 10 BPM calculations
int sumBPM = 0; // sumBPM: Is used to sum the BPM[] array values, and is then used to calculate the average BPM.
int avgBPM = 0; // avgBPM: Is the variable used to hold the average BPM calculated value.

PFont f, f2; // f & f2 : Are font related variables. Used to store font properties.


//==SETUP==============================================================================================
void setup(){
  size(displayWidth,displayHeight); // Set the size of the display to match the monitor width and height
  smooth(); // Draw all shapes with smooth edges.
  f = createFont("Arial",24); // Initialise the "f" font variable - used for the "calibrating" text displayed at the beginning
  f2 = createFont("Arial",96); // Initialise the "f2" font variable - used for the avgBPM display on screen
  
  for(int i=0; i<numOfRecs; i++){ // Initialise the array of rectangles
    myRecs[i] = new Rectangle(i, numOfRecs);
  }
  
  for(int i=0; i<totalBeats; i++){ // Initialise the BPM array
    BPM[i] = 0;
  }
  
  myPort = new Serial(this, Serial.list()[0], 9600); // Start Serial communication with the Arduino using a baud rate of 9600
  myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
}


//==DRAW==============================================================================================
void draw(){
  background(0); // Set the background to BLACK (this clears the screen each time)
  drawRecs();                                           // Method call to draw the rectangles on the screen
  drawBPM();                                            // Method call to draw the avgBPM value to the top right of the screen
}


//==drawRecs==========================================================================================
void drawRecs(){ // This custom method will draw the rectangles on the screen
  myRecs[0].setSize(arduinoValue);                      // Set the first rectangle to match arduinoValue; any positive value will start the animation.
  for(int i=numOfRecs-1; i>0; i--){ // The loop counts backwards for coding efficiency - and is used to draw all of the rectangles to screen
    myRecs[i].setMult(i);                               // setMulti creates the specific curve pattern.
    myRecs[i].setRed(avgBPM);                           // The rectangles become more "Red" with higher avgBPM values
    myRecs[i].setSize(myRecs[i-1].getH());              // The current rectangle size is determined by the height of the rectangle immediately to it's left
    fill(myRecs[i].getR(),myRecs[i].getG(), myRecs[i].getB()); // Set the colour of this rectangle
    rect(myRecs[i].getX(), myRecs[i].getY(), myRecs[i].getW(), myRecs[i].getH()); // Draw this rectangle
  }
}


//==drawBPM===========================================================================================
void drawBPM(){ // This custom method is used to calculate the avgBPM and draw it to screen.
  sumBPM = 0;                                           // Reset the sumBPM variable
  avgBPM = 0;                                           // Reset the avgBPM variable
  boolean calibrating = false; // calibrating: this boolean variable is used to control when the avgBPM is displayed to screen
  
  for(int i=1; i<totalBeats; i++){
    sumBPM = sumBPM + BPM[i-1];                         // Sum all of the BPM values in the BPM array.
    if(BPM[i-1]<1){ // If any BPM values are equal to 0, then set the calibrating variable to true.
      calibrating = true; // This will be used later to display "calibrating" on the screen.
    }
  }
  avgBPM = sumBPM/(totalBeats-1);                       // Calculate the average BPM from all BPM values
                                                        
  fill(255); // The text will be displayed as WHITE text
  if(calibrating){
    textFont(f);
    text("Calibrating", (4*width)/5, (height/5)); // If the calibrating variable is TRUE, then display the word "Calibrating" on screen
    fill(0); // Change the fill and stroke to black (0) so that other text is "hidden" while calibrating variable is TRUE
    stroke(0);
  } else {
    textFont(f2);
    text(avgBPM, (4*width)/5, (height/5)); // If the calibrating variable is FALSE, then display the avgBPM variable on screen
    stroke(255); // Change the stroke to white (255) to show the white line underlying the word BPM.
  }
  
   textFont(f);
   text("BPM", (82*width)/100, (height/11)); // This will display the underlined word "BPM" when calibrating variable is FALSE.
   line((80*width)/100, (height/10),(88*width)/100, (height/10));
   stroke(0);
}


//==serialEvent===========================================================================================
void serialEvent(Serial cPort){ // This will be triggered every time a "new line" of data is received from the Arduino
 comPortString = cPort.readStringUntil('\n'); // Read this data into the comPortString variable.
 if(comPortString != null) { // If the comPortString variable is not NULL then
   comPortString=trim(comPortString); // trim any white space around the text.
   int i = int(map(Integer.parseInt(comPortString),1,1023,1,height)); // convert the string to an integer, and map the value so that the rectangle will fit within the screen.
   arduinoValue = float(i); // Convert the integer into a float value.
   if (!beat){
     if(arduinoValue>0){ // When a beat is detected, the "trigger" method is called.
       trigger(millis()); // millis() creates a timeStamp of when the beat occured.
       beat=true; // The beat variable is changed to TRUE to register that a beat has been detected.
     }
   }
   if (arduinoValue<1){ // When the Arduino value returns back to zero, we will need to change the beat status to FALSE.
     beat = false;
   }
 }



//==trigger===========================================================================================
void trigger(int time){ // This method is used to calculate the Beats per Minute (BPM) and to store the last 10 BPMs into the BPM[] array.
  totalTime = time - lastTime;                         // totalTime = the current beat time minus the last time there was a beat.
  lastTime = time;                                     // Set the lastTime variable to the current "time" for the next round of calculations.
  BPM[beatCounter] = 60000/totalTime;                  // Calculate BPM from the totalTime. 60000 = 1 minute.
  beatCounter++;                                       // Increment the beatCounter
  if (beatCounter>totalBeats-1){ // Reset the beatCounter when the total number of BPMs have been stored into the BPM[] array.
    beatCounter=0;                                     // This allows us to keep the last 10 BPM calculations at all times.
  }
}


//==sketchFullScreen==========================================================================================
boolean sketchFullScreen() { // This puts Processing into Full Screen Mode
 return true;
}


//==Rectangle CLASS==================================================================================*********
class Rectangle{
  float xPos, defaultY, yPos, myWidth, myHeight, myMultiplier; // Variables used for drawing rectangles
  int blueVal, greenVal, redVal; // Variables used for the rectangle colour
  
  Rectangle(int recNum, int nRecs){ // The rectangles are constructed using two variables. The total number of rectangles to be displayed, and the identification of this rectangle (recNum)
    myWidth = displayWidth/nRecs; // The width of the rectangle is determined by the screen width and the total number of rectangles.
    xPos = recNum * myWidth;                                      // The x Position of this rectangle is determined by the width of the rectangles (all same) and the rectangle identifier.
    defaultY=displayHeight/2; // The default Y position of the rectangle is half way down the screen.
    yPos = defaultY;                                              // yPos is used to adjust the position of the rectangle as the size changes.
    myHeight = 1;                                                 // The height of the rectangle starts at 1 pixel
    myMultiplier = 1;                                             // The myMultiplier variable will be used to create the funnel shaped path for the rectangles.
    redVal = 0;                                                   // The red Value starts off being 0 - but changes with avgBPM. Higher avgBPM means higher redVal
    
    if (recNum>0){ // The blue Value progressively increases with every rectangle (moving to the right of the screen)
      blueVal = (recNum*255)/nRecs;
    } else {
      blueVal = 0;
    }
    greenVal = 255-blueVal;                                       // Initially, the green value is at the opposite end of the spectrum to the blue value.
  }
  
  void setSize(float newSize){ // This is used to set the new size of each rectangle
    myHeight=newSize*myMultiplier;
    yPos=defaultY-(newSize/2);
  }
  
  void setMult(int i){ // The multiplier is a function of COS, which means that it varies from 1 to 0.
    myMultiplier = cos(radians(i)); // You can try other functions to experience different effects.
  }
  
  void setRed(int r){
    redVal = int(constrain(map(float(r), 60, 100, 0, 255),0,255)); // setRed is used to change the redValue based on the "normal" value for resting BPM (60-100).
    greenVal = 255 - redVal;                                       // When the avgBPM > 100, redVal will equal 255, and the greenVal will equal 0.
  }                                                                // When the avgBPM < 60, redVal will equal 0, and greenVal will equal 255.
  
  float getX(){ // get the x Position of the rectangle
    return xPos;
  }
 
  float getY(){ // get the y Position of the rectangle
    return yPos;
  }
  
  float getW(){ // get the width of the rectangle
    return myWidth;
  }
  
  float getH(){ // get the height of the rectangle
    return myHeight;
  }
  
  float getM(){ // get the Multiplier of the rectangle
    return myMultiplier;
  }
  
  int getB(){ // get the "blue" component of the rectangle colour
    return blueVal;
  }
  
  int getR(){ // get the "red" component of the rectangle colour
    return redVal;
  }
  
  int getG(){ // get the "green" component of the rectangle colour
    return greenVal;
  }
}


 

Processing Code Discussion:


The Rectangle class was created to store relevant information about each rectangle. By using a custom class, we were able to design our rectangles any way we wanted. These rectangles have properties and methods which allow us to easily control their position, size and colour. By adding some smart functionality to each rectangle, we were able to get the rectangle to automatically position and colour itself based on key values.

The Serial library is used to allow communication with the Arduino. In this Processing sketch, the values obtained from the Arduino were converted to floats to allow easy calulations of the beats per minute (BPM). I am aware that I have over-engineered the serialEvent method somewhat, because the Arduino is only really sending two values. I didn't really need to convert the String. But I am happy with the end result, and it does the job I needed it to...


This project is quite simple. I designed it so that you could omit the Processing code if you wanted to. In that scenario, you would only be left with a blinking LED that blinks in time with your pulse. The Processing code takes this project to the next level. It provides a nice animation and calculates the beats per minute (BPM).
 
I hope you liked this tutorial. Please feel free to share it, comment or give it a plus one. If you didn't like it, I would still appreciate your constructive feedback.

 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 



 
 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.




Description: Arduino Heart Rate Monitor Rating: 3.5 Reviewer: Unknown ItemReviewed: Arduino Heart Rate Monitor
Back to top