当从nodemcu将值写入google表格时,心跳传感器(MAX30100)不会读取值。如何解决此错误?

时间:2019-04-23 05:55:03

标签: google-apps-script google-sheets arduino nodemcu arduino-esp8266

我正在设置一个可以监视人的温度和心跳的设备。使用脚本将温度和心跳值立即上传到Google工作表。温度值可以正常工作,但心跳值显示为0。当我在不上传数据的情况下运行代码时,值在Arduino串行绘图仪中可以正常工作。

在Arduino串行绘图仪上显示时获得的所有值。但是不幸的是,当使用postData()时,心跳值显示为0。

#include <ESP8266WiFi.h>
#include "HTTPSRedirect.h"
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#define REPORTING_PERIOD_MS     1000

PulseOximeter pox;
uint32_t tsLastReport = 0;

const char* ssid = "";
const char* password = "";

// The ID below comes from Google Sheets.
// Towards the bottom of this page, it will explain how this can be obtained
const char *GScriptId = "gscriptid";

// Push data on this interval
//const int dataPostDelay = 900000;  // 15 minutes = 15 * 60 * 1000

const char* host = "script.google.com";
const char* googleRedirHost = "script.googleusercontent.com";

const int httpsPort =  443;
HTTPSRedirect client(httpsPort);

// Prepare the url (without the varying data)
//String url = String("/macros/s/") + GScriptId + "/exec?";

const char* fingerprint = "some fingerprint";

// We will take analog input from A0 pin 
const int AnalogIn     = A0; 

// Callback (registered below) fired when a pulse is detected
void onBeatDetected()
{
  Serial.println("Beat!");
}

void setup() {
  Serial.begin(115200);
  Serial.println("Connecting to wifi: ");
  Serial.println(ssid);
  Serial.flush();

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" IP address: ");
  Serial.println(WiFi.localIP());


  Serial.print(String("Connecting to "));
  Serial.println(host);

  bool flag = false;
  for (int i=0; i<5; i++){
    int retval = client.connect(host, httpsPort);
    if (retval == 1) {
       flag = true;
       break;
    }
    else
      Serial.println("Connection failed. Retrying...");
  }

  // Connection Status, 1 = Connected, 0 is not.
  Serial.println("Connection Status: " + String(client.connected()));
  Serial.flush();

  if (!flag){
    Serial.print("Could not connect to server: ");
    Serial.println(host);
    Serial.println("Exiting...");
    Serial.flush();
    return;
  }

  // Data will still be pushed even certification don't match.
  if (client.verify(fingerprint, host)) {
    Serial.println("Certificate match.");
  } else {
    Serial.println("Certificate mis-match");
  }

   Serial.print("Initializing pulse oximeter..");

  // Initialize the PulseOximeter instance
  // Failures are generally due to an improper I2C wiring, missing power supply
  // or wrong target chip
  if (!pox.begin()) {
    Serial.println("FAILED");
    for (;;);
  } else {
    Serial.println("SUCCESS");
  }

  pox.setOnBeatDetectedCallback(onBeatDetected);

}

// This is the main method where data gets pushed to the Google sheet
void postData(float temp, float bpm){
  if (!client.connected()){
    Serial.println("Connecting to client again..."); 
    client.connect(host, httpsPort);
  }
  String urlFinal = String("/macros/s/") + GScriptId + "/exec?temperature=" + String(temp) + "&bpm=" + String(bpm);
  client.printRedir(urlFinal, host, googleRedirHost);
}

// Continue pushing data at a given interval
void loop() {

  int analogValue = analogRead(A0);
  float millivolts = (analogValue/1024.0) * 3300; //3300 is the voltage provided by NodeMCU
  float celsius = millivolts/10;
//  Serial.print("in DegreeC=   ");
//  Serial.println(celsius);
//  // Post these information
//  Serial.println("/");
//  postData(celsius);
//  Serial.println("/");
//  delay (10000);
  // Make sure to call update as fast as possible
  pox.update();

  // Asynchronously dump heart rate and oxidation levels to the serial
  // For both, a value of 0 means "invalid"
  if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
    Serial.print("Heart rate:");
    float bpm = pox.getHeartRate();
    Serial.print(bpm);
//    Serial.print("bpm / SpO2:");
//    float spo2 = pox.getSpO2();
//    Serial.print(spo2);
//    Serial.println("%");
    Serial.println();
    Serial.print("TEMPRATURE = ");
    Serial.print(celsius);
    Serial.print("*C");
    postData(celsius, bpm);
    Serial.println();

    tsLastReport = millis();
}
}

我希望代码将温度和心跳值写入格式化的Google表格中。

Google表格图片

enter image description here

//Google script code

function doGet(e) { 
  Logger.log( JSON.stringify(e) );  // view parameters
  var result = 'Ok'; // assume success
  if (e.parameter == 'undefined') {
    result = 'No Parameters';
  }
  else {
    var sheet_id = 'sheetid';       // Spreadsheet ID
    var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();     // get Active sheet
    var newRow = sheet.getLastRow() + 1;                        
    var rowData = [];
    rowData[0] = new Date();                                            // Timestamp in column A
    for (var param in e.parameter) {
      Logger.log('In for loop, param=' + param);
      var value = stripQuotes(e.parameter[param]);
      Logger.log(param + ':' + e.parameter[param]);
      switch (param) {
        case 'temperature': //Parameter
          rowData[1] = value; //Value in column B
          result = 'Written on column B';
          break;
        case 'bpm': //Parameter
          rowData[2] = value; //Value in column C
          result += ' ,Written on column C';
          break;  
        default:
          result = "unsupported parameter";
      }
    }
    Logger.log(JSON.stringify(rowData));
    // Write new row below
    var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
    newRange.setValues([rowData]);
  }
  // Return result of operation
  return ContentService.createTextOutput(result);
}
/**
* Remove leading and trailing single or double quotes
*/
function stripQuotes( value ) {
  return value.replace(/^["']|['"]$/g, "");
}
// End of file

0 个答案:

没有答案