(心跳第一個PulseSensor_wt_BT.ino)
#include <SoftwareSerial.h>// import the serial library
SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=12; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer
// Variables
int pulsePin = 0; // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13; // pin to blink led at each beat
int fadePin = 5; // pin to do fancy classy fading blink at each beat
int fadeRate = 0; // used to fade LED on with PWM on fadePin
// Volatile Variables, used in the interrupt service routine!
volatile int BPM; // int that holds raw Analog in 0. updated every 2mS
volatile int Signal; // holds the incoming raw data
volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false; // becomes true when Arduoino finds a beat.
// Regards Serial OutPut -- Set This Up to your needs
static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse
void setup(){
pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat!
pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat!
Serial.begin(115200); // we agree to talk fast!
interruptSetup(); // sets up to read Pulse Sensor signal every 2mS
// UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
// AND APPLY THAT VOLTAGE TO THE A-REF PIN
// analogReference(EXTERNAL);
Genotronex.begin(9600);
Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
pinMode(ledpin,OUTPUT);
}
// Where the Magic Happens
void loop(){
serialOutput() ;
if (QS == true){ // A Heartbeat Was Found
// BPM and IBI have been Determined
// Quantified Self "QS" true when arduino finds a heartbeat
digitalWrite(blinkPin,HIGH); // Blink LED, we got a beat.
fadeRate = 255; // Makes the LED Fade Effect Happen
// Set 'fadeRate' Variable to 255 to fade LED with pulse
serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
QS = false; // reset the Quantified Self flag for next time
}
else {
digitalWrite(blinkPin,LOW); // There is not beat, turn off pin 13 LED
}
ledFadeToBeat(); // Makes the LED Fade Effect Happen
if (Genotronex.available()){
BluetoothData=Genotronex.read();
if(BluetoothData=='1'){ // if number 1 pressed ....
digitalWrite(ledpin,1);
Genotronex.println("LED On D12 ON ! ");
}
if (BluetoothData=='0'){// if number 0 pressed ....
digitalWrite(ledpin,0);
Genotronex.println("LED On D12 Off ! ");
}
}
delay(20); // take a break
}
心跳第二個(AllSerialHandling.ino)
void serialOutput(){ // Decide How To Output Serial.
if (serialVisual == true){
arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial Monitor Visualizer
} else{
sendDataToSerial('S', Signal); // goes to sendDataToSerial function
}
}
// Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
if (serialVisual == true){ // Code to Make the Serial Monitor Visualizer Work
Serial.print("*** Heart-Beat Happened *** "); //ASCII Art Madness
Serial.print("BPM: ");
Genotronex.println("HEART RATE IS ");
Genotronex.println(BPM);
Serial.print(BPM);
Serial.print(" ");
} else{
sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix
sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix
}
}
// Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
Serial.print(symbol);
Serial.println(data);
}
void ledFadeToBeat(){
fadeRate -= 15; // set LED fade value
fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers!
analogWrite(fadePin,fadeRate); // fade LED
}
// Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){
const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 1024; // sensor maximum, discovered through experiment
int sensorReading = data;
// map the sensor range to a range of 12 options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
// do something different depending on the
// range value:
switch (range) {
case 0:
Serial.println(""); /////ASCII Art Madness
break;
case 1:
Serial.println("---");
break;
case 2:
Serial.println("------");
break;
case 3:
Serial.println("---------");
break;
case 4:
Serial.println("------------");
break;
case 5:
Serial.println("--------------|-");
break;
case 6:
Serial.println("--------------|---");
break;
case 7:
Serial.println("--------------|-------");
break;
case 8:
Serial.println("--------------|----------");
break;
case 9:
Serial.println("--------------|----------------");
break;
case 10:
Serial.println("--------------|-------------------");
break;
case 11:
Serial.println("--------------|-----------------------");
break;
心跳第三個(Interrupt.ino)
volatile int rate[10]; // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0; // used to determine pulse timing
volatile unsigned long lastBeatTime = 0; // used to find IBI
volatile int P =512; // used to find peak in pulse wave, seeded
volatile int T = 512; // used to find trough in pulse wave, seeded
volatile int thresh = 525; // used to find instant moment of heart beat, seeded
volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM
void interruptSetup(){
// Initializes Timer2 to throw an interrupt every 2mS.
TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER
OCR2A = 0X7C; // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}
// THIS IS THE TIMER 2 INTERRUPT SERVICE ROUTINE.
// Timer 2 makes sure that we take a reading every 2 miliseconds
ISR(TIMER2_COMPA_vect){ // triggered when Timer2 counts to 124
cli(); // disable interrupts while we do this
Signal = analogRead(pulsePin); // read the Pulse Sensor
sampleCounter += 2; // keep track of the time in mS with this variable
int N = sampleCounter - lastBeatTime; // monitor the time since the last beat to avoid noise
// find the peak and trough of the pulse wave
if(Signal < thresh && N > (IBI/5)*3){ // avoid dichrotic noise by waiting 3/5 of last IBI
if (Signal < T){ // T is the trough
T = Signal; // keep track of lowest point in pulse wave
}
}
if(Signal > thresh && Signal > P){ // thresh condition helps avoid noise
P = Signal; // P is the peak
} // keep track of highest point in pulse wave
// NOW IT'S TIME TO LOOK FOR THE HEART BEAT
// signal surges up in value every time there is a pulse
if (N > 250){ // avoid high frequency noise
if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ){
Pulse = true; // set the Pulse flag when we think there is a pulse
// digitalWrite(blinkPin,HIGH); // turn on pin 13 LED
IBI = sampleCounter - lastBeatTime; // measure time between beats in mS
lastBeatTime = sampleCounter; // keep track of time for next pulse
if(secondBeat){ // if this is the second beat, if secondBeat == TRUE
secondBeat = false; // clear secondBeat flag
for(int i=0; i<=9; i++){ // seed the running total to get a realisitic BPM at startup
rate = IBI;
}
}
if(firstBeat){ // if it's the first time we found a beat, if firstBeat == TRUE
firstBeat = false; // clear firstBeat flag
secondBeat = true; // set the second beat flag
sei(); // enable interrupts again
return; // IBI value is unreliable so discard it
}
// keep a running total of the last 10 IBI values
word runningTotal = 0; // clear the runningTotal variable
for(int i=0; i<=8; i++){ // shift data in the rate array
rate = rate[i+1]; // and drop the oldest IBI value
runningTotal += rate; // add up the 9 oldest IBI values
}
rate[9] = IBI; // add the latest IBI to the rate array
runningTotal += rate[9]; // add the latest IBI to runningTotal
runningTotal /= 10; // average the last 10 IBI values
BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM!
QS = true; // set Quantified Self flag
// QS FLAG IS NOT CLEARED INSIDE THIS ISR
}
}
if (Signal < thresh && Pulse == true){ // when the values are going down, the beat is over
// digitalWrite(blinkPin,LOW); // turn off pin 13 LED
Pulse = false; // reset the Pulse flag so we can do it again
amp = P - T; // get amplitude of the pulse wave
thresh = amp/2 + T; // set thresh at 50% of the amplitude
P = thresh; // reset these for next time
T = thresh;
}
if (N > 2500){ // if 2.5 seconds go by without a beat
thresh = 512; // set thresh default
P = 512; // set P default
T = 512; // set T default
lastBeatTime = sampleCounter; // bring the lastBeatTime up to date
firstBeat = true; // set these to avoid noise
secondBeat = false; // when we get the heartbeat back
}
sei(); // enable interrupts when youre done!
}// end isr
GPS部分
#include <SoftwareSerial.h>
#include <TinyGPS.h>
SoftwareSerial mySerial(10, 11);
TinyGPS gps;
void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);
void setup()
{
// Oploen serial communications and wait for port to open:
Serial.begin(9600);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
delay(1000);
Serial.println("uBlox Neo 6M");
Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
Serial.println("by Mikal Hart");
Serial.println();
Serial.print("Sizeof(gpsobject) = ");
Serial.println(sizeof(TinyGPS));
Serial.println();
}
void loop() // run over and over
{
bool newdata = false;
unsigned long start = millis();
// Every 5 seconds we print an update
while (millis() - start < 5000)
{
if (mySerial.available())
{
char c = mySerial.read();
//Serial.print(c); // uncomment to see raw GPS data
if (gps.encode(c))
{
newdata = true;
break; // uncomment to print new data immediately!
}
}
}
if (newdata)
{
Serial.println("Acquired Data");
Serial.println("-------------");
gpsdump(gps);
Serial.println("-------------");
Serial.println();
}
}
void gpsdump(TinyGPS &gps)
{
long lat, lon;
float flat, flon;
unsigned long age, date, time, chars;
int year;
byte month, day, hour, minute, second, hundredths;
unsigned short sentences, failed;
// On Arduino, GPS characters may be lost during lengthy Serial.print()
// On Teensy, Serial prints to USB, which has large output buffering and
// runs very fast, so it's not necessary to worry about missing 4800
// baud GPS characters.
void printFloat(double number, int digits)
{
// Handle negative numbers
if (number < 0.0)
{
Serial.print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i=0; i<digits; ++i)
rounding /= 10.0;
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
Serial.print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0)
Serial.print(".");
// Extract digits from the remainder one at a time
while (digits-- > 0)
{
remainder *= 10.0;
int toPrint = int(remainder);
Serial.print(toPrint);
remainder -= toPrint;
}
}
#include <SoftwareSerial.h>// import the serial library
#include <TinyGPS.h>
SoftwareSerial gpsSerial(12, 11); // RX, TX(gps腳位)
int ledpin=15; // l在D13上導致將顯示閃爍開/關ed on D13 will show blink on / off
int BluetoothData; // 計算機給出的數據the data given from Computer
// Variables
int pulsePin = 0; // 脈衝傳感器紫色線連接到模擬引腳Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13; // 引腳在每個節拍處閃爍pin to blink led at each beat
int fadePin = 5; // 在每個節拍處做花式優雅的褪色眨眼pin to do fancy classy fading blink at each beat
int fadeRate = 0; // 用於在fadePin上用PWM淡出LEDused to fade LED on with PWM on fadePin
// Volatile Variables, used in the interrupt service routine!
volatile int BPM; // int保持原始的模擬輸入0.每2毫秒更新一次int that holds raw Analog in 0. updated every 2mS
volatile int Signal; // 保存傳入的原始數據holds the incoming raw data
volatile int IBI = 600; // int保存節拍之間的時間間隔! 必須種子int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false; // 當用戶的實時心跳被檢測到時為“真”。 “假”不是“現場拍”"True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false; // 當Arduoino發現一個節拍成為現實becomes true when Arduoino finds a beat.
// /關心串行輸出 - 設置這符合您的需求Regards Serial OutPut -- Set This Up to your needs
static boolean serialVisual = false; // 默認設置為“false”。 重新設置為“真”來查看Arduino串行監視器ASCII可視脈衝Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse
void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);
void setup(){
pinMode(blinkPin,OUTPUT); // 別針會閃爍你的心跳pin that will blink to your heartbeat!
pinMode(fadePin,OUTPUT); // 別針會褪色到你的心跳pin that will fade to your heartbeat!
Serial.begin(115200); // 我們同意快速交談we agree to talk fast!
// 設置每2mS讀脈衝傳感器信號sets up to read Pulse Sensor signal every 2mS
// 如果您正在為低電壓脈衝傳感器供電,請聯繫下一行UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
// 並將該電壓應用於A-REF引腳AND APPLY THAT VOLTAGE TO THE A-REF PIN
// analogReference(EXTERNAL);
btSerial.begin(9600);
btSerial.println("Bluetooth On please press 1 or 0 blink LED ..");
pinMode(ledpin,OUTPUT);
// Oploen串行通信並等待端口打開:Oploen serial communications and wait for port to open:
Serial.begin(9600);
// 設置SoftwareSerial端口的數據速率set the data rate for the SoftwareSerial port
gpsSerial.begin(9600);
btSerial.begin(9600);
delay(1000);
Serial.println("uBlox Neo 6M");
Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
Serial.println("by Mikal Hart");
Serial.println();
Serial.print("Sizeof(gpsobject) = ");
Serial.println(sizeof(TinyGPS));
Serial.println();
interruptSetup();
}
// Where the Magic Happens
void loop(){
serialOutput() ;
if (QS == true){ // 心跳被發現A Heartbeat Was Found
// BPM和IBI已經確定BPM and IBI have been Determined
// 當arduino發現心跳時,量化的自我Quantified Self "QS" true when arduino finds a heartbeat
digitalWrite(blinkPin,HIGH); // 閃爍LED,我們得到了一個節拍Blink LED, we got a beat.
fadeRate = 255; // 使LED淡化效果發生Makes the LED Fade Effect Happen
// 將“fadeRate”變量設置為255,使脈沖淡入Set 'fadeRate' Variable to 255 to fade LED with pulse
serialOutputWhenBeatHappens(); // 發生一擊,輸出串行A Beat Happened, Output that to serial.
QS = false; // 重新設置下一次的量化自標記reset the Quantified Self flag for next time
}
else {
digitalWrite(blinkPin,LOW); // 沒有拍子,關掉13號LED指示燈There is not beat, turn off pin 13 LED
}
ledFadeToBeat(); // 使LED淡化效果發生Makes the LED Fade Effect Happen
if (btSerial.available()){
BluetoothData=btSerial.read();
if(BluetoothData=='1'){ // if number 1 pressed ....
digitalWrite(ledpin,1);
btSerial.println("LED On D12 ON ! ");
}
if (BluetoothData=='0'){// if number 0 pressed ....
digitalWrite(ledpin,0);
btSerial.println("LED On D12 Off ! ");
}
}
delay(2000); // take a break
bool newdata = true;
unsigned long start = millis();
// Every 5 seconds we print an update
while (millis() - start < 5000)
{
if (gpsSerial.available())
{
char c = gpsSerial.read();
//Serial.print(c); // 取消註釋查看原始GPS數據uncomment to see raw GPS data
if (gps.encode(c))
{
newdata = true;
break; // 立即取消打印新數據的註釋!uncomment to print new data immediately!
}
}
}
if (newdata)
{
Serial.println("Acquired Data");
Serial.println("-------------");
gpsdump(gps);
Serial.println("-------------");
Serial.println();
}
}
作者: 小新手 時間: 2017-12-28 19:04
void serialOutput(){ // Decide How To Output Serial.
if (serialVisual == true){
arduinoSerialMonitorVisual('-', Signal); // 去串行監視器展示台的功能goes to function that makes Serial Monitor Visualizer
} else{
sendDataToSerial('S', Signal); // 去sendDataToSerial函數goes to sendDataToSerial function
}
}
// 決定如何輸出BPM和IBI數據Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
if (serialVisual == true){ // 使串行監視器可視化工作的代碼 Code to Make the Serial Monitor Visualizer Work
Serial.print("*** Heart-Beat Happened *** "); //ASCII藝術瘋狂ASCII Art Madness
Serial.print("BPM: ");
btSerial.println("HEART RATE IS ");
btSerial.println(BPM);
Serial.print(BPM);
Serial.print(" ");
} else{
sendDataToSerial('B',BPM); // 用“B”前綴發送心率send heart rate with a 'B' prefix
sendDataToSerial('Q',IBI); // 用“Q”前綴在節拍之間發送時間send time between beats with a 'Q' prefix
}
}
// 將數據發送到脈衝傳感器處理應用程序,本地Mac應用程序或第三方串行讀取器Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
Serial.print(symbol);
Serial.println(data);
}
void ledFadeToBeat(){
fadeRate -= 15; // 設置LED淡入值set LED fade value
fadeRate = constrain(fadeRate,0,255); // 保持LED衰減價值進入負數keep LED fade value from going into negative numbers!
analogWrite(fadePin,fadeRate); // 淡入LEDfade LED
}
// Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){
const int sensorMin = 0; // 傳感器最小值,通過實驗發現sensor minimum, discovered through experiment
const int sensorMax = 1024; // 傳感器最大值,通過實驗發現sensor maximum, discovered through experiment
int sensorReading = data;
// 將傳感器範圍映射到12個選項的範圍內map the sensor range to a range of 12 options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
// 做一些不同的取決於do something different depending on the
// 範圍值range value:
switch (range) {
case 0:
Serial.println(""); /////ASCII Art Madness
break;
case 1:
Serial.println("---");
break;
case 2:
Serial.println("------");
break;
case 3:
Serial.println("---------");
break;
case 4:
Serial.println("------------");
break;
case 5:
Serial.println("--------------|-");
break;
case 6:
Serial.println("--------------|---");
break;
case 7:
Serial.println("--------------|-------");
break;
case 8:
Serial.println("--------------|----------");
break;
case 9:
Serial.println("--------------|----------------");
break;
case 10:
Serial.println("--------------|-------------------");
break;
case 11:
Serial.println("--------------|-----------------------");
break;
}
}
void printFloat(double number, int digits)
{
// 處理負數Handle negative numbers
if (number < 0.0)
{
Serial.print('-');
number = -number;
}
// 圓形正確打印(1.999,2)打印為“2.00”Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i=0; i<digits; ++i)
rounding /= 10.0;
number += rounding;
// 提取數字的整數部分並打印出來Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
Serial.print(int_part);
// 打印小數點,但只有在數字之外Print the decimal point, but only if there are digits beyond
if (digits > 0)
Serial.print(".");
// 一次提取餘數中的數字Extract digits from the remainder one at a time
while (digits-- > 0)
{
remainder *= 10.0;
int toPrint = int(remainder);
Serial.print(toPrint);
remainder -= toPrint;
}
}
void gpsdump(TinyGPS &gps)
{
long lat, lon;
float flat, flon;
unsigned long age, date, time, chars;
int year;
byte month, day, hour, minute, second, hundredths;
unsigned short sentences, failed;
// 在Arduino上,在冗長的Serial.print()中可能會丟失GPS字符On Arduino, GPS characters may be lost during lengthy Serial.print()
// 在Teensy上,串行打印到USB,它具有較大的輸出緩沖和On Teensy, Serial prints to USB, which has large output buffering and
// 運行速度非常快,所以沒必要擔心丟失4800runs very fast, so it's not necessary to worry about missing 4800
// 波特GPS字符。baud GPS characters.