使用Thingspeak和arduino。对讲命令错误

时间:2019-12-20 05:30:23

标签: arduino iot

当前,我的代码中的对讲命令无法正常工作。它曾经可以单独工作,但是当我将其与湿度,温度,心率和发送给thingspeak结合使用时,它就不再起作用了。当我删除void循环中的代码,留下gettalkbackvoid gettalkback 2时,代码就起作用了。我完全不知道为什么它不起作用。

#include "ThingSpeak.h"
#include <DHT.h>
#include <Ethernet.h>
#include <LiquidCrystal.h>
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.   
LiquidCrystal lcd(10, 9, 5, 4, 3, 2); //numbers of interface pins
int sensorPin = A8;
float tempC;
#define redLED 8
#define TSLED 41
#define DHTPIN 6
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
#include <Wire.h>

byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
unsigned long myChannelNumber = ;
const char * myWriteAPIKey = "";

const String channelsAPIKey = "";
const String talkBackAPIKey = "";
const String talkBackID = "";
const String talkCommandID = "";
const unsigned int getTalkBackInterval = 10 * 1000;
const unsigned int updateChannelsInterval = 15 * 1000;
String talkBackCommand;


long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
char charIn;

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(172, 17, 171, 199);
IPAddress myDns(172, 17, 171, 254);

float get_temperature(int pin)
{
  float temperature = analogRead(pin); // Calculate the temperature based on the reading and send that value back
  float voltage = temperature * 5.0;
  voltage = voltage / 1024.0;
  return ((voltage - 0.5) * 100);
}

//  Variables
const int PulseWire = A5;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int blinkLED = 22;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"


EthernetClient client;

void setup()
{
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(TSLED, OUTPUT);
  dht.begin();
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(blinkLED);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);
  pulseSensor.begin();

  Ethernet.init(10);  // Most Arduino Ethernet hardware
  Serial.begin(9600);  //Initialize serial
  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware)
    {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true)
      {
        delay(10); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF)
    {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  }
  else
  {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);

  ThingSpeak.begin(client);  // Initialize ThingSpeak
}

void loop()
{
  getTalkBack();
  void getTalkBack2();
  float h = dht.readHumidity();
  {
    tempC = get_temperature(sensorPin);
  }

  if (tempC < 31)
  {
    lcd.setCursor(0, 0);
    lcd.print(tempC);
    lcd.print(" "); //print the temp
    lcd.print((char)223); // to get ° symbol
    lcd.print("C");
    lcd.print("  ");
    lcd.print(h);
    lcd.print("%");
  }
  else if (tempC > 31)
  {
    lcd.setCursor(0, 0);
    lcd.print(tempC);
    lcd.print(" "); //print the temp
    lcd.print((char)223); // to get ° symbol
    lcd.print("C");
    lcd.print("  ");
    lcd.print(h);
    lcd.print("%");
  }
  delay(20); //  take a break

  if (pulseSensor.sawStartOfBeat())
  {
    int  myBPM = pulseSensor.getBeatsPerMinute();
    lcd.setCursor(0, 1);
    lcd.print("BPM: ");
    lcd.print(myBPM);
  }

  delay(20);                    // considered best practice in a simple sketch.

  // Write to ThingSpeak channel.

  ThingSpeak.setField(1, tempC);
  ThingSpeak.setField(2, h);
  int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  if (x == 200)
  {
    Serial.println("Channel update successful.");
  }
  delay(750);
}
void getTalkBack()
{

  String tsData;
  tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
  if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
  {
    if (client.connect("api.thingspeak.com", 80))
    {
      client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
      client.println();
      lastConnectionTimeTalkBack = millis();
      if (client.connected())
      {
        Serial.println("---------------------------------------");
        Serial.println("GET TalkBack command");
        Serial.println();
        Serial.println("Connecting to ThingSpeak");
        Serial.println();
        Serial.println();
        Serial.println("Server response");
        Serial.println();
        failedCounterTalkBack = 0;

        while (client.connected() && !client.available()) delay(2000); //waits for data
        while (client.connected() || client.available())
        {
          charIn = client.read();
          talkBackCommand += charIn;
          Serial.print(charIn);
          if (talkBackCommand.indexOf("LED_OFF", charIn) != 1)     // Check if LED_OFF msg received
            digitalWrite(TSLED, LOW);              // LED OFF
        }
        if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
        {
          Serial.println();
          Serial.println();
          Serial.println("Disconnected");
        }

      }
      else
      {
        failedCounterTalkBack++;
        Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
        Serial.println();
        lastConnectionTimeChannels = millis();
      }
    }
  }
  if (failedCounterTalkBack > 3 )
  {
    startEthernet();
  }
  tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
  if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
  {
    if (client.connect("api.thingspeak.com", 80))
    {
      client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
      client.println();
      lastConnectionTimeTalkBack = millis();
      if (client.connected())
      {
        Serial.println("---------------------------------------");
        Serial.println("GET TalkBack command");
        Serial.println();
        Serial.println("Connecting to ThingSpeak");
        Serial.println();
        Serial.println();
        Serial.println("Server response");
        Serial.println();
        failedCounterTalkBack = 0;

        delay(1000);
        while (client.connected() && !client.available()) delay(2000); //waits for data
        while (client.connected() || client.available())
        {
          charIn = client.read();
          talkBackCommand += charIn;
          Serial.print(charIn);
          if (talkBackCommand.indexOf("LED_ON", charIn) != 1)     // Check if LED_OFF msg received
            digitalWrite(TSLED, HIGH);              // LED ON

        }

        if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
        {
          Serial.println();
          Serial.println();
          Serial.println("Disconnected");
          Serial.println();

        }
      }
      else
      {
        failedCounterTalkBack++;
        Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
        Serial.println();
        lastConnectionTimeChannels = millis();
      }
    }
  }
  if (failedCounterTalkBack > 3 )
  {
    startEthernet();
  }

  client.stop();
  Serial.flush();
}

void startEthernet()
{
  client.stop();
  Serial.println();
  Serial.println();
  Serial.println("****************************************");
  Serial.println("Connecting Arduino to network...");
  delay(1000);
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println("****************************************");
    Serial.println();
  }
  else
  {
    Serial.println("Arduino connected to network using DHCP");
    Serial.println("****************************************");
    Serial.println();
  }
  delay(1000);
}

0 个答案:

没有答案