I am updating a website with a set of biometric sensors using a FONA 808 GSM/GPS shield, and having difficulties interfacing the FONA and PulseSensor code.
This is on an Uno.
(And I don't think it matters but the SIM card is Ting Wireless).
Everything is working swimmingly with the FONA uploading simple analog reads (temp and GSR), but then I try incorporating with the code from the PulseSensor
The goal is to upload BPM.
It seems that the interrupts used for timing for the PulseSensor are disrupting the post requests for the FONA.
At first, using the stock "timer2", the first problem was the interference on pin 3 between the interrupt and the FONA TX.
Switching to "timer1," pins do not overlap, BPM reads accurately, but the post requests hang(?) and fail.
Through following the PulseSensor documentation, there's a "quick and dirty" - non-interrupt option. It returns BPM OK outside of the FONA code, but when incorporated, it's all over the place. It does however successfully post.
So I can either post nonsense or not post at all at the moment. I am fairly new at this stuff, so hopefully its something obvious to someone? Please school me.
Any help at all would be wonderfully appreciated!!!!!!
-J
Code makes it go over the maximum 9000 words. Code in comments? What is protocol here?
#include "Adafruit_FONA.h"
//#define PROCESSING_VISUALIZER 1
//#define SERIAL_PLOTTER 5
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
String temperatureUrl = "www.openjulian.com/api/xxxx";
String heartrateUrl = "www.openjulian.com/apixxx";
String gsrUrl = "www.openjulian.com/xxxx";
int pulsePin = A1;
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.
unsigned long lastTime; // used to time the Pulse Sensor samples
unsigned long thisTime; // used to time the Pulse Sensor samples
unsigned long currentTime = 0;
unsigned long previousTime = 0;
//unsigned long fadeTime; // used to time the LED fade
int ThermistorPin = 0;
int Vo;
int GSRPin = A2;
int GSRVal = 0;
float R1 = 10000;
float logR2, R2, T;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
uint8_t type;
bool gprs_on = false;
void setup() {
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
type = fona.type();
Serial.println(F("FONA is OK"));
Serial.print(F("Found "));
switch (type) {
case FONA800L:
Serial.println(F("FONA 800L")); break;
case FONA800H:
Serial.println(F("FONA 800H")); break;
case FONA808_V1:
Serial.println(F("FONA 808 (v1)")); break;
case FONA808_V2:
Serial.println(F("FONA 808 (v2)")); break;
case FONA3G_A:
Serial.println(F("FONA 3G (American)")); break;
case FONA3G_E:
Serial.println(F("FONA 3G (European)")); break;
default:
Serial.println(F("???")); break;
}
// Print module IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("Module IMEI: "); Serial.println(imei);
}
// lastTime = micros();
}
//unsigned long currentTime;
unsigned long previousPostTime;
unsigned long postDelay = 2000;
boolean inter = true;
void loop() {
flushSerial();
currentTime = millis();
// ############# CONNECT TO FONA
if (! gprs_on ) {
if (fona.enableGPRS(true)) {
gprs_on = true;
Serial.println("hurray! turned on!");
} else {
Serial.println("failed to turn on!");
}
}
else {
if (inter == true) {
inter = false;
}
getTemperature();
GSRVal = analogRead(GSRPin);
if (currentTime - previousPostTime > postDelay) {
previousTime = currentTime;
postHeartrate(BPM);
postGSR(GSRVal);
postTemperature(T);
Serial.println ("POST");
}
setupInterrupt(); //CHANGE 'ISR(TIMER2_COMPA_vect)' TO 'getPulse()' IN THE INTERRUPTS TAB!
if (QS == true) { // A Heartbeat Was Found
// BPM and IBI have been Determined
QS = false; // reset the Quantified Self flag for next time
}
Serial.print(" BPM = ");
Serial.print(BPM);
Serial.print(" GSR = ");
Serial.print(GSRVal);
Serial.print(" TEMP = ");
Serial.println(T);
}
}
void flushSerial() {
while (Serial.available())
Serial.read();
}
void postData(String apiEndpoint, int bodyData) {
uint16_t statuscode;
int16_t length;
char url[80];
char data[80];
String stringUrl = apiEndpoint;
stringUrl.concat(bodyData);
Serial.println(stringUrl);
stringUrl.toCharArray(url, 79);
String dataBlank = "{'temperature': 99}";
dataBlank.toCharArray(data, 79);
Serial.println(F("****"));
if (!fona.HTTP_POST_start(url, F("text/plain"), (uint8_t *) data, strlen(data), &statuscode, (uint16_t *)&length)) {
Serial.println("Failed!");
return;
}
while (length > 0) {
while (fona.available()) {
char c = fona.read();
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */
UDR0 = c;
#else
Serial.write(c);
#endif
length--;
if (! length) break;
}
}
Serial.println(F("\n****"));
fona.HTTP_POST_end();
return;
}
int getTemperature() {
Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2 * logR2 + c3 * logR2 * logR2 * logR2));
T = T - 273.15;
T = (T * 9.0) / 5.0 + 32.0;
}
void postGSR(int gsr) {
postData(gsrUrl, gsr);
}
//
void postTemperature(float temp) {
postData(temperatureUrl, temp);
// delay(20);
}
////
void postHeartrate(int rate) {
postData(heartrateUrl, rate);
// // delay(20);
}
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 V = 512; // used to find trough in pulse wave, seeded
volatile int thresh = 530; // used to find instant moment of heart beat, seeded
volatile int amp = 0; // 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 setupInterrupt() {
// Initializes Timer1 to throw an interrupt every 2mS.
TCCR1A = 0x00; // DISABLE OUTPUTS AND PWM ON DIGITAL PINS 9 & 10
TCCR1B = 0x11; // GO INTO 'PHASE AND FREQUENCY CORRECT' MODE, NO PRESCALER
TCCR1C = 0x00; // DON'T FORCE COMPARE
TIMSK1 = 0x01; // ENABLE OVERFLOW INTERRUPT (TOIE1)
ICR1 = 16000; // TRIGGER TIMER INTERRUPT EVERY 2mS
sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}
// THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
// Timer 1 makes sure that we take a reading every 2 miliseconds
ISR(TIMER1_OVF_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 < V) { // T is the trough
V = 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[i] = 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[i] = rate[i + 1]; // and drop the oldest IBI value
runningTotal += rate[i]; // 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 - V; // get amplitude of the pulse wave
thresh = amp / 2 + V; // set thresh at 50% of the amplitude
P = thresh; // reset these for next time
V = thresh;
}
if (N > 2500) { // if 2.5 seconds go by without a beat
thresh = 530; // set thresh default
P = 512; // set P default
V = 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
It seems that the interrupts used for timing for the PulseSensor are disrupting the post requests for the FONA.
At first, using the stock "timer2", the first problem was the interference on pin 3 between the interrupt and the FONA TX.
Switching to "timer1," pins do not overlap, BPM reads accurately, but the post requests hang(?) and fail.
Thank you PaulS, but if I am understanding this correctly, I got the PulseSensor off pin 3 by switching it to Timer1 which is using pins 9&10.
Getting the FONA off pins 2 and 3 isn't ideal because it is a shield...
Is that totally off base?