Manira in MATLAB Answers
Last activity on 3 Feb 2023

I have used the following code in Raspi 4. When I run the code it displays field1 and field2 on the screen. However my channel is not receiving any data. Writing Payload = field1=6.6&field2=17.2 to host: mqtt3.thingspeak.com clientID= xxxxxxxxxxxxxxxxxxxx User xxxxxxxxx PWD xxxxxxxxxxxxxxxx import paho.mqtt.publish as publish import psutil import string # The ThingSpeak Channel ID. # Replace <YOUR-CHANNEL-ID> with your channel ID. channel_ID = "xxxxxxxx" # The hostname of the ThingSpeak MQTT broker. mqtt_host = "mqtt3.thingspeak.com" # Your MQTT credentials for the device mqtt_client_ID = "xxxxxxxxxxxxxxxx" mqtt_username = "xxxxxxxxxxxxx" mqtt_password = "xxxxxxxxxxxxx" t_transport = "websockets" t_port = 80 # Create the topic string. topic = "channels/" + channel_ID + "/publish" while (True): # get the system performance data over 20 seconds. cpu_percent = psutil.cpu_percent(interval=20) ram_percent = psutil.virtual_memory().percent # build the payload string. payload = "field1=" + str(cpu_percent) + "&field2=" + str(ram_percent) # attempt to publish this data to the topic. try: print ("Writing Payload = ", payload," to host: ", mqtt_host, " clientID= ", mqtt_client_ID, " User ", mqtt_username, " PWD ", mqtt_password) publish.single(topic, payload, hostname=mqtt_host, transport=t_transport, port=t_port, client_id=mqtt_client_ID, auth={'username':mqtt_username,'password':mqtt_password}) except (keyboardInterrupt): break except Exception as e: print (e)
david phan in Discussions
Last activity on 2 Feb 2023

Hi all, I am wondering whats the total cost to use MATLAB for algo trading. The transparent part is of coz the price of matlab and the toolboxes. But I was shocked to find out the APIs to connect to Interactive Brokers are not free (costly in fact!). Is there free API to connect to IB? What other hidden costs are there? I saw the X Trader in the Automated Trading with MATLAB video. Is this XTrader software part of MATLAB toolbox? Do we need to pay additional to Trading Technologies (to use X_Trader). Also what data feed is the most cost effecient? Is there any additional hidden cost that I am not aware of? Thanks! Full transparent cost of using MATLAB for Algo Trading Log into your MathWorks account and click the Get MATLAB link near your avatar at the top. This will lead you to options for purchasing or provide you a way to contact sales staff to get a quote. XTrader is owned by trading technologies but the datafeed toolbox is compatable and can communicate with the XTrader system.
Andrew Clark in Discussions
Last activity on 2 Feb 2023

Hello, I need help with a simple example. I am trying to do a simple bulk update using JSON & Javascript, using this parm, header and body: $.post("https://api.thingspeak.com/channels/xxxxxxxxx/bulk_update.json" ,{ "Content-Type": "application/json", "write_api_key" : "xxxxxxxxxxxxxxxx", "updates": [ { "created_at": "2022-12-30 10:26:2 -0800", "field1": 100, "status": "good" }, { "created_at": "2022-01-12 10:27:2 -0800", "field2": 100, "field3": 200, "field5": 600, "latitude": 123, "longitude": 23, "elevation": 34 }], function(data){ console.log(data) // log anything returned to the console } }); When I run the above (Mac OS, Chrome) I receive this error message: Access to XMLHttpRequest at 'https://api.thingspeak.com/channels/1283582/bulk_update.json' from origin 'https://backpaqlabs.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. api.thingspeak.com/channels/1283582/bulk_update.json:1 Failed to load resource: net::ERR_FAILED Is there something wrong with the syntax or JSON payload? I have literally taken it from the example in the doc, so I assume it should comply with the API endpoint. BTW, I am receiving CORS errors with getJSON as well, also from Javascript/Chrome. Appreciate any help. Thanks! Still getting CORS error with Bulk Update I think the browser route is specifically denied in the CORS policy on purpose. Ill see what else I can find out. Hi Christopher, thanks for the response. Javascript, which runs in browsers such as Chrome, is allowed, and I use it extensively to fetch data (ie, READ) from Thingspeak. The issue seems to be with WRITE/UPDATE, as all of my READ API functions are currently working. My question is concerning the WRITE function and what seems to be blocking my API calls on your server/endpoint. Can you please verify that UPDATE API requests (and specifically, BULK UPDATE) from outside THINGSPEAK.COM domain are allowed by your CORS policy to access the Thingspeak servers? Thanks much! The dev team agrees with you that bulk update via browser is not specifically prohibited in our policy. You should also have the header 'Access-Control-Allow-Origin' with the value set to *. Do you have this in your request? Christopher, thanks for the tip. Unfortunately, same result using 'Access-Control-Allow-Origin' : '*' in the request Header. I was able to get the "non-bulk" request to work, that is, "update.json". So it seems it's something specific to Bulk. I am also wondering if it could be something in the JSON body that's triggering the error...is the JSON syntax somehow position sensitive, ala Python (in other words, are invisible blanks or tabs a problem in the JSON?) Thanks! Hi Christopher, need to bump this Q as i am still unable to perform the Bulk Updates using JSON due to CORS errors. Can you please confirm with development that I should be able to do the bulk method as described in the above example? Thanks much! I tried out your code and I think this is not a ThingSpeak issue. If I change the URL to anything, I still get the error. Ill keep plugging though. Hi Christopher, thanks for taking a look! It may not be a Thingspeak issue per se, but may be something to do with how the JSON request is formatted or specified. I have tested the JSON and it's semantically correct and correctly formatted. To me, it's still a Thingspeak issue if simple Update API requests will not work or are so hard to use that users will give up. As has been mentioned several times prior, it would be great if we could do this request from the Library API or some other easier-to-use method. Thanks! bulk update json javascript cors
Ray Berkelmans in Discussions
Last activity on 31 Jan 2023

Hi I used to have the following daily max, min and mean code working. But, this week it seems to work for max and mins but not means. Any idea what's going on? writeAPIKey = 'xxxxxx'; % Define date range of 1 day end1 = datetime('now') start=datetime('today') % Read Weight data from Field1 for last 24 hrs [Weight, time] = thingSpeakRead(xxxxxx,'DateRange', [start,end1], 'Fields', [1]); Wtmax = max(Weight); % Get 24hr Max Wtmin = min(Weight); % Get 24hr Min Wtav = mean(Weight); % Get 24hr Av % display results display(Wtmax, 'Wt_max'), display(Wtmin, 'Wt_min'), display(Wtav, 'Wtav'); Output: end1 = datetime 30-Jan-2023 14:00:35 start = datetime 30-Jan-2023 Wt_max = -0.0685 Wt_min = -0.5190 Wtav = NaN Matlab calcs no longer work for averages? I would suspect there are missing or nan values in the dataset. MATLAB is very explicit about how it handles these cases, but it may be different for mean than for max and min. If you find this is the case, have a look at the reference page for mean, and see the part about 'nanflag'. OMG, that was indeed it! I didn't think to check because I could tell from my graphs (all my channels) that there were no missing values or NANs. What I didn't count on was that the very process of calculating a new value and inserting that into the db creates a new timestamp which shows up as an empty cell in all fields except for the newly calculated field. That is certainly a trap for newbies! Using 'omitnan' fixed the issue. I'm kinda wondering why this wouldn't be the default implementation of the Mean (or similar) calculation? Chris, thank you! Generally it is best to put derived data into a new channel, not the same one. Thanks for letting me know it worked, you made my night! ( I like to help users) Its probably not the default becasue if you had a regular data set with no nan, you might want to know if nan started showing up so you could make the decision to omit on purpose insted of on accident. Im not sure, though, I think that design review was before I joined MathWorks! We actually have a lot of meetings where we try to guess how users would encouter issues in our functions and then design the function to best handle it if possible. Thanks for posting on the forum, if you get the chance, please share more detail about your project if you can.
abba baab in MATLAB Answers
Last activity on 29 Jan 2023

Why I am getting error: Error using timetable/retime All variables in input timetables must be numeric, datetime, or duration when synchronizing using 'mean'. Error in ko - 1h avg to new channel (line 10) avgdata=retime(data,'regular','mean','TimeStep',hours(hourz)); DATA EXPORT CSV LOOKS LIKE: 2023-01-21T23:47:13+02:004516153323.18729.2718.2318.61-8.593-10 CODE ko - 1h avg: dayz=1; hourz=1; rc=1234; rk='KEY'; wc=5678; wk='KEY'; data=thingSpeakRead(rc,'ReadKey',rk,'OutputFormat','timetable','numDays',dayz); avgdata=retime(data,'regular','mean','TimeStep',hours(hourz)); thingSpeakWrite(wc,avgdata,'WriteKey',wk);
abba baab in MATLAB Answers
Last activity on 28 Jan 2023

Any idea is it possible to get data from Shelly 1pm (relay with power meter) to Thingspeak? I tried my best but entries stayed "0". Shelly mqtt documentations: https://shelly-api-docs.shelly.cloud/_review/mqtt/#settings https://shelly-api-docs.shelly.cloud/_review/mqtt/#shelly-switch-mqtt -> "meters" -> "power" is what I would like to input to Thingspeak. Screenshot of Shelly 1pm mqtt default settings. I tried using user:user + password:apikey + server: http://mqtt.thingspeak.com:1833 as instructed in https://se.mathworks.com/help/thingspeak/use-desktop-mqtt-client-to-publish-to-a-channel.html .
Fatin in MATLAB Answers
Last activity on 25 Jan 2023

I have an iot project working. But it keep update data which is temperature and humidity every 3min. i dont want that. i want the data to keep update every 12 hour and everyday.
Pedro in Discussions
Last activity on 25 Jan 2023

Hi, what would be the best approach to use the gauge widget to display calculated data? I have a channel that displays a value that needs some math applied to it to give a correct value. I have a matlab visualization that converts this value into what I need and plots it. However, i believe a gauge is more appropriate than a plot and it seems the matlab "uigauge" object does not work for thingspeak. Is there a way for the gauge widget to show my data coming out of the matlab script? Thanks! Gauge widget with matlab data There is a Gage widget built into thingSpeak. On the channel view, select Add Widget, and choose the gage widget. Select the channel, field, and propoerties of the gage widget and the channel where you want it to be displayed. See the widget help for more info. Hi Christopher, thank you for the feedback. I understand that there is a built in feature for that, but it seems seems like it only works for data from the fields that I publish. I wanted to have a gauge to show the result of a matlab script. Say if a channel publishes a 0-100 value, but I use matlab to conver it to a value between 5-35. How could I add a gauge for that? Are you using desktop MATLAB, or MATLAB analysis/viz in ThingSpeak? Either way, after the conversion, you can write back to a new channel and set the gage to read from that new channel. You can also write code in MATLAB to generate a gage visualization for you. A polar plot makes a good start. I mean in MATLAB analysis/viz in ThingSpeak. In regular MATLAB I can create a gauge with uigauge with no issues. I just wanted to see if I could do the same in ThingSpeak but it seems like I will have to write to a different channel. Most UI elements arent allowed in ThingSpeak due to the interface. I have some fairly medium quality gage code that would work in a MATLAB viz, Ive been meaning to post it on file exchange. Thanks for the push. Would something like this work for you? Its a MATLAB function you can run in ThingSpeak to make a gage in a MATLAB viz Absolutely! Thanks for your help! Im not going to get around to putting this on File exchange becasue its too sloppy of a solution, but if it works for you, here is the silly function I wrote (be careful if you use small numbers, the rounding will kill it). % Sample call mygage(475,1,3000,0,1200,1200,1800,1800,2800,25); function MakeGage = mygage(value, lowRange,highRange,greenLow,greenHigh,yellowLow,yellowHigh,redLow,redHigh,nTicks) % TODO range cannot be less than 1 due to rounding fullRange = highRange - lowRange; greenStart = 230 - (360-80) / fullRange * (greenLow - lowRange); greenEnd = 230 - (360 - 80) / fullRange * (greenHigh - lowRange); yellowStart = 230 - (360 - 80) / fullRange*(yellowLow - lowRange); yellowEnd = 230 -(360 - 80) / fullRange * (yellowHigh - lowRange); redStart = 230 - (360 - 80) / fullRange * (redLow - lowRange); redEnd = 230 - (360 - 80) / fullRange * (redHigh - lowRange); tickMove = fullRange / nTicks; green = [greenStart:-5:greenEnd]; green = green*2*pi/360; rgreen = ones(1,size(green,2)); polarplot(green, rgreen,'g','LineWidth',16); hold on yellow = yellowStart:-5:yellowEnd; yellow = yellow*2*pi/360; ryellow = ones(1,size(yellow,2)); polarplot(yellow, ryellow,'y','LineWidth',16); red = redStart:-5:redEnd; red = red*2*pi/360; rred = ones(1,size(red,2)); polarplot(red, rred,'r','LineWidth',16); valueAngle = 230 - (360-80) / fullRange * (value - lowRange); rblack = [0:0.1:1]; black = valueAngle * 2 * pi/360 * ones(1,size(rblack,2)); polarplot(black, rblack,'k','LineWidth',5); ax = gca; ax.RTickLabel = []; ax.RGrid = 'off'; width = 280 / nTicks; tickHold = 0:width:280; tickHold = tickHold-50; tickHold = [tickHold(tickHold>=0),tickHold(tickHold<0)+360]; ax.ThetaTick = tickHold; %ax.ThetaTick=[0:width:230,310:width:360]; tickLabels = round([highRange:-tickMove:lowRange],0); shift = round(50 / width); tickLabels = circshift(tickLabels,-shift); ax.ThetaTickLabel = tickLabels; ax.RLim = [0,1.05]; text(265*2*pi/360,0.8,string(value),'fontSize',20); hold off end matlab widgets gauge
NHON NGUYEN in Discussions
Last activity on 24 Jan 2023

There is exactly the same tutorial for my topic but I couldn't make it work. It worked like a charm on SMS service but it wasn't on call. Authentication shouldn't be a problem cause it's similar to SMS configuration. The remaining information that I've doubt is the "Body" part. I filled it like: From={+Twilio number}&To={+myNumber}&Body=CO2 concentration is exceeding the threshold value and being at :%%channel_1372010_field_3%% And also, the API URL is: https://api.twilio.com/2010-04-01/Accounts/{My AuthSID}/Calls.json I replaced my own information on the above items but It didn't make a call at all even when the TimeControl app run it. Hope to get your help. Make phone calls with Twilio using ThingHTTP Here is the POST format from the <https://www.twilio.com/docs/voice/make-calls# Twilio doc> . It looks like there isn't a body parameter or key. curl -X POST https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Calls.json \ --data-urlencode "Url=http://demo.twilio.com/docs/voice.xml" \ --data-urlencode "To=+14155551212" \ --data-urlencode "From=+15017122661" \ -u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN From twilio i want to get a call with voice response having channel data and text to speech part. say, the voice i want as 'Temperature is 100 degree farenhite, here 100 is the channel data. What i shall write in thingHTTP body to get the voice in call response along with data and text as speech. I am getting data voice but facing problem with that text part. Please help I think that question is better posed on a Twillio community. thinghttp twilio
Aldara López in Discussions
Last activity on 23 Jan 2023

I want to import data from a .cvs with the requested format but constantly the same error comes out : "The uploaded file was not imported because it is missing timestamps." My data is in this format: created_at,field1,field2,field3 1600064881,50.818,0,0 Could someone help me fix it? Thank you Import data to thingspeak I just used the template provided at the import tab on my ThingSpeak channel, it includes epoch format.The file worked fine for me. Can you download the template and use that for your data? Using the template it works perfectly, the only thing that missing was the id. Thank you so much thingspeak import
Silvia Booij in MATLAB Answers
Last activity on 22 Jan 2023

My MQTT client sends different sensor data to thingspeak MQTT broker via a single MQTT device. Following the MQTT device procedure found on the Mathworks website. My MQTT client reports back no errors (100% succesfull MQTT data transmission). But I cannot figure out how to select which data to make visible in the different ThingSpeak fields. At this moment the field in the selected channel has the name of the datafield in the MQTT message, but no data appears. And I do not see any data when I download the Channel's feeds in CSV format. The only work around I can think of is create via an ESP another MQTT server who retrieves the data from ThingsSpeak and sends it back to the ThingSpeak channel without using the MQTT channel (as I do with the non-MQTT devices), but this sounds silly. What is the normal method to make MQTT data visible without adding other hardware?
Håkon Dahle in MATLAB Answers
Last activity on 21 Jan 2023

I use the REST API to read data from Thingspeak and this works well: https://api.thingspeak.com/channels/xxxxxx/fields/1.json?average=daily&start=2010-01-01&end=2011-01-01 This request correctly returns one value per day. However I need a monthly average - a single value per month. Ideally something like: https://api.thingspeak.com/channels/xxxxxx/fields/1.json?average=MONTHLY&start=2010-01-01&end=2011-01-01 Is there a way to achieve something like this?
George in Discussions
Last activity on 14 Jan 2023

Hi there, I am using the following code in order to try and access th location of my device (via MATLAB visualization): myChannel=*******; ReadAPIKey='xxxxxxxxxxxxx'; myData=thingSpeakRead(myChannel,'ReadKey', ReadAPIKey,'numpoints',100,'outputformat','timetable','location',1); myVector=(myData.Latitude).^2+(myData.Longitude).^2+myData.Altitude.^2; maxVector=max(myData.Latitude)^2+max(myData.Longitude)^2+max(myData.Altitude)^2; myVector=myVector/maxVector; myMap=geoscatter(myData.lat,myData.long,15,myVector,'filled'); geobasemap('satellite'); colormap jet; At the moment, I have only 100 entries. However, I am getting the error : "Error using . Unrecognized table variable name 'lat'. Error in Custom (no starter code) 2 (line 7) myMap=geoscatter(myData.lat,myData.long,15,myVector,'filled');". How do i fix this error? Or where would i predefine "lat"? I do not want to set "lat" as a constant value as my device will be moving around and I want to access the location of the device per message sent, wherever it may be. Please may anyone assist. Location of a moving device, via MATLAB visualization You might try channel 876466 to practice reading data from. Its one of my channels with position data in it. I'm sorrry I didnt clean up the code I shared above. I had it and I wanted to share quickly but I didnt test it. Use myData.Latitude and myData.Longitude and you shouldnt get an error, assuming there is location data in the channel. To make sure there is position data in the channel, you have to use the format for the write REST call that I gave in the other post. The parameters for &latitude=xx and &longtitude=yy have to be written to the channel at least once. Every time you read the channel, you will get the most recent n points that show where your device is. There are a lot of ways to handle the changing number of entries. For one, when you read you can use a set time format parameter, such as days= or minutes=. Then thingspeak will retrurn as many points (up to 8k) that are in that time range. There are alse begin and end parameters, and you can use datatime manipulation to set rolling dates with your code. When you read the data, if you need to know the number of points, MATLAB has lots of functions to help with that (size, and height, for example) Another thing you can do is to increment a channel field witht he number of points, then read that channel value to know how many points there are. Hi there, thank you for this helpful reply. I adjusted the variable names and it seemed to be accepted. Upon searching for information about a REST api call, it said that i must search that call in my web's search bar. Is this the correct way to go about doing this? If not, what else would i do? Regarding the ways to handle changing the number of entries, I am slightly unsure on where to use "days=" or "minutes=" within that MATLAB visualization code which you sent previously.Where would I incorporate this in my code? Also, my aim is to solely see the location of the last message which has been sent, including indications of previous locations (the history of other locations). Would this be the best way to do this? Or is there another code which would do this best? If so, please may you share this code as i have struggled to do this and would greatly appreciate some assistance on this problem. Thank you Hi there Chris, please may you let me know if it is possible to show the location history of the device (thus the location of each of the messages recived) on Thingspeak? If it is possible, please may you guide me on how to do this. Thank you Can you clarify what you mean becasue I feel that was the question I already answered above. My aim is to show the location of each message that has ever been sent to the ThingSpeak channel. Such as the image attached below (an example from a Things.io channel). For each message recieved from my device, I want there to be a map and a pin at the precise location at which the message was sent. I am unsure on how to get the code above to do this. I am also still unsure on how to get the number of messages (the 260 or the 100 number in my case) to increase as the incoming messages increases. Also, I am unsure on how to connect the REST api call to the code. I did some research on it and it said to search the REST api call in your browser's search bar. However, this did not work. Please may you assist. Is there another way I could communicate with you, perhaps on email? Thank you for taking the time to describe your goal carefully. You say "show the location of each message that has ever been sent." If your device did not send its location, it is not possible for ThingSpeak to show you the location. Our service does not get the device location from the server if the device did not send the info. Does your device post its location data when it sends data to ThingSpeak? Is your device aware of its location? Support via email is available for holders of commercial or academic licenses. My dvice is sending information from Sigfox to Tingspeak. My Sigfox Atlas is enabled which allows the location of the device to be seen on Sigfox. This was my initial issue, which was how to send the location of my device from Sigfox to Thingspeak. I have a callback enabled on Sigfox's end which sends the "computedLocation" to my field4 of Thingspeak but nothing appears on Thingspeak's end (my goal here is to have a map showing the "computedLocation" from Sigfox), and this is why I think that I am sending the location from Sigfox incorrecly. Do you know how i could send the location from Sigfox to Thingspeak or any other way in which i could do this? I cannot find any resources which do this. Thanks Thats perfect, thanks for the clarification. I see that some of the info was in your earlier posts, but I didnt quite piece it all together. Can you show what the computed location on field 4 looks like - or can you share your channel ID if it is public? Is the data "lattitude,Longitude" or something like that? It might be easier if your callback from sigfox wrote the data into the lattitude and longitude fields, but we can also extract them form field 4 fairly easily too. Once you show me the data format, I can help you use the code above to read the last points in your channel. If you ask thingspeak for more data than you have, it will return the most recent data up to 8000 points. From what you said the problem about getting an increasing number of locations wont be a problem until you hit 8000. Lets get the map working first and then we can deal with the other issue. Yes I do see how my previous messages could have been confusing, but i really do appreciate all of your help. So on Sigfox this is the location which is being recorded (which is correct and quite precise). Following this, I attempted to make a callback following this blog (which uses thethings.io rather than Thingspeak) : https://blog.thethings.io/computedlocation-sigfox-and-visualize-on-a-map-your-devices/ . From this, I generated the following callback on Sigfox: But I do now recognize how this method could be incorrect since I have not recieved any information to do with location on Thingspeak's end.When I show field 4's visualization, it is a blank graph. This is how i know that I am not recieving anything from Sigfox with the above callback. However, since the link above is the only source that I can find which is doing what I aim to do, I am at a loss. Sigfox does have different variables which can be sent through a DATA-ADVANCED callback, which can be seen here: https://support.sigfox.com/docs/data-advanced . However, when I try to enter variables into the "Body" section of the callback, such as "computedLocation.lat", it says that "computedLocation.lat" is undefined and does not let me save the callback. I have also tried to see why this is the case but cannot find the solution. Thus, computedLocation was the variable which i have been attempting to pass to Thingspeak, as i imagine that once it is sent correclty, I will have access to a map on Thingspeak which illustrates the device's location per message sent, similar to the map above. This is a basically a summary of the root to my issue. I know that you have not worked with Sigfox so I really do appreciate your advice and guidance to solve this issue. I made my channel public so that you can see. My channel ID is 1970146 Thanks Im glad you redacted your API key, but I cant quite see the format you used. Is here any other field information in the URL pattern? Looking at your channel, there seems to be data getting in, was that data a result from the callback above? In the POST body, you should consider using field1=(some data) field3=(other data) field4={computedlocation} or something similar. Otherwise ThingSpeak wont know where you want to put the data. For the sigfox callback, I would consider using the body for your variables (like field4=) as in the JSON example here https://www.mathworks.com/help/thingspeak/writedata.html But I think the {computedlocation} question will have to go to sigfox, I'm sorry. Hi there Chris, thank you for your response. So from what I know, you set the field information in the "URL pattern" section of the Sigfox callback. The callback which is above was simply an attempt to get the {computedLocation} to send, the information which is showing on my page is a result of the callback below: So I set the URL pattern as https://api.thingspeak.com/update?api_key= XXXXXXXXXXXXX&field1={customData#temp}&field2={customData#t}&field3={customData#h} which thus sends information to the fields directly. The {computedLocation} is not sent from the Arduino code so that is why I didn't include it in this URL pattern and tried to create a separate callback for it. If this is not the best way to access location, is Thingspeak able to access the location of the incoming messages indpendently? Further, if this issue is beyond Thingspeak, I will go forward by attempting to ask Sigfox. Thank you! ThingSpeak does not have a way to localize message source. ITs too bad the callback cant access {computed location} becasue that would be a nice thing to write to ThingSpeak without having to add a GPS to your device. Please let us know if you figure out how to get the data from sigfox. I looked the their doc briefly and it seemed liek it should work close to how you had it above. I see. I will let you know when I manage to find a solution, thank you for all of your time and for your help, it was extremely helpful and is greatly appreciated! location dht11 arduino sigfox temperature humidity latitude longitude
Asfaque in MATLAB Answers
Last activity on 12 Jan 2023

Previously was able to but now i am unable to connect . Tried Re-setting the password , created new channel and even created anopther account . Still unable to connect.
John Anand in MATLAB Answers
Last activity on 9 Jan 2023

I am connecting to ThinkSpeak using a Esp8266 chip on a FireBeetle board. And I am using this code: #include <SoftwareSerial.h> #define RX 2 #define TX 3 String AP = "**********"; // AP NAME String PASS = "*********"; // AP PASSWORD String API = "*************"; // Write API KEY String HOST = "api.thingspeak.com"; String PORT = "80"; String field = "field1"; int countTrueCommand; int countTimeCommand; boolean found = false; int valSensor = 1; SoftwareSerial esp8266(RX, TX); void setup() { Serial.begin(9600); esp8266.begin(115200); sendCommand("AT", 5, "OK"); sendCommand("AT+CWMODE=1", 5, "OK"); sendCommand("AT+CWJAP=\"" + AP + "\",\"" + PASS + "\"", 20, "OK"); } void loop() { valSensor = getSensorData(); String getData = "GET /update?api_key=" + API + "&" + field + "=" + String(valSensor); sendCommand("AT+CIPMUX=1", 5, "OK"); sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK"); sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">"); esp8266.println(getData); delay(1500); countTrueCommand++; sendCommand("AT+CIPCLOSE=0", 5, "OK"); } int getSensorData() { return random(1000); // Test } void sendCommand(String command, int maxTime, char readReplay[]) { Serial.print(countTrueCommand); Serial.print(". at command => "); Serial.print(command); Serial.print(" "); while (countTimeCommand < (maxTime * 1)) { esp8266.println(command);//at+cipsend if (esp8266.find(readReplay)) //ok { found = true; break; } countTimeCommand++; } if (found == true) { Serial.println("OYI"); countTrueCommand++; countTimeCommand = 0; } if (found == false) { Serial.println("Fail"); countTrueCommand = 0; countTimeCommand = 0; } found = false; } __________________________________________________________________________________________________________________ I get this (error?) In the serial monitor when I run it. Output: Fail 0. at command => AT+CWMODE=1 Fail 0. at command => AT+CWJAP="******","********" Fail 0. at command => AT+CIPMUX=1 Fail 0. at command => AT+CIPSTART=0,"TCP","api.thingspeak.com",80 Fail 0. at command => AT+CIPSEND=0,51 Fail 1. at command => AT+CIPCLOSE=0 Fail 0. at command => AT+CIPMUX=1 Fail 0. at command => AT+CIPSTART=0,"TCP","api.thingspeak.com",80 Fail 0. at command => AT+CIPSEND=0,51 Fail 1. at command => AT+CIPCLOSE=0 Fail 0. at command => AT+CIPMUX=1 Fail 0. at command => AT+CIPSTART=0,"TCP","api.thingspeak.com",80 Fail 0. at command => AT+CIPSEND=0,51 Fail 1. at command => AT+CIPCLOSE=0 Fail 0. at command => AT+CIPMUX=1 Fail _________________________________________________________________________________________________________________ What am I doing wrong? The Wifi password and name are correct. I really couldn't find anything online to help. And I'm honestly out of ideas, I've been trying to fix it all day.
Luk in Discussions
Last activity on 6 Jan 2023

Hello, I have a some problem with my OneWire communication and ThingSpeak (ESP8266). Quiet often I have got -127 value, but everything with connections should be OK. I have a free license a TS and two channels in my account. I think that this piece of code may be problem: void loop() { readKWHMeterPC(); readKWHMeterHeat(); read3WayValve(); digitalWrite(POWER_LED, LOW); if ((millis() - lastTimeLoop) >= DELAY_TIME_LOOP){ readTemperatures(); calcenergyPC(); calcenergyHeat(); avgpowerPC(); // nie liczy w pierwszym przebiegu pracy dokładnie i w ostatnim, bo niekoniecznie jest załączenie/wył. równą minutę przed wysłaniem na TS -> w efekcie liczy moc z mniejszej ilości impulsów niż normalnie w ciągu minuty jest przy stałym obciążeniu avgpowerHeat(); write2TSDataCH1( CH1channelID , CH1dataFieldOne , valveState , CH1dataFieldTwo , meterPulsesPC, CH1dataFieldThree, energyPC, CH1dataFieldFour, meterPulsesHeat , CH1dataFieldFive ,energyHeat, CH1dataFieldSix , powerPC, CH1dataFieldSeven, powerHeat ); write2TSDataCH2( CH2channelID , CH2dataFieldOne , tempC1 , CH2dataFieldTwo , tempC2, CH2dataFieldThree, tempC3 ); lastTimeLoop = millis(); } Can I send data to TS to 2 channels in the same time or not? Occasionaly -127 value from DS18B20 It is fine to call two channels sequentially without waiting, provided CH1channelID !=CH2channelID. I would consider outputting the data to the serial monitor so you can check it. Also, you will need to show us the write2TSDataCH1 function for us to help you debug this. #include <ESP8266WiFi.h> #include <OneWire.h> #include <DallasTemperature.h> #include <ThingSpeak.h> #define ONE_WIRE_BUS 5 // D1 #define THREE_WAY_VALVE_PIN D2 //sprzężenie zwrotne z przekaźniczka od zaworu 3-drogowego #define KWH_METER_PC D8 // hardware'owo w ESP pulldown #define KWH_METER_HEAT D7 // nie zapomnieć dodać zewn. R do GND! przy odczycie początkowym robi wtedy impuls "-1", można na upartego zerować to wtedy ifem w setupie (if<0 to zeruj) #define JOULE_METER D6 // joue'lomierz #define POWER_LED D4 #define TIMEOUT 5000 // Timeout for server response. #define ORNO_CONST 800 // Zmienne do ustalania czasu wysyłania danych do TS unsigned long lastTimeLoop = 0; #define DELAY_TIME_LOOP 60000 // wysyłanie danych do TS co 1 min // Zmienne do ustalania czasu debounce dla sygnału zaworu unsigned long lastTimeValve = 0; #define DELAY_TIME_VALVE 500 bool pulseEdgePC = 0; //zbocze narastające dla odczytu impulsów z licznika energii bool pulseEdgeHeat = 0; //Zmienne dla licznika ORNO od pompy ciepła int meterPulsesPC = 0; //zmienna do TS int readMeterPC = 0; // zmienna - odczyt stanu pinu float energyPC = 0; float lastenergyPC = 0; float powerPC = 0; //Zmienne dla licznika ORNO od defrost int meterPulsesHeat = 0; //zmienna do TS int readMeterHeat = 0; // zmienna - odczyt stanu pinu float energyHeat = 0; float lastenergyHeat = 0; float powerHeat = 0; //Zmienne dla licznika GJ int meterPulsesGJ = 0; //zmienna do TS int readMeterGJ = 0; // zmienna - odczyt stanu pinu float energyGJ = 0; float lastenergyGJ = 0; float powerGJ = 0; //Zmienne dla zaworu 3-drogowego int valveState; // aktualny stan zaworu 3-drogowego, zmienna do TS int lastvalveState; // zmienna - ostatni stan pinu int readValve ; // zmienna - odczyt stanu pinu //Zmienne dla temperatur int numberOfDevices; DeviceAddress tempDeviceAddress; float tempC1; //zmienna dla odczytu temperatury #1 - do TS float tempC2; //zmienna dla odczytu temperatury #2 - do TS float tempC3; //zmienna dla odczytu temperatury #3 - do TS //Zmienne dla TS - kanał "cyfrowy" unsigned long CH1channelID = xxxxxx; const char* CH1writeAPIKey = "xxxxx"; // Enter your Write API key from ThingSpeak const char* CH1readAPIKey = "xxxxxx"; unsigned int CH1dataFieldOne = 1; // Field to write temperature data unsigned int CH1dataFieldTwo = 2; // Field to write temperature data unsigned int CH1dataFieldThree = 3; unsigned int CH1dataFieldFour = 4; unsigned int CH1dataFieldFive = 5; unsigned int CH1dataFieldSix = 6; unsigned int CH1dataFieldSeven = 7; unsigned int CH1dataFieldEight = 8; //Zmienne dla TS - kanał "temperaturowy" unsigned long CH2channelID = xxxxxxx; const char* CH2writeAPIKey = "xxxxxxxxxxxxxx"; // Enter your Write API key from ThingSpeak const char* CH2readAPIKey = "xxxxxxx"; unsigned int CH2dataFieldOne = 1; // Field to write temperature data unsigned int CH2dataFieldTwo = 2; // Field to write temperature data unsigned int CH2dataFieldThree = 3; unsigned int CH2dataFieldFour = 4; unsigned int CH2dataFieldFive = 5; unsigned int CH2dataFieldSix = 6; unsigned int CH2dataFieldSeven = 7; unsigned int CH2dataFieldEight = 8; const char *ssid = "xxxxx"; // Replace with your wifi ssid and WPA2 key const char *pass = "xxxxxxxxxxxxxx"; const char* server = "api.thingspeak.com"; OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature sensor WiFiClient client; // Use this function if you want to write multiple fields simultaneously. //https://www.mathworks.com/help/thingspeak/read-and-post-temperature-data.html //https://github.com/mathworks/thingspeak-arduino int write2TSDataCH1(long TSChannel, unsigned int TSField1, int field1Data, unsigned int TSField2, int field2Data, unsigned int TSField3, float field3Data,unsigned int TSField4, int field4Data,unsigned int TSField5, float field5Data, unsigned int TSField6, float field6Data, unsigned int TSField7, float field7Data){ ThingSpeak.setField( TSField1, field1Data ); ThingSpeak.setField( TSField2, field2Data ); ThingSpeak.setField( TSField3, field3Data ); ThingSpeak.setField( TSField4, field4Data ); ThingSpeak.setField( TSField5, field5Data ); ThingSpeak.setField( TSField6, field6Data ); ThingSpeak.setField( TSField7, field7Data ); int writeSuccess = ThingSpeak.writeFields( TSChannel, CH1writeAPIKey ); return writeSuccess; } int write2TSDataCH2( long TSChannel, unsigned int TSField1, float field1Data, unsigned int TSField2, float field2Data, unsigned int TSField3, float field3Data){ ThingSpeak.setField( TSField1, field1Data ); ThingSpeak.setField( TSField2, field2Data ); ThingSpeak.setField( TSField3, field3Data ); int writeSuccess = ThingSpeak.writeFields( TSChannel, CH2writeAPIKey ); return writeSuccess; } int readTSDataCH1( long TSChannel,unsigned int TSField ){ int data = ThingSpeak.readIntField( TSChannel, TSField, CH1readAPIKey ); return data; } float readTSDataFloatCH1( long TSChannel,unsigned int TSField ){ float data = ThingSpeak.readFloatField( TSChannel, TSField, CH1readAPIKey ); return data; } void readTemperatures(){ sensors.requestTemperatures(); tempC1 = sensors.getTempCByIndex(0); tempC2 = sensors.getTempCByIndex(1); tempC3 = sensors.getTempCByIndex(2); } void read3WayValve(){ readValve = digitalRead(THREE_WAY_VALVE_PIN); if (readValve != lastvalveState){ lastTimeValve = millis(); } if ((millis()-lastTimeValve) > DELAY_TIME_VALVE){ if (readValve != valveState){ valveState = readValve; } } lastvalveState = readValve; } void readKWHMeterPC(){ readMeterPC = digitalRead(KWH_METER_PC); if (readMeterPC == HIGH && pulseEdgePC == 0) { meterPulsesPC = meterPulsesPC+1; pulseEdgePC = 1; } if (readMeterPC == LOW){ pulseEdgePC=0; } Serial.println("Impulsy PC:" + String(meterPulsesPC)); } void readKWHMeterHeat(){ readMeterHeat = digitalRead(KWH_METER_HEAT); if (readMeterHeat == HIGH && pulseEdgeHeat == 0) { meterPulsesHeat = meterPulsesHeat+1; pulseEdgeHeat = 1; } if (readMeterHeat == LOW){ pulseEdgeHeat=0; } Serial.println("Impulsy grzałek:" + String(meterPulsesHeat)); } void calcenergyPC(){ energyPC = float(meterPulsesPC)/ORNO_CONST; } void avgpowerPC(){ powerPC = (energyPC-lastenergyPC)/(60.0/3600.0); lastenergyPC = energyPC; //Serial.println(powerPC); } void calcenergyHeat(){ energyHeat = float(meterPulsesHeat)/ORNO_CONST; } void avgpowerHeat(){ powerHeat = (energyHeat-lastenergyHeat)/(60.0/3600.0); lastenergyHeat = energyHeat; } void setup() { Serial.begin(9600); delay(10); sensors.begin(); pinMode(THREE_WAY_VALVE_PIN,INPUT_PULLUP); pinMode(KWH_METER_PC,INPUT); pinMode(KWH_METER_HEAT,INPUT); pinMode(POWER_LED,OUTPUT); Serial.println("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); ThingSpeak.begin(client); meterPulsesPC = readTSDataCH1( CH1channelID, CH1dataFieldTwo ); energyPC = readTSDataFloatCH1( CH1channelID, CH1dataFieldThree ); lastenergyPC = energyPC; meterPulsesHeat = readTSDataCH1( CH1channelID, CH1dataFieldFour ); energyHeat = readTSDataFloatCH1( CH1channelID, CH1dataFieldFive ); lastenergyHeat = energyHeat; } void loop() { readKWHMeterPC(); readKWHMeterHeat(); read3WayValve(); digitalWrite(POWER_LED, LOW); if ((millis() - lastTimeLoop) >= DELAY_TIME_LOOP){ readTemperatures(); calcenergyPC(); calcenergyHeat(); avgpowerPC(); // nie liczy w pierwszym przebiegu pracy dokładnie i w ostatnim, bo niekoniecznie jest załączenie/wył. równą minutę przed wysłaniem na TS -> w efekcie liczy moc z mniejszej ilości impulsów niż normalnie w ciągu minuty jest przy stałym obciążeniu avgpowerHeat(); write2TSDataCH1( CH1channelID , CH1dataFieldOne , valveState , CH1dataFieldTwo , meterPulsesPC, CH1dataFieldThree, energyPC, CH1dataFieldFour, meterPulsesHeat , CH1dataFieldFive ,energyHeat, CH1dataFieldSix , powerPC, CH1dataFieldSeven, powerHeat ); write2TSDataCH2( CH2channelID , CH2dataFieldOne , tempC1 , CH2dataFieldTwo , tempC2, CH2dataFieldThree, tempC3 ); lastTimeLoop = millis(); } } All of the code above. I am testing now onewire on a separate ESP and now everything is okay. Yes, I know about serial monitor, but ESP is far away from me and a person who have it is not technician ;) But if everything in code is OK, I will try to do this (serial monitor). I dont see anything obvious wrong in the code. There isnt any reason ThingSpeak would record a value of -127 unless you sent it exactly that value. Which field values are getting the '-127' value?
Louis in Discussions
Last activity on 6 Jan 2023

Accidentally clicked on the "X" and field 1 chart disappeared. How do I recall the chart ? Field 1 chart missing Click the last open field plot box that says "add visualizations" You will see an option for "field x plot" field chart
MOHAMED in MATLAB Answers
Last activity on 5 Jan 2023

merci de me aidez a trouvé le sens, premieremet mon projet c'est le suivie et commande d'une pompe eau immergé dans un ouits a distance 15KM puis mes utilisations sont arduino nano avec GPRS sim800L et sensor current SCT013 pour donné l'image courant convertir en puissance et energie,j'ai creé une plateforme de commande de la pompe mais le suivieconsommation assissté par thingspeak svp quelq'un me donné la methode ou le code pour que cela meme projet
Andre in MATLAB Answers
Last activity on 28 Dec 2022

I am using the ESP32 to interface the YF-S201 flowmeter sensor and send collected data over to Thingspeak server. The data is updated on serial monitor but the data is not reflected on ThingSpeak server. Could anyone please help me with how to send data of the YF-S201 sensor to Thingspeak server. I am attaching the code which I am presently using. I am not able to figure out what is wrong in the code and thereby would appreciate some help. #include <WiFi.h> #include <SPI.h> #include <Wire.h> String apiKey = ""; // Enter your Write API key from ThingSpeak const char *ssid = ""; // replace with your wifi ssid and wpa2 key const char *pass = ""; const char* server = "api.thingspeak.com"; #define LED_BUILTIN 16 #define SENSOR 4 long currentMillis = 0; long previousMillis = 0; int interval = 1000; boolean ledState = LOW; float calibrationFactor = 4.5; volatile byte pulseCount; byte pulse1Sec = 0; float flowRate; unsigned long flowMilliLitres; unsigned int totalMilliLitres; float flowLitres; float totalLitres; void IRAM_ATTR pulseCounter() { pulseCount++; } WiFiClient client; void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); pinMode(SENSOR, INPUT_PULLUP); pulseCount = 0; flowRate = 0.0; flowMilliLitres = 0; totalMilliLitres = 0; previousMillis = 0; attachInterrupt(digitalPinToInterrupt(SENSOR), pulseCounter, FALLING); } void loop() { currentMillis = millis(); if (currentMillis - previousMillis > interval) { pulse1Sec = pulseCount; pulseCount = 0; // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate = ((1000.0 / (millis() - previousMillis)) * pulse1Sec) / calibrationFactor; previousMillis = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres = (flowRate / 60) * 1000; flowLitres = (flowRate / 60); // Add the millilitres passed in this second to the cumulative total totalMilliLitres += flowMilliLitres; totalLitres += flowLitres; // Print the flow rate for this second in litres / minute Serial.print("Flow rate: "); Serial.print(float(flowRate)); // Print the integer part of the variable Serial.print("L/min"); Serial.print("\t"); // Print tab space // Print the cumulative total of litres flowed since starting Serial.print("Output Liquid Quantity: "); Serial.print(totalMilliLitres); Serial.print("mL / "); Serial.print(totalLitres); Serial.println("L"); } if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com { String postStr = apiKey; postStr += "&field1="; postStr += String(float(flowRate)); postStr += "&field2="; postStr += String(totalLitres); postStr += "\r\n\r\n"; client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); client.print("\n\n"); client.print(postStr); } client.stop(); }
Agustin Ontalba in MATLAB Answers
Last activity on 28 Dec 2022

Dear all. Thanks in advanced for reading this issue, and help if possible . The fact is that I have deleted BY MISTAKE all historical data. Does anyone if there is a backup file to recover my data before the deletion? Thanks again
Nurul Atikah Mazlan in MATLAB Answers
Last activity on 21 Dec 2022

I am currently working on a project where I did analysis on CNN architecture and I want to compare several types of CNN architecture that give the best performance of image classification. My result will be published to ThingSpeak by using data import in a .csv file. In my .csv file I want to add a new column called Network only just for a label. So that my x-axis will display type of CNN architecture without removing the timestamp. Is that possible?Please assist me on this question team. Please find an attachment for your reference on what I want my ThingSpeak graph to look like.Thank you!
Evmorfia Bataka in Discussions
Last activity on 20 Dec 2022

Hello! The fields sometimes will update most of the times but not always. The Serial monitor shows the following output when it does not update: while when it update it shows the following: There is no issue with the update rate since it is more than 15 seconds. Iam using a feather fona and the chunk of the code Iam using to send the data is the following: if (gprsSerial.available()) Serial.write(gprsSerial.read()); gprsSerial.println("AT"); delay(1000); gprsSerial.println("AT+CPIN?"); delay(1000); gprsSerial.println("AT+CREG?"); delay(1000); gprsSerial.println("AT+CGATT?"); delay(1000); gprsSerial.println("AT+CIPSHUT"); delay(1000); gprsSerial.println("AT+CIPSTATUS"); delay(2000); gprsSerial.println("AT+CIPMUX=0"); delay(2000); ShowSerialData(); gprsSerial.println("AT+CSTT=\"internet\"");//start task and setting the APN, delay(1000); ShowSerialData(); gprsSerial.println("AT+CIICR");//bring up wireless connection delay(3000); ShowSerialData(); gprsSerial.println("AT+CIFSR");//get local IP adress delay(2000); ShowSerialData(); gprsSerial.println("AT+CIPSPRT=0"); delay(3000); ShowSerialData(); gprsSerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection delay(6000); ShowSerialData(); gprsSerial.println("AT+CIPSEND");//begin send data to remote server delay(8000); ShowSerialData(); delay(4000); gprsSerial.println(str3);//begin send data to remote server delay(8000); ShowSerialData(); delay(6000); gprsSerial.println((char)26);//sending delay(6000);//waitting for reply, important! the time is base on the condition of internet gprsSerial.println(); ShowSerialData(); gprsSerial.println("AT+CIPSHUT");//close the connection delay(3000); ShowSerialData(); delay(3000); } Thank you in advance! Things Speak will sometimes not update the fields (Feather Fona) My guess is that your device is disconnecting before the server sends a response. Lookng at your code however, you have quite long delays built it. It may also be possible that your device is disconnecting while its waiting for you to do something. I would condsider using loops where you check the time (perhaps with millis()) and consider using yield instead of delay, or even reducing the delay slightly to give the device time to take action. (maybe 1 second instead of 6) Also, this comment makes me wonder if your connection is poor: delay(6000);//waitting for reply, important! the time is base on the condition of internet Thank you so much for your prompt reply! I increased the delays because of this issue. Originally, i used the following code: if (gprsSerial.available()) Serial.write(gprsSerial.read()); gprsSerial.println("AT"); delay(1000); gprsSerial.println("AT+CPIN?"); delay(1000); gprsSerial.println("AT+CREG?"); delay(1000); gprsSerial.println("AT+CGATT?"); delay(1000); gprsSerial.println("AT+CIPSHUT"); delay(1000); gprsSerial.println("AT+CIPSTATUS"); delay(2000); gprsSerial.println("AT+CIPMUX=0"); delay(2000); ShowSerialData(); gprsSerial.println("AT+CSTT=\"airtelgprs.com\"");//start task and setting the APN, delay(1000); ShowSerialData(); gprsSerial.println("AT+CIICR");//bring up wireless connection delay(3000); ShowSerialData(); gprsSerial.println("AT+CIFSR");//get local IP adress delay(2000); ShowSerialData(); gprsSerial.println("AT+CIPSPRT=0"); delay(3000); ShowSerialData(); gprsSerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection delay(6000); ShowSerialData(); gprsSerial.println("AT+CIPSEND");//begin send data to remote server delay(4000); ShowSerialData(); String str="GET https://api.thingspeak.com/update?api_key=xxxxxxxxxxxxxxxx&field1=" + String(t) +"&field2="+String(h); Serial.println(str); gprsSerial.println(str);//begin send data to remote server delay(4000); ShowSerialData(); gprsSerial.println((char)26);//sending delay(5000);//waitting for reply, important! the time is base on the condition of internet gprsSerial.println(); ShowSerialData(); gprsSerial.println("AT+CIPSHUT");//close the connection delay(100); ShowSerialData(); } void ShowSerialData() { while(gprsSerial.available()!=0) Serial.write(gprsSerial.read()); delay(5000); } which I found on this link: https://how2electronics.com/send-gsm-sim800-900-gprs-data-thingspeak-arduino/ Will use yield instead and see what happens. Thanks again! Can you try moving the device to improve the connection? I was kind of spitballing with yield, I confess I havent had much luck that way. Let us know though please. I think it is not a connection issue since the reception in this location is proven to be optimal. I used yield but when I searched about it I figured out it is applied mostly for esp8266. For a 32u4 feather I believe it will not work properly (but will try for sure). What I did now is to decrease the 6000 to 4000 seconds of delay. I will do some trial an error on fixing those delays and will share the progress. Once again, thank you so much! I havent seen any other examples for AT command set that use that much delay except when the connection is poor. Another thing you can try for waiting is startTime=millis(); //when the request starts while (millis()-startTime)<waitTime { //or while there is no response from the device delay(1); //also can check the serial output for data here } Hello! It has been 7 days since I used the new code and the performance is much better. As I posted above I decreased the delay but also changed the delay in the function ShowSerialData(); to millis() as you suggested. void ShowSerialData() { while(gprsSerial.available()!=0) Serial.write(gprsSerial.read()); int startTime=millis(); //when the request starts while (millis()-startTime<4000){ //or while there is no response from the device //delay(1); } } It only fails to update 1 out of 24 updates per day (much better than before) or sometimes it doesnt fail at all per day. So I am convinced now that the key is to replace the delay for sure. Maybe some modifications in the other delays too will give the optimal solution. Notice that I didnt use the delay(1) at all. I realized that it only "freezes" the system and probably this is why it fails. Thanks again for your valuable advices! Cheers! In the showSerialData method, you could check the response and then disconnect and complete the transaction only if the response is correct. Perhaps you could log the response to see what is happening when the post fails. Another thing you could try is to repost if the proper response isnt provided. You can have a look at the code in the write data example in the thingspeak arduino library to see how to test the response. I appreciate you updating the thread. Im glad to hear you made progress. fields update feather fona
Manfred Kreidl in MATLAB Answers
Last activity on 20 Dec 2022

Hi, In have tried to connect with a websocket client to mqtt.thingspeak.com on port 80. I have used the user I have created und the account profile settings and the "alert api key" als login password. Formely the client could connect to to the ThingsSpeak server and could publish values to channels successfully. This seems not to be possible anymore. Has there been a change to that?
George in Discussions
Last activity on 18 Dec 2022

Hi there, I am attempting to obtain a location history (thus the location of each of the previous messages recived) and the current location of my device on Thingspeak. I have not found any examples of how to do this on Thingspeak. Please may someone guide me or advise me on how to do this. Thank you Location history and current location mkr1200 arduino dht11 location sigfox
Zachariah Belding in Discussions
Last activity on 15 Dec 2022

When making a ThingHttp request via POST, the server response header does not include: "Content-Length:". Instead it is using "Transfer-Encoding: chunked". This makes it dificult to confirm that the entire response has been recieved. Any way to change this? 21:09:55.812 -> POST /apps/thinghttp/send_request HTTP/1.1 21:09:55.812 -> Host: api.thingspeak.com 21:09:55.812 -> Content-Type: application/x-www-form-urlencoded 21:09:55.812 -> Content-Length: 60 21:09:55.812 -> 21:09:55.812 -> headers=false&api_key=[removed]&message=Arduino Reset 21:09:55.906 -> 21:09:57.040 -> 21:09:57.040 -> 21:09:57.040 -> HTTP/1.1 200 OK 21:09:57.040 -> Date: Thu, 15 Dec 2022 02:09:57 GMT 21:09:57.040 -> Content-Type: text/html; charset=utf-8 21:09:57.040 -> Transfer-Encoding: chunked 21:09:57.040 -> Connection: keep-alive 21:09:57.040 -> Status: 200 OK 21:09:57.040 -> Cache-Control: max-age=0, private, must-revalidate 21:09:57.040 -> X-Request-Id: 798bbb62-da97-4ff8-a15b-c60b68fd60d3 21:09:57.040 -> ETag: W/"408e73c03e9c23fc2318c396c21c09e8" 21:09:57.040 -> 21:09:57.040 -> 2d 21:09:57.040 -> Congratulations! You've fired the alert event 21:09:57.040 -> 0 21:09:57.040 -> ThingHTTP server response header using "Transfer-Encoding: chunked" There is no control for the headers used in ThingHTTP, though you can ask ThingSpeak to reduce the headers sent to a device in some cases. I would guess that the client that is accepting the ThingHTTP request should be able to do the right HTTP thing. Are you writing a custom receiver/client? Does it run on a device? If you really needed to send length information, you can be able to calculate the length in a MATLAB analysis, and then use webread and webwrite to send the response to your device or whomever else is listening. You can control the headers explicitly in MATLAB. Thanks, yes this is a custom library written for an LTE Modem. As a more broad question, do you know why "Transfer-Encoding: chunked" is being used at all? This is usually only used for large amounts of data or for streaming. I have never seen it used for APIs. According to these two sources, "chunked" is be depreciated: https://everything.curl.dev/http/post/chunked "This assumes that you know you do this against an HTTP/1.1 server. Before 1.1, there was no chunked encoding, and after version 1.1 chunked encoding has been deprecated." https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding "Note: HTTP/2 disallows all uses of the Transfer-Encoding header" thinghttp transfer-encoding: chunked

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.