メインコンテンツ

結果:

My dear friend Ram and I have finished our latest movie series. You can watch the final movie , or see the whole series.

In this movie we show how you can use TimeControls and Reacts to control devices or to schedule your MATLAB code that you can write in ThingSpeak. We also discuss a bit about channel sharing.

Mannika Garg
Mannika Garg
最後のアクティビティ: 2021 年 12 月 28 日

Hi,

I am new to Matlab and looking to model complete EPS system starting with battery modelling. I have seen videos where the modelling is explained but looking for a one which can teach me from the scratch.

Kaizer 1419
Kaizer 1419
最後のアクティビティ: 2021 年 12 月 26 日

Is it possible to use the REST API to create ThingHTTP requests?

I am using TX and RX pin of arduino connect to RX and TX pin of NodeMCU. The data does not received, the data upload to thingspeak is zero.

Muhammad Afzal
Muhammad Afzal
最後のアクティビティ: 2021 年 12 月 22 日

Hi Everyone,

Today mistakenly i clear the working channel instead of testing channel which have more then 27000 Environmental Sensor readings so is there any option where i can get back my that data?

Thank you.

Hi!

I'm trying to use a mix of Arduino Nano + SIM800L + RTC DS3231 + 2x PZEM-004T to achieve the goal of upload the two Energy readings every 24h to Thingspeak channel. My sketch is this https://pastebin.com/a6Zn8HaV, i'm in doubt if the use of String class for the GET job is correct.

Could you help me?

Thanks

Desmond Hanan
Desmond Hanan
最後のアクティビティ: 2023 年 7 月 26 日

I was testing some sensors using code that I've run before successfully on an Arduino device to update to thingspeak, but I keep getting the http error code -302.

if true
  % code
#include <SPI.h>
#include <WiFi101.h>
#include <Wire.h>
#include <secrets_new.h>
#include <ThingSpeak.h>
#include <SD.h>
char ssid[] = SECRET_SSID;   // your network SSID (name) 
WiFiClient  client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
int soil_moisture_2cm = 0;
int soil_moisture_5cm = 0;
int soil_temperature_2cm = 0;
int soil_temperature_5cm = 0;
void setup() {
// put your setup code here, to run once:
WiFi.setPins(8,7,4,2);
Wire.begin();
delay(1000);
Serial.begin(9600);
 if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }
String fv = WiFi.firmwareVersion();
if (fv != "1.0.0") {
  Serial.println("Please upgrade the firmware");
}
ThingSpeak.begin(client);
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(SECRET_SSID);
  while(WiFi.status() != WL_CONNECTED){
    WiFi.begin(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
    Serial.print(".");
    delay(5000);     
  } 
  Serial.println("\nConnected.");
      }
soil_moisture_2cm = analogRead(A0);
soil_moisture_5cm = analogRead(A1);
soil_temperature_2cm = analogRead(A2);
soil_temperature_5cm = analogRead(A3);
 ThingSpeak.setField(1, soil_moisture_2cm);
 ThingSpeak.setField(2, soil_moisture_5cm);
   ThingSpeak.setField(3, soil_temperature_2cm);
   ThingSpeak.setField(4, soil_temperature_5cm);
    int y = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  if(y == 200){
    Serial.println("Channel 2 update successful.");
  }
else{
  Serial.println("Problem updating channel 2. HTTP error code " + String(y));
}
delay(30000);
}
end
Safak Agustoslu
Safak Agustoslu
最後のアクティビティ: 2021 年 12 月 14 日

I have android 2.4 and 4.4 mobile device. I tried yesterday night, they are good working. Send data to my chanels and receive data good working. Same program android 6.0 good working yesterday night and tonight. But tonight, android 2.4 and 4.4 mobile device give 1101 error.

BANDEIRA ROGERIO
BANDEIRA ROGERIO
最後のアクティビティ: 2022 年 3 月 13 日

COMO FACO PARA COLOCAR EM TEMPO REAL VIA CODIGO AT + CLBS a localizacao, alguem pode me ajudar ????

Sriram Naren
Sriram Naren
最後のアクティビティ: 2021 年 12 月 13 日

     we are doing a project on health monitoring system. We have made all the required changes in the code but our data is not being uploaded in thingspeak.It would be of great help if you can suggest some way.
    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #include <SoftwareSerial.h>
    float pulse = 0;
    float temp = 0;
    SoftwareSerial ser(9,10);
    String apiKey = "xxxxxxxxxxxxxxxx";
    // Variables
    int pulsePin = A0; // Pulse Sensor purple wire connected to analog pin 0
    int blinkPin = 7 ; // pin to blink led at each beat
    int fadePin = 13; // pin to do fancy classy fading blink at each beat
    int fadeRate = 0; // used to fade LED on with PWM on fadePin
    // Volatile Variables, used in the interrupt service routine!
    volatile int BPM; // int that holds raw Analog in 0. updated every 2mS
    volatile int Signal; // holds the incoming raw data
    volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded!
    volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when nota "live beat".
    volatile boolean QS = false; // becomes true when Arduoino finds a beat.
    // Regards Serial OutPut -- Set This Up to your needs
    static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse
    volatile int rate[10]; // array to hold last ten IBI values
    volatile unsigned long sampleCounter = 0; // used to determine pulse timing
    volatile unsigned long lastBeatTime = 0; // used to find IBI
    volatile int P = 512; // used to find peak in pulse wave, seeded
    volatile int T = 512; // used to find trough in pulse wave, seeded
    volatile int thresh = 525; // used to find instant moment of heart beat, seeded
    volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded
    volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM
    volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM
    void setup()
    {
    lcd.begin(16, 2);
    pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat!
    pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat!
    Serial.begin(115200); // we agree to talk fast!
    interruptSetup(); // sets up to read Pulse Sensor signal every 2mS
    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
    // analogReference(EXTERNAL);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(" Patient Health");
    lcd.setCursor(0,1);
    lcd.print(" Monitoring ");
    delay(4000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Initializing....");
    delay(5000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Getting Data....");
    ser.begin(9600);
    ser.println("AT");
    delay(1000);
    ser.println("AT+GMR");
    delay(1000);
    ser.println("AT+CWMODE=3");
    delay(1000);
    ser.println("AT+RST");
    delay(5000);
    ser.println("AT+CIPMUX=1");
    delay(1000);
    String cmd="AT+CWJAP=\"Harshini Arulkumaran\",\"prythian\"";
    ser.println(cmd);
    delay(1000);
    ser.println("AT+CIFSR");
    delay(1000);
    }
    // Where the Magic Happens
    void loop()
    {
    serialOutput();
    if (QS == true) // A Heartbeat Was Found
    {
    // BPM and IBI have been Determined
    // Quantified Self "QS" true when arduino finds a heartbeat
    fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED with pulse
    serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
    QS = false; // reset the Quantified Self flag for next time
    }
    ledFadeToBeat(); // Makes the LED Fade Effect Happen
    delay(20); // take a break
    read_temp();
    esp_8266();
    }
    void ledFadeToBeat()
    {
    fadeRate -= 15; // set LED fade value
    fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers!
    analogWrite(fadePin,fadeRate); // fade LED
    }
    void interruptSetup()
    {
    // Initializes Timer2 to throw an interrupt every 2mS.
    TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
    TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER
    OCR2A = 0X7C; // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
    TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
    sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
    }
    void serialOutput()
    { // Decide How To Output Serial.
    if (serialVisual == true)
    {
    arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial Monitor Visualizer
    }
    else
    {
    sendDataToSerial('S', Signal); // goes to sendDataToSerial function
    }
    }
    void serialOutputWhenBeatHappens()
    {
    if (serialVisual == true) // Code to Make the Serial Monitor Visualizer Work
    {
    Serial.print("Heart-Beat Detected"); //ASCII Art Madness
    Serial.print("BPM: ");
    Serial.println(BPM);
    }
    else
    {
    sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix
    sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix
    }
    }
    void arduinoSerialMonitorVisual(char symbol, int data )
    {
    const int sensorMin = 0; // sensor minimum, discovered through experiment
    const int sensorMax = 1024; // sensor maximum, discovered through experiment
    int sensorReading = data; // map the sensor range to a range of 12 options:
    int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
    // do something different depending on the
    // range value:
    switch (range)
    {
    case 0:
    Serial.println(""); /////ASCII Art Madness
    break;
    case 1:
    Serial.println("---");
    break;
    case 2:
    Serial.println("------");
    break;
    case 3:
    Serial.println("---------");
    break;
    case 4:
    Serial.println("------------");
    break;
    case 5:
    Serial.println("--------------|-");
    break;
    case 6:
    Serial.println("--------------|---");
    break;
    case 7:
    Serial.println("--------------|-------");
    break;
    case 8:
    Serial.println("--------------|----------");
    break;
    case 9:
    Serial.println("--------------|----------------");
    break;
    case 10:
    Serial.println("--------------|-------------------");
    break;
    case 11:
    Serial.println("--------------|-----------------------");
    break;
    }
    }
    void sendDataToSerial(char symbol, int data )
    {
    Serial.print(symbol);
    Serial.println(data);
    }
    ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124
    {
    cli(); // disable interrupts while we do this
    Signal = analogRead(pulsePin); // read the Pulse Sensor
    sampleCounter += 2; // keep track of the time in mS with this variable
    int N = sampleCounter - lastBeatTime; // monitor the time since the last beat to avoid noise
    // find the peak and trough of the pulse wave
    if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI
    {
    if (Signal < T) // T is the trough
    {
    T = Signal; // keep track of lowest point in pulse wave
    }
    }
    if(Signal > thresh && Signal > P)
    { // thresh condition helps avoid noise
    P = Signal; // P is the peak
    } // keep track of highest point in pulse wave
    // NOW IT'S TIME TO LOOK FOR THE HEART BEAT
    // signal surges up in value every time there is a pulse
    if (N > 250)
    { // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )
    {
    Pulse = true; // set the Pulse flag when we think there is a pulse
    digitalWrite(blinkPin,HIGH); // turn on pin 13 LED
    IBI = sampleCounter - lastBeatTime; // measure time between beats in mS
    lastBeatTime = sampleCounter; // keep track of time for next pulse
    if(secondBeat)
    { // if this is the second beat, if secondBeat == TRUE
    secondBeat = false; // clear secondBeat flag
    for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup
    {
    rate[i] = IBI;
    }
    }
    if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE
    {
    firstBeat = false; // clear firstBeat flag
    secondBeat = true; // set the second beat flag
    sei(); // enable interrupts again
    return; // IBI value is unreliable so discard it
    }
    // keep a running total of the last 10 IBI values
    word runningTotal = 0; // clear the runningTotal variable
    for(int i=0; i<=8; i++)
    { // shift data in the rate array
    rate[i] = rate[i+1]; // and drop the oldest IBI value
    runningTotal += rate[i]; // add up the 9 oldest IBI values
    }
    rate[9] = IBI; // add the latest IBI to the rate array
    runningTotal += rate[9]; // add the latest IBI to runningTotal
    runningTotal /= 10; // average the last 10 IBI values
    BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM!
    QS = true; // set Quantified Self flag
    // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    pulse = BPM;
    }
    }
    if (Signal < thresh && Pulse == true)
    { // when the values are going down, the beat is over
    digitalWrite(blinkPin,LOW); // turn off pin 13 LED
    Pulse = false; // reset the Pulse flag so we can do it again
    amp = P - T; // get amplitude of the pulse wave
    thresh = amp/2 + T; // set thresh at 50% of the amplitude
    P = thresh; // reset these for next time
    T = thresh;
    }
    if (N > 2500)
    { // if 2.5 seconds go by without a beat
    thresh = 512; // set thresh default
    P = 512; // set P default
    T = 512; // set T default
    lastBeatTime = sampleCounter; // bring the lastBeatTime up to date
    firstBeat = true; // set these to avoid noise
    secondBeat = false; // when we get the heartbeat back
    }
    sei(); // enable interrupts when youre done!
    }// end isr
    void esp_8266()
    {
    // TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80
    String cmd = "AT+CIPSTART=4,\"TCP\",\"";
    cmd += "192.168.137.1"; // api.thingspeak.com
    cmd += "\",80";
    ser.println(cmd);
    Serial.println(cmd);
    if(ser.find("Error"))
    {
    Serial.println("AT+CIPSTART error");
    return;
    }
    String getStr = "GET /update?api_key=";
    getStr += apiKey;
    getStr +="&field1=";
    getStr +=String(temp);
    getStr +="&field2=";
    getStr +=String(pulse);
    getStr += "\r\n\r\n";
    // send data length
    cmd = "AT+CIPSEND=4,";
    cmd += String(getStr.length());
    ser.println(cmd);
    Serial.println(cmd);
    delay(1000);
    ser.print(getStr);
    Serial.println(getStr); //thingspeak needs 15 sec delay between updates
    delay(3000);
    }
    void read_temp()
    {
    int temp_val = analogRead(A1);
    float mv = (temp_val/1024.0)*5000;
    float cel = mv/10;
    temp = (cel*9)/5 + 32;
    Serial.print("Temperature:");
    Serial.println(temp);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("BPM :");
    lcd.setCursor(7,0);
    lcd.print(BPM);
    lcd.setCursor(0,1);
    lcd.print("Temp.:");
    lcd.setCursor(7,1);
    lcd.print(temp);
    lcd.setCursor(13,1);
    lcd.print("F");
    }
Dick Chan
Dick Chan
最後のアクティビティ: 2022 年 7 月 23 日

Dear all, I am using the micro:bit with ESP-01s and the CO2 sensor to monitor indoor air quality. Thingspeak cannot show the data eventhough the ESP is connected to the wifi (checked with the router). Failed to talk to my ESP even I have setup a new channel many times. Can anyone advise me what to do?

Thank you for your help in advance.

bernard podant
bernard podant
最後のアクティビティ: 2021 年 12 月 4 日

hello, when I add a visualization, it is written "Field value unavailable" can somebody assist ?

many thanks

Giulio Griguoli
Giulio Griguoli
最後のアクティビティ: 2021 年 11 月 25 日

Hi, I'm trying to send with a serial connection a signal. The signal is just a byte (uint8) that I want to send to my evaluation board every 1 millisecond using Simulink. How can I do that? I tried using the Serial Send block, but the result is different from what I expected to see. Then I tried to use the To instrument block, but I don't know why there isn't the port COM 5 so I couldn't use it.

Hi, currently I'm studying about DC-DC Boost converter with controller. After I applied the step time, the output voltage supposed to follow the step time, but there is some delay in the simulation results after I applied the "step time" in the step input block. Can someone help, why this delay occur? Please see the attached pictures. Thanks

Christopher Stapels
Christopher Stapels
最後のアクティビティ: 2021 年 11 月 23 日

The third movie in our new series is live. We focus on MATLAB Analysis and Visualizations in this video. You can see how to set up code to preprocess your data and how to add custom visualizations.

Dr Narayanaswamy P R Iyer
Dr Narayanaswamy P R Iyer
最後のアクティビティ: 2021 年 11 月 23 日

As per data sheet for VIPER22A, the product is obsolete.

Dr Narayanaswamy P R Iyer
Dr Narayanaswamy P R Iyer
最後のアクティビティ: 2021 年 11 月 23 日

For UC3843A you will have to refer to the data sheet, link given below: https://www.ti.com/lit/ds/symlink/uc3843a.pdf?ts=1637624394197&ref_url=https%253A%252F%252Fwww.ti.com%252Fproduct%252FUC3843A

For UC3843A, the reference output voltage is 5 V and the normal output voltage is 13.5 V.

Michal Gebolys
Michal Gebolys
最後のアクティビティ: 2021 年 11 月 23 日

So far I haven't found an option to change the channel's name, neither on website nor in the API. Is it possible to change the channel name?

Rose Li
Rose Li
最後のアクティビティ: 2021 年 11 月 20 日

After repairing the power supply of a big water buffalo PC150NCA, now all the parts found to be broken are replaced, but the power-on output 12V is only 4.2V. The original power supply block is UC3843B, which is not sold locally. I can only buy a UC3843A replacement . I don’t know if the low output voltage has anything to do with this (the optocoupler and the 431 voltage regulator block have also been replaced)

Hi, I am currently working on IOT control using ZYBO-Z7 FPGA with the Pmod ESP32, my goal is to read multiple data across 8 fields simultaneously, my current method is reading data from individual fields manually using the code given from this user from a digilent forum (https://forum.digilentinc.com/topic/21634-retrieve-data-from-thingspeak-through-using-pmod-esp32/), this method makes the control slow as I have to individually wait for 8 fields of data one by one. My current solution I am testing out is to read json data using the C++ code below, however the json file is a placed in constant and can only read from that specific array and does not update real time data from thingspeak, how do I get my ZYBO-Z7 to process multiple data from a single feed with 8 fields all from one json URL? Much needed help please and thanks.

/*
 * This workspace attempts to parse (deserialize) a serialize json data
 * from thingspeak (see project_4_1). The code below was extracted (with some editing) from
 * arduinojson.org/v5/assistant after I input the serialize json data
 * from project_4_1: {"channel":{"id":1410948,"name":"testing","latitude":"0.0","longitude":"0.0","field1":"temp","field2":"ph","created_at":"2021-06-08T07:08:42Z","updated_at":"2021-06-09T04:58:00Z","last_entry_id":3},"feeds":[{"created_at":"2021-06-08T08:05:31Z","entry_id":1,"field1":"63"},{"created_at":"2021-06-08T08:07:35Z","entry_id":2,"field1":"76"},{"created_at":"2021-06-08T08:14:50Z","entry_id":3,"field1":"56"}]}
 * The extracted code from arduinojson assistant was tested in
 * https://wandbox.org/permlink/T07A43gUP3EuZjaF
*/
#include <iostream> //if complained of "unresolved inclusion", just build project
#include <ArduinoJson-v5.13.5.h>
#include "xparameters.h"
#include "xil_printf.h"
#include "sleep.h"
#include "stdio.h"
#include "xtime_l.h"
#include "stdlib.h"  //added
#include "string.h"
#include "xgpiops.h"
extern"C"{
#include "PmodESP32.h"
}
#ifdef __MICROBLAZE__
#define HOST_UART_DEVICE_ID XPAR_AXI_UARTLITE_0_BASEADDR
#define HostUart XUartLite
#define HostUart_Config XUartLite_Config
#define HostUart_CfgInitialize XUartLite_CfgInitialize
#define HostUart_LookupConfig XUartLite_LookupConfig
#define HostUart_Recv XUartLite_Recv
#define HostUartConfig_GetBaseAddr(CfgPtr) (CfgPtr->RegBaseAddr)
#include "xuartlite.h"
#include "xil_cache.h"
#else
#define HOST_UART_DEVICE_ID XPAR_PS7_UART_1_DEVICE_ID
#define HostUart XUartPs
#define HostUart_Config XUartPs_Config
#define HostUart_CfgInitialize XUartPs_CfgInitialize
#define HostUart_LookupConfig XUartPs_LookupConfig
#define HostUart_Recv XUartPs_Recv
#define HostUartConfig_GetBaseAddr(CfgPtr) (CfgPtr->BaseAddress)
#include "xuartps.h"
#endif
#define PMODESP32_UART_BASEADDR XPAR_PMODESP32_0_AXI_LITE_UART_BASEADDR
#define PMODESP32_GPIO_BASEADDR XPAR_PMODESP32_0_AXI_LITE_GPIO_BASEADDR
#define BLOCK_SIZE 40
void EnableCaches();
void DisableCaches();
void DemoInitialize();
void DemoRun();
void DemoCleanup();
void receiveData(XTime time);
void setWifiMode(void);
void connectWifi(void);
void establishConnection(void);
void cipsend(void);
PmodESP32 ESP32;
HostUart myHostUart;
XTime TimeStart;
XTime TimeEnd;
int countdown =60;
char *ptr;
XGpioPs_Config *ConfigPtr;
static XGpioPs Gpio;
u8 light;
u8 light1; //ALS
u16 eCO2;
u16 TVOC;
u8 buf[5]; //AQS
u8 recv_buffer;
u32 num_received;
const float ReferenceVoltage = 3.3;
int sec = 0;
int min = 0;
int hour = 0;
int x = 0;
int j = 0;
int status;
int fakecount1 = 0;
int fakecount2 = 0;
int floatmotor = 0;
int floatpumpspoil = 0;
int motorreal = 0;
int DosingDone = 0;
int led1status = 0;
int led234status = 0;
int pumpstatus = 0;
int motorstatus = 0;
int pumpbroken = 0;
int checkingEC = 0;
float ECvalue = 0;
float PHvalue = 0;
void DemoInitialize () {
	HostUart_Config *CfgPtr;
	EnableCaches();
	ESP32_Initialize(&ESP32, PMODESP32_UART_BASEADDR, PMODESP32_GPIO_BASEADDR);
	CfgPtr = HostUart_LookupConfig(HOST_UART_DEVICE_ID);
	HostUart_CfgInitialize(&myHostUart, CfgPtr, HostUartConfig_GetBaseAddr(CfgPtr));
	   ConfigPtr = XGpioPs_LookupConfig(XPAR_PS7_GPIO_0_DEVICE_ID);
	   XGpioPs_CfgInitialize(&Gpio, ConfigPtr, ConfigPtr->BaseAddr);
	   XGpioPs_SetDirectionPin(&Gpio, 13, 1);
	   XGpioPs_SetOutputEnablePin(&Gpio, 13,1); //pin1 JF1 layer 1 LED #
	   XGpioPs_SetDirectionPin(&Gpio, 10, 1);
	   XGpioPs_SetOutputEnablePin(&Gpio, 10,1); //pin2 JF2 layer 2, 3, 4 LED #
}
void DemoRun() {
	setWifiMode();
	connectWifi();
	establishConnection();
	cipsend();
}
void DemoCleanup() {
	DisableCaches();
}
int main() {
	DemoInitialize();
	DemoRun();
	      free(ptr);
	      const size_t capacity = JSON_OBJECT_SIZE(10) + 140;
	      DynamicJsonBuffer jsonBuffer(capacity);
	      //const char* json = "{\"created_at\":\"2021-11-19T05:33:15Z\",\"entry_id\":134,\"field1\":\"0\",\"field2\":\"1\",\"field3\":\"1\",\"field4\":\"1\",\"field5\":\"2\",\"field6\":\"2\",\"field7\":\"2\",\"field8\":\"10\"}";
	      JsonObject& root = jsonBuffer.parseObject(json);
	      const char* created_at = root["created_at"]; // "2021-11-19T05:33:15Z"
	      int entry_id = root["entry_id"]; // 134
	      const char* field1 = root["field1"]; // "0"
	      const char* field2 = root["field2"]; // "1"
	      const char* field3 = root["field3"]; // "1"
	      const char* field4 = root["field4"]; // "1"
	      const char* field5 = root["field5"]; // "2"
	      const char* field6 = root["field6"]; // "2"
	      const char* field7 = root["field7"]; // "2"
	      const char* field8 = root["field8"]; // "10"
	      if(root["field1"] == "1")
	      {
	    	  xil_printf("1");
	      }
	      else if(root["field1"] == "0")
	      {
	    	  xil_printf("0");
	      }
	      else
	      {
	    	  xil_printf("error reading");
	      }
	      if(root["field2"] == "1")
	      {
	    	  xil_printf("1");
	      }
	      else if(root["field2"] == "0")
	      {
	    	  xil_printf("0");
	      }
	      else
	      {
	    	  xil_printf("error reading");
	      }
	      if(root["field3"] == "1")
	      {
	    	  xil_printf("1");
	      }
	      else if(root["field3"] == "0")
	      {
	    	  xil_printf("0");
	      }
	      else
	      {
	    	  xil_printf("error reading");
	      }
	      if(root["field4"] == "1")
	      {
	    	  xil_printf("1");
	      }
	      else if(root["field4"] == "0")
	      {
	    	  xil_printf("0");
	      }
	      else
	      {
	    	  xil_printf("error reading");
	      }
	      if(root["field5"] == "1")
	      {
	    	  xil_printf("1");
	      }
	      else if(root["field5"] == "0")
	      {
	    	  xil_printf("0");
	      }
	      else
	      {
	    	  xil_printf("error reading");
	      }
	DemoCleanup();
	return 0;
}
void setWifiMode(void){
    u8 tx[]="AT+CWMODE=3\r\n";
    u32 num = strlen((char *) tx);
    xil_printf((char *) tx);
    ESP32_SendBuffer(&ESP32, tx, num);
    usleep(100000);
    receiveData(1);
}
void connectWifi(void){
    u8 tx[] = "AT+CWJAP=\"eee-iot\",\"gr3enChess30\"\r\n";
    u32 num = strlen((char *) tx);
    xil_printf((char *) tx);
    ESP32_SendBuffer(&ESP32, tx, num);
    usleep(100000);
    receiveData(9);
}
void receiveData(XTime time){
    XTime tEnd, tCur;
    u8 recv_buffer=0;
    u32 num_received=0;
      XTime_GetTime(&tCur);
      tEnd  = tCur + (time * COUNTS_PER_SECOND);
      do
      {
          num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
                  if(num_received >0){
                      num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
                      xil_printf("%c", recv_buffer);
                  }
          if(tCur == tCur + COUNTS_PER_SECOND){
              countdown = countdown -1;
          }
          else
              XTime_GetTime(&tCur);
      } while (tCur < tEnd);
}
void receiveData2(XTime time){
    XTime tEnd, tCur;
    u8 recv_buffer=0;
    u32 num_received=0;
      int i=0;
      int max_index = BLOCK_SIZE-1;
      ptr = (char*) malloc(sizeof(int)*BLOCK_SIZE);  //compare with project_4_3 or _4_1 where (int*) is not required because it is a C file in those projects
      if(ptr==NULL)
      {
          perror("some error");
          //return 1;
      }
      XTime_GetTime(&tCur);
      tEnd  = tCur + (time * COUNTS_PER_SECOND);
      do
      {
          num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
                  if(num_received >0){
                      num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
                          if(i > max_index)
                          {
                              ptr=(char*) realloc(ptr, (max_index+1 + BLOCK_SIZE)*sizeof(int));  //compare with project_4_3 or _4_1 where (int*) in realloc is not required because it is a C file in those projects
                              if(ptr == NULL)
                              {
                                  perror("insufficient memory!");
                                  break;
                              }
                              //printf("\nReallocated!");
                              max_index += BLOCK_SIZE;
                          }
                          ptr[i]=recv_buffer;
                          i++;
                      //}
                  }
          if(tCur == tCur + COUNTS_PER_SECOND){
             countdown = countdown -1;
          }
          else
              XTime_GetTime(&tCur);
      } while (tCur < tEnd);
}
void establishConnection(void){
    u8 tx[] = "AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80\r\n";
    u32 num = strlen((char *) tx);
    ESP32_SendBuffer(&ESP32, tx, num);
    receiveData(1);
}
void cipsend(void){
    u8 command[150];
    u8 finalcmd[50];
      sprintf((char*)command, "GET https://api.thingspeak.com/channels/1572052/feeds/last.json/?api_key=xxxxxxxxxxxxxxxx\r\n");
      u32 length = strlen((char*)command);
      sprintf((char*)finalcmd, "AT+CIPSEND=%d\r\n", (int)length);
      u32 cmdlength =strlen((char*)finalcmd);
      xil_printf("Length %d\r\n", length);
      xil_printf((char *)finalcmd);
      ESP32_SendBuffer(&ESP32, finalcmd, cmdlength);
      usleep(100000);
      xil_printf((char *)command);
      ESP32_SendBuffer(&ESP32, command, length);
      receiveData2(1);
}
void EnableCaches() {
#ifdef __MICROBLAZE__
#ifdef XPAR_MICROBLAZE_USE_ICACHE
   Xil_ICacheEnable();
#endif
#ifdef XPAR_MICROBLAZE_USE_DCACHE
   Xil_DCacheEnable();
#endif
#endif
}
void DisableCaches() {
#ifdef __MICROBLAZE__
#ifdef XPAR_MICROBLAZE_USE_ICACHE
   Xil_ICacheDisable();
#endif
#ifdef XPAR_MICROBLAZE_USE_DCACHE
   Xil_DCacheDisable();
#endif
#endif
}