Thingspeak: Analog GPIO

From OnnoWiki
Revision as of 17:50, 4 November 2019 by Onnowpurbo (talk | contribs) (Created page with " #include "ThingSpeak.h" #include <Ethernet.h> #include "secrets.h" byte mac[] = SECRET_MAC; // Set the static IP address to use if the DHCP fails to assign IPAddress i...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
#include "ThingSpeak.h"
#include <Ethernet.h>
#include "secrets.h"

byte mac[] = SECRET_MAC;
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
EthernetClient client; 

unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY; 

void setup() {
  Ethernet.init(10);  // Most Arduino Ethernet hardware
  Serial.begin(115200);  //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(1); // 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() {
  
  float a0 = analogRead(15);
  if (isnan(a0) || isnan(t) ) {
     Serial.println("Failed to read from GPIO 15");
     return;
  }
  
  // set the fields with the values
  ThingSpeak.setField(3, a0); 
  
  // write to the ThingSpeak channel 
  int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  if(x == 200){
    Serial.println("Channel update successful.");
  }
  else{
    Serial.println("Problem updating channel. HTTP error code " + String(x));
  }
     
  delay(20000); // Wait 20 seconds to update the channel again
}