Data to Thingspeak Over Ethernet Port

Dependencies:   mbed HTTPClient mbed-rtos NTPClient EthernetInterface

main.cpp

Committer:
dewantkatare
Date:
2019-04-13
Revision:
5:b8a76bfc45c9
Parent:
4:21c1357bb880

File content as of revision 5:b8a76bfc45c9:

#include "mbed.h"
#include "EthernetInterface.h"
#include "HTTPClient.h"
#include <stdio.h>


char buffer[256];
char resp[1024];
char val[4][16];  
float f_out = 23.0; 
int ret = 0;

//Ethernet Interface
EthernetInterface eth;

//HTTP Client for interfacing to web services
HTTPClient http;

//serial over USB for debug and Info
Serial pc(USBTX, USBRX);

//http client init
HTTPMap map;
HTTPText inText(resp, 1024);


int main(){

    //ethernet init
    eth.init(); //Use DHCP
    ret= eth.connect();

    if (!ret){
            pc.printf("\r\nConnected, IP: %s, MASK: %s, GW: %s",
            eth.getIPAddress(), eth.getNetworkMask(), eth.getGateway());
    } else {
        pc.printf("\r\nError eth.connect() - ret = %d", ret);
    }
    
    while(1){
        pc.printf("\r\nWriting to thingspeak");
        map.put("api_key","EEMB3URN9LDSPRIM");  /* The thingspeak API KEY*/
        sprintf(val[0],"%4.1f",f_out);
        map.put("field1", val[0]);
        map.put("field2", val[0]);
        pc.printf("\r\nPosting Data...");
        ret = http.post("https://api.thingspeak.com/update", map, &inText);     //writing data to Thingspeak
        if (!ret){
            pc.printf("\r\nPOST successfully - read %d characters", strlen(resp));
            pc.printf("\r\nResult: %s\n", resp);
        }else{
            pc.printf("\r\nError Connecting to ethernet port - ret = %d - HTTP return code = %d", ret, http.getHTTPResponseCode());
        }
    }
}