Scheitern beim Thingspeak einbinden

Hallo zusammen,

es geht um einen Batterieüberwachung auf einem Gartengrundstück welches mit einer Richtfunkstrecke angebunden ist, hierbei habe ich Probleme Thingspeak einzubinden und stehe auf dem Schlauch vielleicht kann mir einer weiter helfen.

Gruß Markus

hier mal der Code

#include <ThingSpeak.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   50
#define VOLTAGE_MAX 16.0 
#define VOLTAGE_MAXCOUNTS 1023.0
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xff, 0x75, 0x45, 0xED };
IPAddress ip(192, 168, 1, 10); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
File webFile;               // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
unsigned long myChannelNumber = 11111; // Thingspeak
const char * myWriteAPIKey = "XXXXXXXXXXX"; // Thingspeak
void setup()
{
    // disable Ethernet chip
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);
    Serial.begin(9600);       // for debugging
    
    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;    // init failed
    }
    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
    
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients
    ThingSpeak.begin(client);
}
void loop()
{
    EthernetClient client = server.available();  // try to get client
    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // buffer first part of HTTP request in HTTP_req array (string)
                // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                if (req_index < (REQ_BUF_SZ - 1)) {
                    HTTP_req[req_index] = c;          // save HTTP request character
                    req_index++;
                }
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    // remainder of header follows below, depending on if
                    // web page or XML page is requested
                    // Ajax request - send XML file
                    if (StrContains(HTTP_req, "ajax_inputs")) {
                        // send rest of HTTP header
                        client.println("Content-Type: text/xml");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send XML file containing input states
                        XML_response(client);
                    }
                    else {  // web page request
                        // send rest of HTTP header
                        client.println("Content-Type: text/html");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send web page
                        webFile = SD.open("index.htm");        // open web page file
                        if (webFile) {
                            while(webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    // display received HTTP request on serial port
                    Serial.print(HTTP_req);
                    // reset buffer index and all buffer elements to 0
                    req_index = 0;
                    StrClear(HTTP_req, REQ_BUF_SZ);
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                } 
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
    int sensorValue = analogRead(A2);
    float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);
}
// send the XML file containing analog value
void XML_response(EthernetClient cl)
{
    int analog_val;
    
    cl.print("<?xml version = \"1.0\" ?>");
    cl.print("<inputs>");
    // read analog pin A2
    analog_val = analogRead(2);
    cl.print("<analog>");
    cl.print(analog_val);
    cl.print("</analog>");
    cl.print("</inputs>");
}
// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
    for (int i = 0; i < length; i++) {
        str[i] = 0;
    }
}
// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
    char found = 0;
    char index = 0;
    char len;
    len = strlen(str);
    
    if (strlen(sfind) > len) {
        return 0;
    }
    while (index < len) {
        if (str[index] == sfind[found]) {
            found++;
            if (strlen(sfind) == found) {
                return 1;
            }
        }
        else {
            found = 0;
        }
        index++;
    }
    return 0;
    ThingSpeak.writeField(myChannelNumber, 1, voltage, myWriteAPIKey);
  delay(20000); // ThingSpeak will only accept updates every 15 seconds.
}

Um Dir zu helfen sind etwas mehr Informationen notwendig.

  1. Auf welchem Arduino läuft das? (Ist es ein Uno, könnte der RAM schon knapp werden bei den ganzen Strings und Libs die Du verwendest
  2. Welcher Art sind die Probleme? Gibt es Fehlermeldungen? Was ist der SOLL und was der IST Zustand (und nein "geht nicht" ist keine Problembeschreibung :slight_smile:

Dein Code ist nicht nur Client für Thingspeak sondern selbst auch Server. Im setup() taucht folgende Zeile auf:

ThingSpeak.begin(client);

Allerdings wird "client" vorher nirgendwo definiert / deklariert. Evtl. ist das schon Teil des Problems.

Mario.

Hallo Mario,

Ich bin dermaßen eingerostet in Sachen Programmierung das ist Jahre her letzte Projekt war 2011 für ein Ballonprojekt.

Ziel ist es auf der Webseite welche auf der SD Karte ist mit einem Frame zusätzlich zu dem visuellem Anzeigeinstrument den Spannungsverlauf zeitlich einzubinden um zu sehen wie die Solarzellen nachladen, später noch dazu den Ladestrom.
Laufen sollte das auf einem Uno den ich aus dem Ballonprojekt liegen habe schon wegen dem Stromverbrauch es reich das der Richtfunkspiegel 350mA aus dem 12V saugt. deswegen auch ein DCDC Wandler Verwendung findet.

als Orientierung für Thingspeak habe ich mir den Code im link angesehen
https://github.com/mathworks/thingspeak-arduino/blob/master/examples/WriteVoltage/WriteVoltage.ino

Gruß Markus

In Deinem Code ist einiges durcheinander geraten.

Schau Dir mal das Beispiel WifiWebClient an.

Die Bibliothek Thinkspeak.h nimmt Dir viel Aufwand ab.
Ich kann Dein Problem nicht nachvollziehen, da ich mit einem nodemcu arbeite.

Und wie hier angegeben könnte es funktionieren.
Ich habe mein Programm noch einmal überarbeitet. Es kompiliert jetzt einwandfrei. Da ich weder ein Ethernet oder Wifi Shield habe kann ich leider nicht sagen ob es bei Dir läuft.
Daher wäre Feedback nett.
Ich verwende ein nodemcu.

#include <WiFi.h>
#include <ThingSpeak.h>

#define VOLTAGE_MAX 16.0
#define VOLTAGE_MAXCOUNTS 1023.0
int status = WL_IDLE_STATUS;     // the Wifi radio's status

// replace with your channel’s thingspeak API key,
const char * myWriteAPIKey = "ABCDEFGHIJKL";
unsigned long myChannelNumber = 123456;

// Local AP Credentials 
char ssid[] = "yourNetwork";     //  your network SSID (name)
char pass[] = "secretPassword";  // your network password

WiFiClient client;


void setup() {
  Serial.begin(115200);
  delay(10);

  
  
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

  while (status != WL_CONNECTED) {
    delay(500);
     status = WiFi.begin(ssid, pass);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.println("WiFi connected");

 ThingSpeak.begin(client);
  
}


void loop() {
    int sensorValue = analogRead(2);
    float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

 // fill data fields (max 8 fields) and update 
    ThingSpeak.setField(1, voltage);
    ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    delay(20000); // ThingSpeak will only accept updates every 15 seconds.

}

Probier es einfach mal aus.

Und hier mit Ethernet. Wobei die gleichen Einschränkungen gelten wie für der oben genannten Code.

#include <ThingSpeak.h>
#include <Ethernet.h>

// replace with your channel’s thingspeak API key,
const char * myWriteAPIKey = "ABCDEFGHIJKL";
unsigned long myChannelNumber = 123456;

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

#define VOLTAGE_MAX 16.0
#define VOLTAGE_MAXCOUNTS 1023.0


// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;


void setup() {
  Serial.begin(9600);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print("Connecting ....  ");
 
 // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

 ThingSpeak.begin(client);
  
}


void loop() {
    int sensorValue = analogRead(2);
    float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);

 // fill data fields (max 8 fields) and update 
    ThingSpeak.setField(1, voltage);
    ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    delay(20000); // ThingSpeak will only accept updates every 15 seconds.

}

Hallo zusammen,

habe es hinbekommen laut aber nur auf dem Mega sauber

Gruß Markus

#include <ThingSpeak.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   50
#define VOLTAGE_MAX 16.0
#define VOLTAGE_MAXCOUNTS 1023.0

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xff, 0x75, 0x45, 0xED };
IPAddress ip(192, 168, 1, 10); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
File webFile;               // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
EthernetClient client;
   
    #define VOLTAGE_MAX 16
    #define VOLTAGE_MAXCOUNTS 1023.0


unsigned long myChannelNumber = 170185; // Thingspeak
const char * myWriteAPIKey = "FLULHAQJ4A4YOHY0"; // Thingspeak



void setup()
{
    // disable Ethernet chip
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);

    Serial.begin(9600);       // for debugging
    
    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;    // init failed
    }
    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
    
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients
   
    ThingSpeak.begin(client);
}

void loop()
{
    EthernetClient client = server.available();  // try to get client
int sensorValue = analogRead(A2);
 float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);
    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // buffer first part of HTTP request in HTTP_req array (string)
                // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                if (req_index < (REQ_BUF_SZ - 1)) {
                    HTTP_req[req_index] = c;          // save HTTP request character
                    req_index++;
                }
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    // remainder of header follows below, depending on if
                    // web page or XML page is requested
                    // Ajax request - send XML file
                    if (StrContains(HTTP_req, "ajax_inputs")) {
                        // send rest of HTTP header
                        client.println("Content-Type: text/xml");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send XML file containing input states
                        XML_response(client);
                    }
                    else {  // web page request
                        // send rest of HTTP header
                        client.println("Content-Type: text/html");
                        client.println("Connection: keep-alive");
                        client.println();
                        // send web page
                        webFile = SD.open("index.htm");        // open web page file
                        if (webFile) {
                            while(webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    // display received HTTP request on serial port
                    Serial.print(HTTP_req);
                    // reset buffer index and all buffer elements to 0
                    req_index = 0;
                    StrClear(HTTP_req, REQ_BUF_SZ);
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                } 
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
    ThingSpeak.writeField(myChannelNumber, 1, voltage, myWriteAPIKey);

}

// send the XML file containing analog value
void XML_response(EthernetClient cl)
{
    int analog_val;
    
    cl.print("<?xml version = \"1.0\" ?>");
    cl.print("<inputs>");
    // read analog pin A2
    analog_val = analogRead(2);
    cl.print("<analog>");
    cl.print(analog_val);
    cl.print("</analog>");
    cl.print("</inputs>");
}

// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
    for (int i = 0; i < length; i++) {
        str[i] = 0;
    }
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
    char found = 0;
    char index = 0;
    char len;

    len = strlen(str);
    
    if (strlen(sfind) > len) {
        return 0;
    }
    while (index < len) {
        if (str[index] == sfind[found]) {
            found++;
            if (strlen(sfind) == found) {
                return 1;
            }
        }
        else {
            found = 0;
        }
        index++;
    }

    return 0;
    
}