ThingSpeak

ThingSpeak

Public Channel

Edward in Discussions
Last activity on 28 Dec 2023

I am sending data to Thingspeak chanels from an ESP8266. I am saving data on the ESP memory which is collected at 5 minute intervals . I have created a trigger function which sends the data on demand in batches from the memory, which means there could be varying number of Data points from say 10 to 50.However I have notice recently whils my code tells me the dayta points have been transmitted not all get recorded in thingspeak, are there restrictions which cause this problem and if so what is the solution please? Batch Data You cannot write two entries with the same timestamp to the channel, and there are limitations on the number of points in each update and for the frequency of bulk posts. See the Bulk JSON write page for more information. If you are still stuck, have a look at the examples like this one for ESP8266. Please let us know how it goes. batch data
Ilias Lamprou in Discussions
Last activity on 28 Dec 2023

Hi, while I can download data from the thingspeak page as csv older than 5 months, I can't read history data older than one month. The data exists on the database. This are my requests: https://api.thingspeak.com/channels/667773/fields/1.json?start=2023-11-23T01:01:10.000Z https://api.thingspeak.com/channels/667773/fields/1.json?start=2023-10-23T01:01:10.000Z The same results. Every day the older value date is higher by one day. Today the older value day is: 2023-11-25T02:13:46Z Why? Is there a limit to history data loading? I cannot read history data older than one month I think you need the end parameter ad well. Without it, thingspeak might read backwards to try to get to ‘start” but stop when it gets to 8k records. Anyway, im sure you need both start and end parameters to get date based reads to work. Hi, I have already tested. The same results. This is a request: https://api.thingspeak.com/channels/667773/fields/1.json?start=2023-09-30T21:00:00.000Z&end=2024-03-14T22:00:00.000Z Today the latest day I can get data is: 2023-11-25T19:17:27Z Some hours later than last night. The channel is public, everyone can test the results. I believe there is some limit from the server There is definitely a limit of 8000 records. If you want more data than that, you will need to do multiple reads. Make sure you delay between reads at least a little so you dont slam the server. Have a look at the tip in the blue box: Read Data history limit history data
guy caluwaerts in Discussions
Last activity on 21 Dec 2023

I want to control the level my water tank with a esp8266 and Thingspeak. I can see the level in Thingspeak. This is working. Now I want to send 2 emails : One daily email with the actual level Alarm email when level is below a setpoint. How can I incorporate the value from a channel in the email ? What I have now for the daily email , but with errors : alert_body = 'huidig peil regenput'; channelID = ..........; % Provide the ThingSpeak alerts API key. All alerts API keys start with TAK. alertApiKey = 'TAK...............'; % Set the address for the HTTTP call alertUrl="https://api.thingspeak.com/alerts/send"; % webwrite uses weboptions to add required headers. Alerts needs a ThingSpeak-Alerts-API-Key header. options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey ]); % Set the email subject. alertSubject = sprintf("Niveau regenput " ); % Read the recent data. peil = thingSpeakRead(channelID,'Fields',1); % Check to make sure the data was read correctly from the channel. % Set the outgoing message webwrite(alertUrl , "body", alertBody, "subject", alertSubject,'Fields',peil); % Catch errors so the MATLAB code does not disable a TimeControl if it fails try webwrite(alertUrl , "body", alert_body, "subject", alertSubject, options); catch someException fprintf("Failed to send alert: %s\n", someException.message); end The errors I receive : Unrecognized function or variable 'alert_Body'. Error in Read Channel to Trigger Email 1 (line 24) webwrite(alertUrl , "body", alert_Body, "subject", alertSubject,"Fields",peil); Manny thanks in advance Send email with the value of a channel MATLAB is case sensitive. alert_body is not equal to alert_Body Be careful with daily emails, you are limited to 800 yearly alert emails. (but there are enough for one per day or more) Your code example shows how to put a channel value in the email. peil = thingSpeakRead(channelID,'Fields',1); % Check to make sure the data was read correctly from the channel. % Set the outgoing message webwrite(alertUrl , "body", alertBody, "subject", alertSubject,'Fields',peil); This will make the subject equal to the value from field 1 Hi Christopher, I did the notification and don't receive no errors anymore. Unfortunately I also don't receive the emails in my mailbox. % webwrite uses weboptions to add required headers. Alerts needs a ThingSpeak-Alerts-API-Key header. options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey ]); % Set the email subject. alertSubject = sprintf("Niveau regenput " ); % Read the recent data. peil = thingSpeakRead(channelID,'Fields',1); % Set the outgoing message try webwrite(alertUrl , "body", alertBody, "subject", alertSubject,'Fields',peil); end Check your junk folder and make sure you arent blocking thingspeak.com at your email server. You can also take the try ..end.. syntax off, and remove the semicolon on the webwrite line to test and make sure the command was sent. What do you mean with junk folder ? When I do save and run I receive 2 messages. MATLAB code ran successfully. Failed to send alert: The server returned the status 401 with message "" in response to the request to URL https://api.thingspeak.com/alerts/send. 401 means unauthorized. Check your alerts api key. By junk folder i menat for email, but its clear its not sending. I copy past het API key again but no result. does the api key begin with TAK? yes. I use the alertapikey alertApiKey = 'TAKMAxjn5Ad1TrzrNWH'; I also renewed already the key, but no result. You are forgetting the options when you webwrite. Thats why its 401 unauthorized. No key included with the requiest. webwrite(alertUrl , "body", alertBody, "subject", alertSubject, options); webwrite(alertUrl , "body", alertBody, "subject", alertSubject, peil, options); doesn't work webwrite(alertUrl , "body", alertBody, "subject", alertSubject, options); Was sending an email once, but without the value of channel 1 Afterwards I received the message when I run the app : "Failed to send alert: Each postName must be given a corresponding postValue." where can I find the documentation about sending information by email ? All the examples I can find only describe the software for the arduino or esp8266/32 https://www.mathworks.com/help/thingspeak/alerts-api.html and https://www.mathworks.com/help/thingspeak/sendalert.html I reccomend you start with the example code and try to modify it one part at a a time. This example is independant of the devece. I would start here. https://www.mathworks.com/help/thingspeak/analyze-channel-data-to-send-email.html My soil moisture cannel doesnt have good data anymore, but you can tie it to the traffic 38629 or weather 12397 channels at ThingSpeak for testing. In the example, you can add the moisture data to the alert body variable to bet information sent to you. I started from these exemples and could send emails but after I tried to include to value of channel 1, I don't receive emails anymore and receive error messages when I run the timecontrol app without to make any changes. I still struggle with my originale question how to include the value of a channel in the body of the email. Christopher, I followed this example. You only send an email with text. I want to send text + the last value from channel 1. What is working for the moment: 1. sending text with : alertBody = 'huidig peil regenput :'; 2. Sending value of channel 1 : alertBody = thingSpeakRead(channelID,'Field',1); What is not working is the combination of both. It must be something like this, but this syntax is not accepted : alertBody = ('huidig peil regenput :' ,thingSpeakRead(channelID,'Field',1)); try seperating the actions. bob = thingSpeakRead(channelID,'Field',1)); % assumes data is numeric, otherwise use 'outputformat','timetable' alertBody = "The value of my field is " + bob; email timecontrol
Alex de Bonth in MATLAB Answers
Last activity on 20 Dec 2023

In the Particle Photon webhook i am getting the message "cacheablelLookup ENOTFOUND api.thingspeaks.com Why do I get this message and why doesnt the data show up in Thingspeaks?
Joseph Varani in Discussions
Last activity on 20 Dec 2023

Hello, I have followed the tutorial from https://www.halvorsen.blog/documents/technology/iot/arduino/resources/Arduino%20UNO%20R4%20WiFi%20and%20ThingSpeak.pdf to use an arduino Uno R4 wifi board to write sensor data to thingspeak, and the field 1 of random data is updating properly, but when I try to send data from analog pin A0 it will not update to field 2. I've been speaking with ChatGPT to try to resolve this issue, and it has offered several solutions that have simplified the code dramatically but the same problem persists. I wonder if this could be an error with the channel settings in my thingspeak channel? I cannot find any errors myself. ChatGPT suggested looking for the http responses to trouble shoot and both fields return -210, which it says means the API key is missing, but I have stored this key in the seperate arduino_secrets.h tab in the code, so both fields must be using the same API key, and since field 1 is working properly I don't think this is the issue. This is why I suspect there might be a deeper issue with my channel. I set it up about a year ago with a different experimental project, so maybe it has been corrupted over time. Any help is much appreciated! My current loop code reads as follows: void loop() { // Update field 1 float temperature = random(2000, 3000) / 100.0; Serial.println(temperature); ThingSpeak.setField(1, temperature); ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); int response = ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); Serial.print("ThingSpeak write response code: "); Serial.println(response); delay(1000); // Add a delay to separate updates // Update field 2 float button = analogRead(A0); int buttonInt = static_cast<int>(button); Serial.println(buttonInt); ThingSpeak.setField(2, buttonInt); ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); int response2 = ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); Serial.print("ThingSpeak write response code: "); Serial.println(response2); delay(19000); // Adjust the delay to maintain the total delay period } Field 2 not updating You are allowing no time between subsequent writes to the two fields (in the same channel), when 15 seconds are required if you have a free account. See this post for the full explanation and solution. Thank you for your quick response! I have updated my code to send both fields in a single writeFields as your other post showed, but I still had the same issue. Field 1 updated just fine but nothing was happening with field 2. However, I had also been thinking that maybe there was an issue with the settings for field 2 in thingspeak, so as an experiment I added a 3rd field of another random number, and this time field 3 updated, and all of the data from field 2 this morning also showed up! So this seems to be fixed, thank you again! The only strange thing that I am now noticing is that field 2 still does not update as consistently as fields 1 or 3. I think this is because the range for field 2 is between 0 and 1023, whereas fields 1 and 3 are all between 20 and 30, so could it be that this is just easier to graph for thingspeak? Occasionally field 2 will give me error code 504, saying something about timeout, I believe. This hasnt happened since this morning, but I still need to update the page to see the newest data rather than it being displayed in real time. My new loop looks like below: void loop() { // Update field 1 float temperature = random(2000, 3000) / 100.0; Serial.println(temperature); // Update field 2 float button = analogRead(A0); int buttonInt = static_cast<int>(button); Serial.println(buttonInt); float humidity = random(2000, 3000) / 100.0; Serial.println(humidity); ThingSpeak.setField(1, temperature); ThingSpeak.setField(2, buttonInt); ThingSpeak.setField(3, humidity); ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); int response = ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); Serial.print("ThingSpeak write response code: "); Serial.println(response); delay(20000); // Add a delay to separate updates] } Code looks much better, except you are still writing twice with no delay in between. Both of these lines will cause a write, but the second will faile every time becasue its too fast. ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); int response = ThingSpeak.writeFields(SECRET_CH_ID, SECRET_WRITE_APIKEY); . Fields take up to 255 characters of string data per feed so I dont think your theory about the size of the data is correct, unless it is causing some kind of error on the device side. To be sure, I would write your program with just an update to field 2 and try that for a while to understand where it is failing.
Jitse Schaafsma in Discussions
Last activity on 18 Dec 2023

Hi there, I hope someone can help me on this. I have written a code to connect my SIM7600 to Thingspeak using MQTT. It is basically an aruidino code. All instructions are echo's with an OK message so assume those instrictions are correct. However, the final step, publishing the message to the MQTT server return an error : CMQTTCONNLOST : 0,1. Any idea which instructions might be wron? I included the commands send. 10:09:09.031 -> AT+CMQTTPUB=0,0,60,0,0 10:09:09.031 -> +CMQTTPUB: 0,0 10:09:09.031 -> 10:09:09.031 -> OK 10:09:09.031 -> 10:09:09.031 -> +CMQTTCONNLOST: 0,1 The program : SerialAT.begin(115200, SERIAL_8N1, RXD2, TXD2); delay(1000); SerialAT.println("AT+CRESET"); // Reset the SIM7600 module Read_Response(30000); SerialAT.println("AT+IPR=115200"); // Set Baudrate of the SIM7600 module Read_Response(30000); SerialAT.println("AT+CSQ"); // Check signal level Read_Response(10000); SerialAT.println("AT+COPS?"); // Query network information Read_Response(10000); SerialAT.println("AT+CMQTTSTOP"); //Stop MQTT service Read_Response(10000); SerialAT.println("AT+CMQTTSTART"); //Start MQTT service Read_Response(10000); SerialAT.println("AT+CSSLCFG=\"sslversion\",0,3"); //Configure SSL contect ssl_ctxindex,sslversion <0,TLS1.2> Read_Response(10000); SerialAT.println("AT+CSSLCFG=\"authmode\",0,0"); //Establishing MQTT Connection <ssl_ctx_index,authmode<0,no autentification> Read_Response(10000); SerialAT.println("AT+CMQTTACCQ=0,\"Username\",0,4"); // Acquire a client <client_index,client_ID> Read_Response(10000); SerialAT.println("AT+CMQTTSSLCFG=0,0"); // Set the SSL context <session_id,ssl_ctx_index> ssl_ctx_index check AT+CSSLCFG command Read_Response(10000); SerialAT.println("AT+CMQTTCONNECT=0,\"tcp://mqtt3.thingspeak.com:1883\",90,1,\"Username\",\"password\""); //Connect to MQTT server <client_index,server_addr,keep_alive time,clean_session,username,password> Read_Response_Ignore_OK(3000); String payload="\"channels/"+ String(ChannelId)+"/publish\""; int Payload_Length; Payload_Length=payload.length(); SerialAT.println("AT+CMQTTTOPIC=0,"+String(Payload_Length)); // Input the publish message topic <client_index,req_length> SerialAT.println(payload); Read_Response_Ignore_OK(3000); payload="field1=12&field2=13&status=MQTTPUBLISH"; Payload_Length=payload.length(); SerialAT.println("AT+CMQTTPAYLOAD=0,"+String(Payload_Length)); // input the publish message body <client_index,req_length> SerialAT.println(payload); Read_Response_Ignore_OK(1000); SerialAT.println("AT+CMQTTPUB=0,0,60,0,0"); // Publish a message to the server <client_id,qos,pub_timeout,retained> Read_Response_Ignore_OK(1000); Serial.print(Receive_buffer); Serial.println("And we are done"); SIM7600, MQTT, Thingspeak, all well until Publish the message There is a good MQTT troubleshoot page with a bunch of things to try. Ill assume you already have a device set up in ThingSpeak and that you have enabled publishing to that channel. Your code above has some strange slashes for the topic i'd have alook at this line. String payload="\"channels/"+ String(ChannelId)+"/publish\""; Also you dont show us what is in the variable MQTTPUBLISH. You also dont show us the Read_Response() function, but issume it involves some wait time since there is a large number in the argument. If possible, I suggest writing the functions to complete when there is no more data instead of with a fixed timeout if possible. My suggestion is to start with the desktop client to make sure you can get all the connection and publish syntax correct before moving to the device. Thank you for your response. To be honest, i have tried so many variations of the payload to be submitted as part of the instruction : AT+CMQTTTOPIC. The one in my post is just one of many variations. Also, i see other posts including the status=MQTTPUBLISH in the message body. Again, i have also tried it without this included. The Read_Response() function makes sure that i read all echo's send from the SIM7600 so that i know if something is going wrong. And yes, i have read many posts, troubleshooting, and it is the overload of information that makes me unsure about the syntax requirements. So my specific question is : What is the correct syntax for the topic (i assume something in the range of channels/12345/publish in which 12345 is the ClientId as stated in the MQTT information pane when constructing the MQTT app What is the correct syntax of the message body ( I assume something like field1=1234&field2=6788). Oh btw, I am pretty sure I have an mqtt connection because AT+CMQTTCONNECT echo's an OK statement. But then again, if that instruction is not correct please let me know. Og btw 2, I have also an mQTT thingspeak on a Any specific feedback is welkom because using a SIM7080, works fine. But the same syntax does not appear to work for the SIM7800. Any concrete feedback is welcome, Regards To continue, For another channel i created a complete new MQTT. I have made sure that channel and fields can be written. I also secured my client_ID and password. My SIM7600 has a connection because: 20:34:11.926 -> AT+CMQTTCONNECT=0,"tcp://mqtt3.thingspeak.com:1883",90,1,"******","****" returns OK +CMQTTCONNECT: 0,0 meaning that the connection is established. Then I upload channels/788628/publish as topic to the SIM7600 module I receive an OK echo. Then I upload field1=1234 as a message to the SIM7600 module I receive an OK echo To finally upload all to the MQTT server I need to use this command: AT+CMQTTPUB=0,0,60,0,0\r\n I do receive then this echo: +CMQTTPUB: 0,0 but also +CMQTTCONNLOST: 0,1 which means connection lost. Documentation says : When client disconnect passively, URC “+CMQTTCONNLOST” will be reported, then user need to connect MQTT server again. So it appears releated to the SIM7600 module. But i do not understand why it "passively disconnects". For completeness, these are my general settings: const String URL="tcp://mqtt3.thingspeak.com"; const String port="1883"; //"1883" in case of no encryption , 8883 in case of TLS/SSL encryption; const String client_index="0"; const String Keep_alive_time="90"; const String Clean_session="1"; const String server_type="0"; //0 - MQTT server with TCP 1 - MQTT server with SSL/TLS const String Mqtt_version="4"; //3 - MQTT version 3.1 4 - MQTT version 3.1.1 const String ssl_ctx_index="0"; // The SSL context ID. The range is 0-9 const String authmode="0"; // 0 no authentification, 1 server authentication. It needs the root CA of the server. , 2 server and client authentication. It needs the root CA of the server, // the cert and key of the client, 3 client authentication and no server authentication. It needs the cert and key of the client const String session_id="0"; // A numeric parameter that identifies a client. The range of permitted values is 0 to 1 const String sslversion="3"; //0 – SSL3.0 1 – TLS1.0 2 – TLS1.1 3 – TLS1.2 4 – All The correct syntax for MQTT Publish is here https://www.mathworks.com/help/thingspeak/publishtoachannelfeed.html For those interested, This is the basic code that finally works for me: Error_Code=0; while (1) { Serial2.print("AT+CLTS=1\r\n"); // Get local timestamp Read_Response_WaitFor("OK",SIMWaitTime); //Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+CCLK?\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); //Serial.println(Receive_buffer); delay(Delay_between_commands); if (Process_DateandTime(false)) {Error_Code=4;} Serial2.print("AT+CSSLCFG=\"SSLVERSION\",0,3\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+CNACT=0,1\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+CNACT?\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); if (!GET_IP_Address ()) { Serial.println("No IP address"); Serial.println("Program stalled"); Error_Code=2; break; } Serial2.print("AT+SMCONF=\"URL\",\"mqtt3.thingspeak.com\",\"1883\"\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+SMCONF=\"KEEPTIME\",60\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+SMCONF=\"CLEANSS\",1\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+SMCONF=\"QOS\",0\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+SMCONF=\"RETAIN\",0\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+SMCONF=\"SUBHEX\",0\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial.println("AT+SMCONF=\"CLIENTID\",\""+String(SPIFFS_Data.ClientId)+"\"\r\n"); Serial2.print("AT+SMCONF=\"CLIENTID\",\""+String(SPIFFS_Data.ClientId)+"\"\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial.println("AT+SMCONF=\"USERNAME\",\""+String(SPIFFS_Data.Username)+"\"\r\n"); Serial2.print("AT+SMCONF=\"USERNAME\",\""+String(SPIFFS_Data.Username)+"\"\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial.println("AT+SMCONF=\"PASSWORD\",\""+ String(SPIFFS_Data.Password)+ "\"\r\n"); Serial2.print("AT+SMCONF=\"PASSWORD\",\""+ String(SPIFFS_Data.Password)+ "\"\r\n"); Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); Serial2.print("AT+SMCONN\r\n"); // Check MQTT connection Read_Response_WaitFor("OK",SIMWaitTime); Serial.println(Receive_buffer); delay(Delay_between_commands); if(strstr(Receive_buffer,"ERROR") != NULL) { Serial.println("SMCONN ERROR " ); Error_Code=3; break; } else { Serial.println("We have a MQTT connection"); String F1="field"+String(SPIFFS_Data.FieldNr)+"="; String F2="&field"+String(SPIFFS_Data.FieldNr+1)+"="; String F3="&field"+String(SPIFFS_Data.FieldNr+2)+"="; String F4="&field"+String(SPIFFS_Data.FieldNr+3)+"="; String payload; payload=F1+String(int(pressure))+F2+String(int(tmp))+F3+String(int(hum))+F4+String(int(BatVoltage*100))+"&"+Date_payload; String Mqtt_Message; int Payload_Length; Payload_Length=payload.length(); Serial.print(payload); Serial.print (" "); Serial.println(Payload_Length); //Mqtt_Message="AT+SMPUB=\"channels/"+ ChannelId+"/publish/fields/field1\","+String(Payload_Length)+",1,1\r\n"; //https://nl.mathworks.com/help/thingspeak/publishtoachannelfieldfeed.html Mqtt_Message="AT+SMPUB=\"channels/"+ String(SPIFFS_Data.ChannelId)+"/publish\","+String(Payload_Length)+",1,1\r\n"; //https://nl.mathworks.com/help/thingspeak/publishtoachannelfeed.html Serial.println(Mqtt_Message); Serial2.print(Mqtt_Message);//Serial2.print("AT+SMPUB=\"channels/888617/publish/fields/field1\",1,1,1\r\n"); // lengte moet goed zijn delay(Delay_between_commands); Serial2.print(payload); Read_Response_WaitFor("OK",20000); //SIMWaitTime); Serial.println(Receive_buffer); break; } } //end while Serial.print("Done with error code : "); Serial.println(Error_Code); if (Error_Code==0) { Serial.print("Going to sleep for "); Serial.print(SPIFFS_Data.Sleep_Period); Serial.print(" seconds"); esp_sleep_enable_timer_wakeup(SPIFFS_Data.Sleep_Period * uS_TO_S_FACTOR); esp_deep_sleep_start(); } else { Serial.print("Going to sleep for "); Serial.print(Sleep_Period_After_Error); Serial.print(" seconds"); esp_sleep_enable_timer_wakeup(Sleep_Period_After_Error * uS_TO_S_FACTOR); esp_deep_sleep_start(); } bool GET_IP_Address () { char *p0; char *p1; int span; p0=strstr(Receive_buffer,"CNACT: "); if (p0!=NULL) { p0=p0+strlen("CNACT: "); p1=strstr(p0,"\n"); if (p1!=NULL) { span=min(19,p1-p0); strncpy(IP_buffer, p0, span); IP_buffer[span]='\0'; Serial.print("IP_buffer : "); Serial.println(IP_buffer); Serial.print(" : "); Serial.println(strlen(IP_buffer)); if (strlen(IP_buffer) >15) {return true;} else {return false;} // 0,1,"10.236.109.95" } else { return (false); Serial.println("No IP address"); } } else { return (false); } } bool Process_DateandTime(bool PSUTZ) { char *Process_ptr; bool Date_Error; Date_Error=false; //Process_ptr=strstr(Receive_buffer,"CCLK:"); if (PSUTZ) {Process_ptr=strstr(Receive_buffer,"PSUTTZ:");} else {Process_ptr=strstr(Receive_buffer,"CCLK:");} if (Process_ptr!=NULL) { Serial.println(Process_ptr); strcpy(date_time_char_array,Process_ptr); Serial.println(date_time_char_array); int k=0; for (int i=0; i<strlen(date_time_char_array); i++) { if (strchr(allowed_char,date_time_char_array[i])!=NULL) { date_time_char_array_processed[k]=date_time_char_array[i]; k++; } } Serial.println(date_time_char_array_processed); Process_ptr=date_time_char_array_processed+1; Serial.println(Process_ptr); while (1) { Process_ptr=strtok(Process_ptr,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Year=atoi(Process_ptr); Process_ptr=strtok(NULL,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Month=atoi(Process_ptr); Process_ptr=strtok(NULL,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Day=atoi(Process_ptr); Process_ptr=strtok(NULL,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Hour=atoi(Process_ptr); Process_ptr=strtok(NULL,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Minute=atoi(Process_ptr); Process_ptr=strtok(NULL,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Second=atoi(Process_ptr); Process_ptr=strtok(NULL,"/,:"); // 23/04/14,11:56:48,+08,1 if (Process_ptr==NULL) {DateTime_Error=true;break;} Thisday.Timezone=atoi(Process_ptr); Thisday.Hour=Thisday.Hour+(Thisday.Timezone/4); break; } Serial.println(); Serial.print(Thisday.Year); Serial.print("/"); Serial.print( Thisday.Month); Serial.print("/"); Serial.print( Thisday.Day); Serial.print(","); Serial.print(Thisday.Hour); Serial.print(":"); Serial.print( Thisday.Minute); Serial.print(":"); Serial.print( Thisday.Second); Serial.print(","); Serial.println( Thisday.Timezone); Date_payload="created_at=20"+String(Thisday.Year)+"-"+Int_to_2_Digits(Thisday.Month)+"-"+Int_to_2_Digits(Thisday.Day)+" "+Int_to_2_Digits(Thisday.Hour)+":"+Int_to_2_Digits(Thisday.Minute)+":"+Int_to_2_Digits(Thisday.Second); Serial.println(Date_payload); //Serial.println("Done with it"); //while (1) {delay(300);} if (Thisday.Year<23) {Date_Error=true; } if (Thisday.Month<0 or Thisday.Month>12 ) {Date_Error=true; } if (Thisday.Day<0 or Thisday.Month>31 ) {Date_Error=true; } if (Thisday.Hour<0 or Thisday.Hour>24 ) {Date_Error=true; } if (Thisday.Minute<0 or Thisday.Minute>60 ) {Date_Error=true; } if (Thisday.Second<0 or Thisday.Second>60 ) {Date_Error=true; } } else { //strcpy(fnameJPG,"AA00000001012011.JPG"); Date_Error=true; } return Date_Error; } bool Read_Response_WaitFor(char* StopCharArray,long time_out) { // false als niet gevonden int k=0; long wait_until; char ccc; //while (!Serial2.available() and millis()<wait_until) {delay(10);} time_taken=millis(); wait_until=time_taken+time_out; while (millis()<wait_until) { while (Serial2.available()) { ccc=Serial2.read(); //Serial.print(ccc); if (k<buffer_size-1) { Receive_buffer[k]=ccc; k++; } } Receive_buffer[k]=NULL; if (strstr(Receive_buffer,StopCharArray)!=NULL) { //Serial.println("OK found"); // SIM7600_Error=0; Receive_buffer[k]=NULL; return false; } } //if (k>=buffer_size-1) {SIM7600_Error=1; strcpy(Receive_buffer,SIM7600_Error_list[SIM7600_Error].c_str());return;} //if (millis()>=wait_until) {SIM7600_Error=2; strcpy(Receive_buffer,SIM7600_Error_list[SIM7600_Error].c_str()); return;} Receive_buffer[k]=NULL; time_taken=millis()-time_taken; Serial.println(); Serial.print("1] This operation took "); Serial.print(time_taken); Serial.println(" millisec"); return true; //if (strstr(Receive_buffer,"ERROR")!=NULL) {return true;} else {return false;} } mqtt thingspeak sim7600
steametics one in MATLAB Answers
Last activity on 18 Dec 2023

I have the following code in the "body" section of the ThingHTTP: {"Value1":"%%channel_<my_channer_ID>_field_1%%";"Value2":"%%trigger%%";"Value3":"%%channel_id%%"} I have tried various formats in the above json document but no luck. Everything works - i.e. the React App fires, which calls the App ThingHTTP and finally the IFTTT webhook which sends me an email. BUT without the data I'm trying to pass via the "ValueX" keyword pairs. the body of the email (shown below) is correctly populated EXCEPT for the "ValueX". I've failed to find the issue and asking for second pair of eyes... Thanks Mohsin Email SUBJECT: The event named "{{EventName}}" occurred at {{OccurredAt}} on the Maker Webhooks service email BODY: What: {{EventName}}<br> When: {{OccurredAt}}<br> Temperature: {{Value1}},<br> Light Intensity: {{Value2}},<br> Noise level: {{Value3}}.<br> <br> PLEASE TURN OFF THE LIGHTS.<br> <br> Thanks<br> MMJ<br> Email SUBJECT: The event named "IFTTT_Trigger_TooBright" occurred at January 27, 2020 at 04:57PM on the Maker Webhooks service email BODY: What: IFTTT_Trigger_TooBright When: January 27, 2020 at 04:57PM Temperature: , Light Intensity: , Noise level: . PLEASE TURN OFF THE LIGHTS. Thanks MMJ
AADYA JALOTA in MATLAB Answers
Last activity on 18 Dec 2023

the lamp indicator in ThingSpeak is showing "Field not available". It was working fine few days back but not now. kindly help us out
Shore in MATLAB Answers
Last activity on 16 Dec 2023

I scrape the temperature of my town from a weather service. I set time control to do this every 5 minutes and then send it to my field 6 in my channel. When I do a csv data dump, the data looks like this: FIELDS--- 1 2 3 4 5 6 7 8 2023-12-06T22:12:06-05:00600020 36 2023-12-06T22:12:29-05:0060002159555500 -0.61 0 2023-12-06T22:13:08-05:0060002259555600 -0.60 0etc, etc... So, every 5 minutes, field 6 gets a value. The other fields get a value twice a minute or so. The ThingSpeak widgets (gage, chart, digital) work fine for field 6. ThingSpeak just uses the data it finds in field 6 for widgets. But, my attempted at #6 field plot visualization is blank, because my plotting uses "points", for example, 300 points, and as such, out of 300 reads there are maybe 270 blank #6 fields and 30 filled-in #6 fields. I think that if I upgrade to a paid license, I would be able to fix this issue, but it is not important for my present needs, not having toolbox access with my license, but is is under consideration.
Ed Jacques in Discussions
Last activity on 12 Dec 2023

I have been having problems sending ThingSpeak alerts so I created a simple routine that demonstrates the problem. The code executes successfully but I never receive an email with the alert. What am I doing wrong? % Set Thingspeak address, alerts API key, and options for the HTTTP call alertUrl = "https://api.thingspeak.com/alerts/send"; alertApiKey = "TAKxxxxxxxxxxxxxxxx"; options = weboptions("HeaderFields",["ThingSpeak-Alerts-API-Key",alertApiKey]); % Set content for email subject and body. alertSubject = "ThingSpeak Alert Subject"; alertBody = "ThingSpeak Alert Body"; % Catch errors so the MATLAB code does not disable a TimeControl if it fails try webwrite(alertUrl, "body", alertBody, "subject", alertSubject, options); catch Exception fprintf("Failed to send alert: %s\n", Exception.message); end ThingSpeak Alerts not Working Are you getting any warnings for the code if you trigger it manually? I just sucessfully tested an alert to me. And I assume you are using your own alerts API key? I get no warnings when I trigger manually unless I trigger more than two times in a 30 minutes where I get 429s. I am using my alerts API key. I even tried to regenerate the key to no avail. Strange thing is the alerts worked Sunday but stopped working a couple of days later. Have you checked your remaining balance? Yes, I have 3,000,000 remaining messages. I am having no problems reporting data to ThingSpeak, just with alerts. Also, I have 722 of 800 remaining alerts available. I know ive said a lot of obvious things, but I have to run through them all. any chance a spam blocker or junk folder is cartching the email? Do you see the balance go down when you trigger an alert? Also try taking the try catch off and see if there is any error reported. Yes, I checked my spam folder and see the Alert count decrement each time I attempt to send an alert. I also removed the try catch and see no errors. I am at the point where I am considering deleting my account and starting over but I don't see a way to delete my account. My present guess is that it is something with your email provider. The alerts function is working, since I got alert emails when I tested, and it is sending to your address since, the alert balance is decremented. You cannot delete your ThingSpeak account without deleting your MathWorks account, there is a form for that and its faily complex. In the account settings though, you can change your email address. Would you consider changing your email to a different address, jut for testing? By they way to you have any odd characters in your email address? It could be a formatiing issue. Great idea. I changed my email address to a gmail account and manually initiated two alerts with no errors indicated. The remaining alerts count decremented by two. No emails were received on the gmail account. It appears my attempt to change my address didn't work because as a Licensed Contact I am required to use an email address associated with my company so please disregard the above message. I will technical support to see if they are blocking emails from ThingSpeak. Also sent you regular email from my MathWorks account. Let me know if you see that. Yes, received your email from mathworks.com. Anyway you can send something from ThingSpeak.com? I did not receiveanything from your ThingSpeak account so it looks like the problem is on my end. Thanks for all of your help. I will let you know what I find out. Sorry, Im not able to send an email from ThingSpeak domain. but you can generate one by exporting data from a channel (import export tab of channel view) and then immediately reloading the same csv file back. Then you will get an error message from mail.thingspeak.com saying that you have tried to upload repeat data to a channel and the upload failed. Its the same mailserver as the alerts. Problem resolved. The email was being blocked probably due to the use of the mailgun service on your end. Thanks for all of your help. alerts
Perky Whale in MATLAB Answers
Last activity on 12 Dec 2023

I've been trying to get messages retained using the mqtt3.thingspeak.com broker but they will not retain, either on an Arduino device with pubsub client library, or the MQTTX desktop client. Does the thingspeak broker support the retain flag? I am correctly (as far as I know) setting the retain flag to true however thingspeak will not deliver a retained message to a client upon connection.
Josue in Discussions
Last activity on 12 Dec 2023

Hello I want to upload a single value from a raspberry and I can't find a way. Can somebody help me? Lot of Thanks¡¡ Upload a single value There are a few options. You can use publish to MQTT, and use this example for help. Or you can use the REST API. There is an example using Bulk update on the pi, you can modify using the details from the write Data API. I never published a single write example from Raspberry Pi in the ThingSpeak doc, but feel like I might have put some code up in this forum before. I'd have a search through old threads. In the end I chose a script: DATA=$value curl -X POST "https://api.thingspeak.com/update?api_key=API_KEY&field1=$DATA" Crontab is my friend :-D nice. Killed my solution with simplicity. Well done.
Nik__ in Discussions
Last activity on 12 Dec 2023

Dear all, in the Matlab Analysis I use twice the fuinction thingSpeakRead to read data from a channel, from two different fields. The problem is that so far, only one of the values is read properly and the other one delivers NaN. What could be the reason? Thank you! Here's my code: % TODO - Replace the [] with channel ID to read data from: readChannelID = [xxx]; % TODO - Enter the Read API Key between the '' below: readAPIKey = 'xxxxxxxx'; % TODO - Replace the [] with channel ID to write data to: writeChannelID = [xxx]; % TODO - Enter the Write API Key between the '' below: writeAPIKey = 'xxxxxx'; %% Read Data %% %data = thingSpeakRead(readChannelID, 'ReadKey', readAPIKey); temperature = thingSpeakRead(xxx,Fields=[1]) humidity = thingSpeakRead(xxx,Fields=[8]) thingSpeakRead delivers NaN value thingspeakread nan
Andreas in Discussions
Last activity on 9 Dec 2023

Hallo, ich Neuling hier, und habe das Beispiel WriteMultipleFields benutzt um die Funktionsweise zu verstehen. So weit so gut, hat auch alles grklappt. Jetzt nach 2 Tagen bekomme ich immer eine Fehlermeldung. Problem updating channel. HTTP error code -401 abwechselnd mit Channel update successful. Es ist immernoch die gleiche Software, Board ist WiFi LoRa 32 V3. Rückmeldung vom ESP Hat sich erledigt, habe den Fehler gefunden. Hatte die Updatetime auf 10 Sek. gestellt um nicht solange warten zu müssen, das scheint dem Server aber nicht zugefallen. Danke und schönen Abend noch fehlermeldung status
Rishivardhan in MATLAB Answers
Last activity on 8 Dec 2023

#include <DHT.h> #include <MQ135.h> #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ThingSpeak.h> // Air Quality Monitoring System #define DHTPIN 2 // GPIO2 on ESP8266 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); MQ135 mq135(A0); // Soil Moisture Sensor const int soilMoisturePin = A0; // Analog pin for soil moisture sensor // WiFi and ThingSpeak settings const char *ssid = "xxxxxx"; const char *password = "xxxxxx"; const char *thingSpeakApiKey = "WL790UNYFNUNVMV2"; const unsigned long airQualityChannel = 2365781; WiFiClient client; void setup() { Serial.begin(115200); delay(10); // Connect to WiFi Serial.println("Connecting to WiFi"); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); ThingSpeak.begin(client); } void loop() { // Air Quality Monitoring float humidity = dht.readHumidity(); float temperature = dht.readTemperature(); float airQuality = mq135.getPPM(); // Soil Moisture Reading int soilMoisture = analogRead(soilMoisturePin); Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" °C\t"); Serial.print("Humidity: "); Serial.print(humidity); Serial.print(" %\t"); Serial.print("Air Quality: "); Serial.print(airQuality); Serial.print(" ppm\t"); Serial.print("Soil Moisture: "); Serial.print(soilMoisture); Serial.println(" (0-1023)"); updateAirQuality(temperature, humidity, airQuality, soilMoisture); delay(15000); } void updateAirQuality(float temperature, float humidity, float airQuality, int soilMoisture) { ThingSpeak.writeField(airQualityChannel, 1, temperature, thingSpeakApiKey); ThingSpeak.writeField(airQualityChannel, 2, humidity, thingSpeakApiKey); ThingSpeak.writeField(airQualityChannel, 3, airQuality, thingSpeakApiKey); ThingSpeak.writeField(airQualityChannel, 4, soilMoisture, thingSpeakApiKey); int writeSuccess = ThingSpeak.writeFields(airQualityChannel, thingSpeakApiKey); if (writeSuccess) { Serial.println("ThingSpeak update successful"); } else { Serial.println("Error updating ThingSpeak"); } } this is my code i can't see the data is updating but in serial monitor i can see the total 4 fields updating in thingspeak i can only see the field 1 is updating and remaining 3 or updated only once and not again so please help me in this please
Matteo in Discussions
Last activity on 7 Dec 2023

Buongiorno, non mi è possibile connetermi al canale di thingspeak che ho creato, per passare i dati tramite MQTT. Il codice segue la libreria PubSubClient su arduino ide, l'errore restituito dal serial monitor dell'ide é: -4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time. Allego il codice per eventuali verifiche: Grazie per a disponibilità #include "PubSubClient.h" #include <ESP8266WiFi.h> #include "secrets.h" bool DEBUG = false; // true=serial message of debug enabled char* server = "mqtt.thingspeak.com"; WiFiClient wifiClient; PubSubClient client(server, 1883, wifiClient); String payload; // BME280 Setting #include <Wire.h> #include <Adafruit_BME280.h> //#define SEALEVELPRESSURE_HPA (1013.25) Adafruit_BME280 bme; // I2C bool BMEStatus; ADC_MODE(ADC_VCC); // Set ADC for read Vcc // Update time in seconds. Min with Thingspeak is ~20 seconds const int UPDATE_INTERVAL_SECONDS = 3600; //il clock interno ha un errore del 5% questo valore va tarato sperimentalmente //const int UPDATE_INTERVAL_SECONDS = 60; // caricamento ogni minuto solo per test void setup() { // Connect BME280 GND TO pin14 OR board's GND pinMode(14, OUTPUT); digitalWrite(14, LOW); Serial.begin(115200); delay(10); // BME280 Initialise I2C communication as MASTER Wire.begin(13, 12); //Wire.begin([SDA], [SCL]) BMEStatus = bme.begin(); if (!BMEStatus) { if (DEBUG) { Serial.println("Could not find BME280!"); } //while (1); } // Weather monitoring See chapter 3.5 Recommended modes of operation bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, // temperature Adafruit_BME280::SAMPLING_X1, // pressure Adafruit_BME280::SAMPLING_X1, // humidity Adafruit_BME280::FILTER_OFF ); // read values from the sensor float temperature, humidity, pressure; if (BMEStatus) { temperature = bme.readTemperature(); humidity = bme.readHumidity(); pressure = bme.readPressure() / 100.0F; } else { if (DEBUG) Serial.println("Could not find BME280!"); temperature=0; humidity=0; pressure=0; } float voltage = ESP.getVcc(); voltage = voltage/1024.0; //volt if (DEBUG) { Serial.println("T= " + String(temperature) + "°C H= " + String(humidity) + "% P=" + String(pressure) + "hPa V=" + voltage + "V"); } // Construct MQTT payload payload="field1="; payload+=temperature; payload+="&field2="; payload+=humidity; payload+="&field3="; payload+=pressure; payload+="&field4="; payload+=voltage; payload+="&status=MQTTPUBLISH"; //Connect to Wifi if (DEBUG) { Serial.println(); Serial.print("\nConnecting to WiFi SSID "); Serial.print(SECRET_SSID); } WiFi.begin(SECRET_SSID, SECRET_PASS); int timeOut=10; // Time out to connect is 10 seconds while ((WiFi.status() != WL_CONNECTED) && timeOut>0) { delay(1000); if (DEBUG) { Serial.print("."); } timeOut--; } if (timeOut==0) //No WiFi! { if (DEBUG) Serial.println("\nTimeOut Connection, go to sleep!\n\n"); ESP.deepSleep(1E6 * UPDATE_INTERVAL_SECONDS); } if (DEBUG) // Yes WiFi { Serial.print("\nWiFi connected with IP address: "); Serial.println(WiFi.localIP()); } // Reconnect if MQTT client is not connected. if (!client.connected()) { reconnect(); } mqttpublish(); delay(200); // Waiting for transmission to complete!!! (ci vuole) WiFi.disconnect( true ); delay( 1 ); if (DEBUG) { Serial.println("Go to sleep!\n\n"); } // Sleep ESP and disable wifi at wakeup ESP.deepSleep( 1E6 * UPDATE_INTERVAL_SECONDS, WAKE_RF_DISABLED ); } void loop() { //there's nothing to do } void mqttpublish() { // read values from the sensor float temperature, humidity, pressure; if (DEBUG) { Serial.print("Sending payload: "); Serial.println(payload); } // Create a topic string and publish data to ThingSpeak channel feed. String topicString ="channels/" + String( channelID ) + "/publish/"+String(writeAPIKey); unsigned int length=topicString.length(); char topicBuffer[length]; topicString.toCharArray(topicBuffer,length+1); if (client.publish(topicBuffer, (char*) payload.c_str())) { if (DEBUG) Serial.println("Publish ok"); } else { if (DEBUG) Serial.println("Publish failed"); } } void reconnect() { String clientName="MY-ESP"; // Loop until we're reconnected while (!client.connected()) { if (DEBUG) Serial.println("Attempting MQTT connection..."); // Try to connect to the MQTT broker if (client.connect((char*) clientName.c_str())) { if (DEBUG) Serial.println("Connected"); } else { if (DEBUG) { Serial.print("failed, try again"); // Print to know why the connection failed. // See http://pubsubclient.knolleary.net/api.html#state for the failure code explanation. Serial.print(client.state()); Serial.println(" try again in 2 seconds"); } delay(2000); } } } Difficoltà di connessione con il client MQTT al server di thingspeak Your code is using the deprecated MQTT format. Have a look at the MQTT doc for the new format, and see the examples for some code. You will have to make an MQTT devicein ThingSepak and add the channel that you want to be able to interact with to th device for publish and subscribe. thingspeak mqtt
titus in Discussions
Last activity on 6 Dec 2023

Am running multiple sensors in the field producing strings of data then sending them to a node. The node is an Arduino Uno on which SIM 800 is attached for internet connectivity. After computation, the result is several strings that i want to display to things speak. The code i have so far can only upload numerical data. Am in need of help to display these strings in Thingsspeak.Help me. How to display Strings in Thingspeak using SIM800 and Arduino Uno You can write string data to ThingSpeak just as you write numrical data. The automatic field plots wont show it, so you can write that string data to the status field, and enable the status display in your channel settings. Or create a custom MATLAB visualization to show the text read from any field. To create the visualization, you can use thingSpeakRead, then figure, then the text function, or various other methods. sim 800 sim800 arduino uno
Hafiz Hamza in Discussions
Last activity on 5 Dec 2023

Dear Team, I have populated my data on ThingsBoard platform using ESP8266, now I want to read that data using MATLAB Industrial Communication Toolbox. I have written a code for this purpose below, % Replace these values with your ThingsBoard MQTT broker details brokerAddress = "ssl://demo.thingsboard.io"; % Adjust the broker address port = 1883; % Use the appropriate port for secure MQTT % Replace these values with your ThingsBoard device details clientID = ""; userName = ""; password = ""; % Leave empty if not required % Replace this with the path to the root certificate you downloaded rootCert = ""; % Create an MQTT client mqClient = mqttclient(brokerAddress, 'Port', port, 'ClientID', clientID, ... 'Username', userName, 'Password', password, 'CARootCertificate', rootCert); % Check if the connection is established mqClient.Connected % Expected output: ans = int32(1) % Subscribe to the telemetry topic topicToSub = "v1/devices/me/telemetry"; subscribe(mqClient, topicToSub); % Wait for a while to receive messages (adjust the time as needed) pause(60); % Peek at the MQTT client to view received messages peek(mqClient); % Close the MQTT client clear mqClient; %%%%__________________Output Result______________________%%%%% >> MQTT_Receive Warning: Using a port that allows unencrypted communication. For confidential matters, considering using an encryption enforcing port, such as 8883. Error using MQTT_Receive Failed to establish a connection with broker "ssl://demo.thingsboard.io". I desperately seeking your assistance in this regard MATLAB Communication With ThingsBoard To Read Data It looks like the device is expecting a secure connection. Can you change the port number to 8883 and try to connect again? Eric Thank you very much for your responce. I am populatin the data on the ThingsBoard using 1883 port. After exploring further I found that there is a mistake in the line below brokerAddress = "ssl://demo.thingsboard.io"; % Adjust the broker address (for secure port) brokerAddress = "tcp://demo.thingsboard.io"; % Adjust the broker address (for 1883). After chnaging still the same result. not able to get the desired output...
Alan Benn in Discussions
Last activity on 4 Dec 2023

I'm logging data which I'd like to see on a daily basis. ie each day the chart x axis resets to 12midnight to 12midnight for the current day and just shows todays data. Is this possible please ? Line chart showing daily data I'm not totally clear about the result you would like. It seems like you are describing what the filed plots on your channel look like. Can you add more description about what you want to see? Here is an example that shows multiple days of data on the same plot. Is that example close to what you wanted? Thats sort of what I want yes. In fact overlaying 2-3 days of recent data might be useful. The field plots on my channel are OK but the x axis, ie time, isn't fixed at 12midnight to 12 midnight for the current day. Even if I set the x range to 1 day, it keeps changing as data flows in and shows some of yesterdays data. Even with the example you gave, does the chart change as a new day starts ? ie what was day 3 becomes day 2, day2 becomes day 1 and the new data for day 3 starts populating. My data points come in each hour. Anyway thanks, I'll look at the example and see how that goes. I haven't done much with visualisations.
Alec in MATLAB Answers
Last activity on 4 Dec 2023

I'm trying to make a website with a bunch of embedded html scripts that display data received from a Simulink program. All of my numerical data I can make public and then put the iFrame code onto my website, but when I go to add an image widget into my public channel there isn't an option to do this. I've tried using thingSpeakRead() in MATLAB using the API key with no luck. How does one publicly display images uploaded to ThingSpeak? They did it here, and I can't figure out how: https://thingspeak.com/channels/366768
Perky Whale in MATLAB Answers
Last activity on 29 Nov 2023

I have a few ESP8266 running various sensor tasks, and sending GET or POST requests to Thingspeak via api.thingspeak.com. They all connect to the household router. Recently, I became aware of a problem with the devices occasionally timing out when trying to communicate with Thingspeak. For example, here's a bit of code from a basic water level sensor: String url = "http://api.thingspeak.com/update?api_key=xxxxxxxxxxxxx&field1="; url += getdistance(); url += "&field8="; url += batt; http.begin(client, url); int httpcode = http.GET(); Serial.println(httpcode); String payload = http.getString(); Serial.println(payload); http.end(); Fairly often, the connection will fail with a -1 httpcode. Sometimes it will run for weeks with no issues and then suddenly stop connecting. If I type the URL in a browser, it will always work immediately. If I connect the ESP to a mobile hotspot, it will also connect immediately with no issues. I can't find any issues at all with the router, and I've fully reset it etc. I've also confirmed the wifi connection between ESP and router is not the problem. Sometimes one ESP will be running fine, and another will be having connection issues. The next day, the first one will have issues and the other will be fine. So I added a bit of code to see if I could time the connection: server = "api.thingspeak.com" timer= millis(); while(client.connect(server,80)){ delay(10)} t=millis()-timer; Serial.print(t); The devices now connect every time. But the connection can take up to 180 seconds. Some ESP's updating to older channels are much more reliable and connect within a second or two; it seems as though the more recently created channels take longer to connect to. I'm reaching out here because I can't really think of where to begin trying to fix this. Why does a browser succeed immediately updating a channel with the api.thingspeak url but the ESP takes up to 180 seconds? Why do I not have any problems connecting the ESP via a mobile hotspot? Why does the same device work for weeks then suddenly play up? I think I've isolated the problem to either the router or the thingspeak api, and I can't find anything wrong with the router. Might be worth noting that I have an ESP in a heat pump which updates every 15 seconds to thingspeak by MQTT and it hasn't skipped a beat in months so maybe I should upgrade them all to MQTT. Is the api just that flakey? I've seen other posters here with the same issue but it never seems to get resolved.
Perky Whale in MATLAB Answers
Last activity on 28 Nov 2023

I have a few ESP8266 running various sensor tasks, and sending GET or POST requests to Thingspeak via api.thingspeak.com. They all connect to the household router. Recently, I became aware of a problem with the devices occasionally timing out when trying to communicate with Thingspeak. For example, here's a bit of code from a basic water level sensor: String url = "http://api.thingspeak.com/update?api_key=xxxxxxxxxxxxx&field1="; url += getdistance(); url += "&field8="; url += batt; http.begin(client, url); int httpcode = http.GET(); Serial.println(httpcode); String payload = http.getString(); Serial.println(payload); http.end(); Fairly often, the connection will fail with a -1 httpcode. Sometimes it will run for weeks with no issues and then suddenly stop connecting. If I type the URL in a browser, it will always work immediately. If I connect the ESP to a mobile hotspot, it will also connect immediately with no issues. I can't find any issues at all with the router, and I've fully reset it etc. I've also confirmed the wifi connection between ESP and router is not the problem. Sometimes one ESP will be running fine, and another will be having connection issues. The next day, the first one will have issues and the other will be fine. So I added a bit of code to see if I could time the connection: server = "api.thingspeak.com" timer= millis(); while(client.connect(server,80)){ delay(10)} t=millis()-timer; Serial.print(t); The devices now connect every time. But the connection can take up to 180 seconds. Some ESP's updating to older channels are much more reliable and connect within a second or two; it seems as though the more recently created channels take longer to connect to. I'm reaching out here because I can't really think of where to begin trying to fix this. Why does a browser succeed immediately updating a channel with the api.thingspeak url but the ESP takes up to 180 seconds? Why do I not have any problems connecting the ESP via a mobile hotspot? Why does the same device work for weeks then suddenly play up? I think I've isolated the problem to either the router or the thingspeak api, and I can't find anything wrong with the router. Might be worth noting that I have an ESP in a heat pump which updates every 15 seconds to thingspeak by MQTT and it hasn't skipped a beat in months so maybe I should upgrade them all to MQTT. Is the api just that flakey?
Hans Scharler in Blogs
Last activity on 27 Nov 2023

The MATLAB AI Chat Playground was launched on the MATLAB Central community at the end of November. I recently got the chance the interview the chatbot about ThingSpeak. I was curious how much it knew about building IoT projects on ThingSpeak and data analysis with MATLAB. Here are some excerpts fro...
Mckenzie Gibson in MATLAB Answers
Last activity on 27 Nov 2023

I am getting my data and visuualizing it but I want to export the data to a spreasheet (libraoffice) Somehow I did it once but cant repeat it. I want to export all five fields.
William Glass in Discussions
Last activity on 22 Nov 2023

Hello I have been using ThingSpeak for about 2 years with no problems. I am observing sensor data and connecting widgets to some of the values. Since yesterday, there are some of the widgets that send blank values. Have you changed something? Thank you widgets I have noticed some intermittant issues with the web page in the past two days (it is being looked into), but the data ingestion seems to be fine. Can you show a screen shot of the issue you are seeing? Hello Here are 2 files graph AirTemp,AirBat widget Airtemp,Airbat We are working on this issue. In the meantime, you should be able to use a browser refresh to get the widgets back. Thank you

About ThingSpeak

The community for students, researchers, and engineers looking to use MATLAB, Simulink, and ThingSpeak for Internet of Things applications. You can find the latest ThingSpeak news, tutorials to jump-start your next IoT project, and a forum to engage in a discussion on your latest cloud-based project. You can see answers to problems other users have solved and share how you solved a problem.