Devices & Components
Arduino Uno Rev3
Jumper wires (generic)
KY-039 heartbeat sensor
Project description
Code
Final version
c_cpp
The program reads the heartbeat and prints the rate in the serial window.
1#define samp_siz 4 2#define rise_threshold 4 3 4// Pulse Monitor Test Script 5int sensorPin = 0; 6 7void setup() { 8 Serial.begin(9600); 9} 10 11void loop () 12{ 13 float reads[samp_siz], sum; 14 long int now, ptr; 15 float last, reader, start; 16 float first, second, third, before, print_value; 17 bool rising; 18 int rise_count; 19 int n; 20 long int last_beat; 21 22 for (int i = 0; i < samp_siz; i++) 23 reads[i] = 0; 24 sum = 0; 25 ptr = 0; 26 27 while(1) 28 { 29 // calculate an average of the sensor 30 // during a 20 ms period (this will eliminate 31 // the 50 Hz noise caused by electric light 32 n = 0; 33 start = millis(); 34 reader = 0.; 35 do 36 { 37 reader += analogRead (sensorPin); 38 n++; 39 now = millis(); 40 } 41 while (now < start + 20); 42 reader /= n; // we got an average 43 44 // Add the newest measurement to an array 45 // and subtract the oldest measurement from the array 46 // to maintain a sum of last measurements 47 sum -= reads[ptr]; 48 sum += reader; 49 reads[ptr] = reader; 50 last = sum / samp_siz; 51 // now last holds the average of the values in the array 52 53 // check for a rising curve (= a heart beat) 54 if (last > before) 55 { 56 rise_count++; 57 if (!rising && rise_count > rise_threshold) 58 { 59 // Ok, we have detected a rising curve, which implies a heartbeat. 60 // Record the time since last beat, keep track of the two previous 61 // times (first, second, third) to get a weighed average. 62 // The rising flag prevents us from detecting the same rise more than once. 63 rising = true; 64 first = millis() - last_beat; 65 last_beat = millis(); 66 67 // Calculate the weighed average of heartbeat rate 68 // according to the three last beats 69 print_value = 60000. / (0.4 * first + 0.3 * second + 0.3 * third); 70 71 Serial.print(print_value); 72 Serial.print('\n'); 73 74 third = second; 75 second = first; 76 77 } 78 } 79 else 80 { 81 // Ok, the curve is falling 82 rising = false; 83 rise_count = 0; 84 } 85 before = last; 86 87 88 ptr++; 89 ptr %= samp_siz; 90 91 } 92} 93 94 95
Downloadable files
Circuit
Circuit

Circuit
Circuit

Comments
Only logged in users can leave comments