Ajay Kumar in MATLAB Answers
최근 활동: 2025년 5월 11일

Basically, I am getting temperature values and trying to send an email alert whenever the temperature exceeds a specific point. But however the code runs but yet I am facing an error that says Error using matlab.internal.webservices.HTTPConnector/copyContentToByteArray (line 373) The server returned the status 429 with message "Too Many Requests" in response to the request to URL https://api.thingspeak.com/alerts/send. Error in readContentFromWebService (line 46) byteArray = copyContentToByteArray(connection); Error in webwrite (line 139) [varargout{1:nargout}] = readContentFromWebService(connection, options); Error in Customer Temperature Email Trigger (line 10) webwrite(alertUrl , "body", alertBody, "subject", alertSubject, options); I am also attaching the code. channelID = 1614947; alertApiKey = 'PRIVATE_ALERT_API_KEY'; alertUrl="https://api.thingspeak.com/alerts/send"; options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey ]); temperature = thingSpeakRead(channelID,'NumDays',30,'Fields',1); recentvalue = temperature(end) alertSubject = sprintf("Temperature Alert"); alertBody = sprintf(" The temperature of the customer entering the store is high : ",recentvalue); if recentvalue > 32 webwrite(alertUrl , "body", alertBody, "subject", alertSubject, options); end Basically the other articles tell me that I have to enter a delay or a pause because the free version of thingspeak has limitations. Any idea on what I could do to make sure the code runs with minimal amount of delay?
Gilles Mangin-Voirin in MATLAB Answers
최근 활동: 2025년 3월 10일

Hello, I have been encountering several times a day for a few weeks an error when updating my data stored on Thingspeak (computerized hive parameters). The return code of my Arduinos is 211! But I can't find the meaning of this code anywhere... Does anyone know more? Here is one of my hives: https://thingspeak.mathworks.com/channels/1289244 Thanks PS: The update continues to be done but it seems to be missing points (those that return the error 211)
Mahesh Prasath in Discussions
최근 활동: 2025년 1월 11일

in the below code write is working fine, but read is failing ( 404 error) can you please help me reslove this. /* Go to thingspeak.com and create an account if you don't have one already. After logging in, click on the "New Channel" button to create a new channel for your data. This is where your data will be stored and displayed. Fill in the Name, Description, and other fields for your channel as desired, then click the "Save Channel" button. Take note of the "Write API Key" located in the "API keys" tab, this is the key you will use to send data to your channel. Replace the channelID from tab "Channel Settings" and privateKey with "Read API Keys" from "API Keys" tab. Replace the host variable with the thingspeak server hostname "api.thingspeak.com" Upload the sketch to your ESP32 board and make sure that the board is connected to the internet. The ESP32 should now send data to your Thingspeak channel at the intervals specified by the loop function. Go to the channel view page on thingspeak and check the "Field1" for the new incoming data. You can use the data visualization and analysis tools provided by Thingspeak to display and process your data in various ways. Please note, that Thingspeak accepts only integer values. You can later check the values at https://thingspeak.com/channels/2005329 Please note that this public channel can be accessed by anyone and it is possible that more people will write their values. */ #include <WiFi.h> const char *ssid = "xxxx"; // Change this to your WiFi SSID const char *password = "xxxxx"; // Change this to your WiFi password const char *host = "api.thingspeak.com"; // This should not be changed const int httpPort = 80; // This should not be changed const String channelID = "2805914"; // Change this to your channel ID const String writeApiKey = "xxxxxxxxxxxxxxxx"; // Change this to your Write API key const String readApiKey = "xxxxxxxxxxxxxxxx"; // Change this to your Read API key // The default example accepts one data filed named "field1" // For your own server you can ofcourse create more of them. int field1 = 20; //int field1 = 20; int numberOfResults = 1; // Number of results to be read int fieldNumber = 1; // Field number which will be read out void setup() { Serial.begin(115200); while (!Serial) { delay(100); } // We start by connecting to a WiFi network Serial.println(); Serial.println("******************************************************"); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void readResponse(NetworkClient *client) { unsigned long timeout = millis(); while (client->available() == 0) { if (millis() - timeout > 5000) { Serial.println(">>> Client Timeout !"); client->stop(); return; } } // Read all the lines of the reply from server and print them to Serial while (client->available()) { String line = client->readStringUntil('\r'); Serial.print(line); } Serial.printf("\nClosing connection\n\n"); } void loop() { NetworkClient client; String footer = String(" HTTP/1.1\r\n") + "Host: " + String(host) + "\r\n" + "Connection: close\r\n\r\n"; // WRITE -------------------------------------------------------------------------------------------- if (!client.connect(host, httpPort)) { return; } client.print("GET /update?api_key=" + writeApiKey + "&field1=" + field1 + footer); readResponse(&client); delay(200); // READ -------------------------------------------------------------------------------------------- String readRequest = "GET /channels/" + channelID + "/fields/" + fieldNumber + ".json?results=" + numberOfResults + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"; if (!client.connect(host, httpPort)) { return; } client.print(readRequest); readResponse(&client); // ------------------------------------------------------------------------------------------------- //++field1; delay(10000); } I am using example program WiFiClient, write is working fine, but read is giving error 404 A couple of comments: 404 is not found, so I would suggest a serial.println on this line so you can see what is actually getting sent. Then try it in your browser wndow you help you trouble shoot it. String readRequest = "GET /channels/" + channelID + "/fields/" + fieldNumber + ".json?results=" + numberOfResults + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"; it should look something like this: https://api.thingspeak.com/channels/2005329/field/1.json?results=4 I would suggest explicitly including the host address (api.thingspeak.com). You can also try to verify that you have the channel ID correct. We really reccomend you use the ThingSpeak library for arduino. It takes care of a lot of hard work for you. You can definitely send non integer values to thingspeak. The interfect trats everything as a string, but then the thingspeak plots will attempt to interprest numbes as integers or floats or what have you. API keys are kind of like passwords, so I have redacted them in your code above. Good luck on your project, please let us know if you get it working! Hi Chris, Thanks for your response, I got it sloved, readApikey was missing i added it as in the below and the code worked. String readRequest = "GET /channels/" + channelID + "/fields/" + fieldNumber + ".json?api_key=" + readApiKey + "&results=" + numberOfResults + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"; read 404 error
Torbjorn in Discussions
최근 활동: 2024년 11월 18일

Hello I have 3 devices (IOT board using SIM7600 module) sending one value to Thingsspeak. Have been working just fine a couple of years. However 14/11-24 I receive http error code 406 for all 3 devices. The http get is working just fine when testing directly in the browser (https://api.thingspeak.com/update?api_key=xxxxx&field1=33), the server return the entrie number. However, when running the same address via SIM7600 I receive - +HTTPACTION: 0,406,0 Any tips for the 406 error code? Http response error 406 internet says 406 is unaceptable. Perhaps you are making a header request that we dont do. Can you share anything more about the request format? Perhaps there was a security upgrade at our end that your request is not addressing? I believe this is most likely this is because invalid content-type header is being set. The browser automatically sets the header, but, your embedded firmware is setting the header manually and likely using an invalid header. The valid content-type headers are described here: https://www.mathworks.com/help/thingspeak/writedata.html First, I’d like to thank everyone who contributed their suggestions and insights—it’s much appreciated! Since last Thursday, HTTP GET requests from the SIM7600 module to ThingSpeak were returning a 406 error (+HTTPACTION: 0,406,0), indicating that the server found the request unacceptable. However, the same request worked fine in a browser. As suggested that the issue was related to the headers or format of the request being sent by the SIM7600. Actions Taken Debugging the SIM7600 HTTP Request: We used httpbin.org to analyze the actual HTTP headers and payload being sent by the SIM7600 module. It was observed that the User-Agent header was either missing or empty, and no Content-Type header was included. Modifying the HTTP Headers: We added a User-Agent header explicitly using: AT+HTTPPARA="UA","SIM7600_MODULE" This ensures the server recognizes the request as coming from a legitimate source. We added a Content-Type header (though typically required for POST requests, ThingSpeak now seems to enforce it for GET as well): AT+HTTPPARA="CONTENT","application/x-www-form-urlencoded" Validating the Solution: After adding the headers, the HTTP GET request to ThingSpeak worked as expected, and data updates were successful. Testing Workflow: The final working sequence for a GET request to ThingSpeak is as follows: AT+HTTPINIT AT+HTTPPARA="CID",1 AT+HTTPPARA="URL","http://api.thingspeak.com/update?api_key=YOUR_API_KEY&field1=10" AT+HTTPPARA="UA","SIM7600_MODULE" AT+HTTPPARA="CONTENT","application/x-www-form-urlencoded" AT+HTTPACTION=0 The response from AT+HTTPACTION now includes 200 (success), and the channel updates correctly. The issue was resolved by explicitly setting the User-Agent and Content-Type headers in the HTTP request. It seems ThingSpeak has recently implemented stricter validation of HTTP requests, requiring these headers to be present. Thaks so much for the explanation of your journey! Im happy to hear you were able to resolve the problem. Thank you for sharing the steps on your end. Indeed, a recent upgrade of the underlying framework did make the application more strict with respect to certain required headers. sim7600 error 406
Harshita in Discussions
최근 활동: 2023년 9월 6일

Hi! Actually I'm trying to store data from 5 sensors on the ThingSpeak cloud. I was able to do it 2-3 days back, but right now I'm trying to do the same for last 2-3 hours and it's just not happening. There's nothing wrong with the code because it's getting compiled properly. I'm using ThingSpeak.writeFields(2261556,"93S04OOU67USDX64"); I tried printing its value after storing in a temporary variable........The value comes out to be -301. Is there any fix for this? I need it urgently for a project. I hope to receive some help soon. Thanks! -301 error of ThingSpeak 301 error generally means connectivity. What kind of device do you have? I would try moving the device or try connecting to a different network. For troubleshooting, you can try updating from a web browser, with thins kind of commansd in the browser address bar. https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXXXXX&field1=123 Just make sure to replace XXXXXXXXXXXXXXXX with your write API key for the channel. Ive redacted yours above, jut to keep it safe. @Christopher Stapels Thanks for replying! I tried it through web it's working. However, I aim to collect the data from sensors, store it o ThingSpeak and then access it through a mobile application. So, I want a solution for the -301 error coming while connecting to ThingSpeak for writing the data. I'm using a Windows. Are you running the code on a desktop computer? If your PC is has an ethernet connection, you wont need to use the ThingSpeak device library. Please describe the experiment. What kind of sensors? Are they connected directly to the computer? Do you need to update data from the mibile device or just read it? What device/program/interface/computer ar you using this command on? ThingSpeak.writeFields(2261556,"xxxxxxxxxxxxxxxx"); Yes, I'm running the code on my Windows laptop. In the experiment I'm simply collecting data from DHT11, flame, rain, Soil Moisture and Passive Infrared sensors. These are in total 5 sensors. They are connected to a Node MCU. On the mobile app, I just need to read the data. I'm using the command on Arduino IDE installed on my Windows 11 laptop. I hope I answered all the questions. Can you suggest a way out please? OK Node MCU was the key I was looking for. Are you programming in Arduino IDE or some other program? Are you making a connection to the Wifi? Is the connection successful? If you're not sure, you can add a little more of the code you are using on the Node MCU. Are you using example code from the ThingSpeak library? Yes, I'm using Arduino IDE. I'm using my mobile hotspot for my laptop & NodeMCU. I have provided my code below. #include <SimpleDHT.h> #define DHT11_PIN D3 SimpleDHT11 dht11 (DHT11_PIN); #define flame_sensor D0 #define pir D5 #define rain_sensor D4 #define soil_sensor A0 #include <ESP8266WiFi.h> #include <ThingSpeak.h> WiFiClient client; long myChannelNumber = 2262440; const char myWriteAPIKey[] = "BCQMZ9ELD7W2O6CL"; void setup() { Serial.begin(9600); WiFi.begin("Redmi 9 Prime","hi"); while(WiFi.status() !=WL_CONNECTED){ delay(100); Serial.print("."); } Serial.println(); Serial.println("NodeMCU is Connected"); Serial.println(WiFi.localIP()); ThingSpeak.begin(client); pinMode(flame_sensor,INPUT); pinMode(pir,INPUT); pinMode(rain_sensor,INPUT); pinMode(soil_sensor,INPUT); } void loop() { //DHT11 byte temperature, humidity; int error = dht11.read (& temperature, & humidity, NULL); Serial.print ("DHT: Temperature:"); Serial.print ((int) temperature); Serial.println ("° C,"); Serial.print ("DHT: humidity:"); Serial.print ((int) humidity); Serial.println ("%"); //FLAME SENSOR int flame = digitalRead(flame_sensor); Serial.println(flame); //PIR SENSOR int state = digitalRead(pir); if (state) Serial.println("PIR: Motion detected!!"); else Serial.println("PIR: No motion detected..."); //RAIN SENSOR int rain = analogRead(rain_sensor); Serial.print("RAIN: "); Serial.println(rain); //SOIL MOISTURE SENSOR int moisture = ( 100.00 - ( (analogRead(soil_sensor)/1023.00) * 100.00 ) ); Serial.print("SOIL: "); Serial.println(moisture); Serial.println(); ThingSpeak.setField(1,(int)temperature); ThingSpeak.setField(2,(int)humidity); ThingSpeak.setField(3,flame); ThingSpeak.setField(4,state); ThingSpeak.setField(5,rain); ThingSpeak.setField(6,moisture); int i = ThingSpeak.writeFields(2262440,"BCQMZ9ELD7W2O6CL"); Serial.println(i); delay(2000); } Can you try a fixed WiFi network, that isnt the mobile hotspot? Ive suceeded before with an ESP device and a mobile hotspot, but -301 is generally a wifi strength issue, so that woul dbe the best troubleshooting for now. Another thing you can try is to put a little more delay after the wifi is connected before you set up the ThingSpeak client just to make sure everything is ready. perhaps after this line: Serial.println("NodeMCU is Connected"); add delay(3000); Thats a long shot though. The strength issue is most likely. thingspeak -301 error connection error
cog in MATLAB Answers
최근 활동: 2023년 8월 2일

I am attempting to bulk write some JSON data to a ThingSpeak channel using the API. An example payload is: % Payload is data = { 'write_api_key': <my_api_write_key>, 'updates': [ {'field5': 833.205, 'field4': 6, 'field3': 775.648, 'field2': 24.2523, 'delta_t': 1, 'field1': 59.1391}, {'field5': 833.199, 'field4': 6, 'field3': 771.03, 'field2': 24.2844, 'delta_t': 2, 'field1': 59.1331}, {'field5': 833.208, 'field4': 6, 'field3': 750.343, 'field2': 24.3008, 'delta_t': 3, 'field1': 59.1405}, {'field5': 833.208, 'field4': 7, 'field3': None, 'field2': 24.2903, 'delta_t': 5, 'field1': 59.1479}, {'field5': 833.216, 'field4': 7, 'field3': 748.45, 'field2': 24.2965, 'delta_t': 6, 'field1': 59.1686}, {'field5': 833.21, 'field4': 8, 'field3': None, 'field2': 24.2914, 'delta_t': 7, 'field1': 59.1756}, {'field5': 833.204, 'field4': 8, 'field3': 738.847, 'field2': 24.2867, 'delta_t': 8, 'field1': 59.1943}, {'field5': 833.208, 'field4': 8, 'field3': 732.472, 'field2': 24.2814, 'delta_t': 10, 'field1': 59.1964}, {'field5': 833.212, 'field4': 8, 'field3': None, 'field2': 24.2599, 'delta_t': 11, 'field1': 59.1971}, {'field5': 833.207, 'field4': 8, 'field3': 737.475, 'field2': 24.2658, 'delta_t': 12, 'field1': 59.2122}, {'field5': 833.212, 'field4': 8, 'field3': None, 'field2': 24.2498, 'delta_t': 14, 'field1': 59.2161}, {'field5': 833.209, 'field4': 7, 'field3': 749.432, 'field2': 24.2503, 'delta_t': 15, 'field1': 59.2298}, {'field5': 833.208, 'field4': 7, 'field3': 760.224, 'field2': 24.2396, 'delta_t': 16, 'field1': 59.2308} ] } I am sending this payload programatically, in Python, with the requests library using the following command: response = requests.post(url='https://api.thingspeak.com/channels/<my_channel_id>/bulk_update.json', ... data=json.dumps(data)) This results in the response below: % Response { "status": "401", "error": { "error_code":"error_auth_required", "message":"Authorization Required", "details":"Please provide proper authentication details." } } I am certain that the API write key and channel_id are correct. I have used both for single writes successfully. I am using a free ThingSpeak account. I have also tried adding headers to the requests.post() call to indicate explicitly that this is json data. I'm not sure why this is occuring and would sincerely appreciate any pointers.
Phil Gaudet in MATLAB Answers
최근 활동: 2022년 4월 11일

Using new Adafruit Huzzah breakout with Arduino IDE 1.8.10, TS library 1.5.0 on MacOS 10.15.1 . Board always connects to fixed IP address on my network. It never connects to ThingSpeak, throwing a -301 error code. This same board works fine as a webserver and gets network time without a problem using other custom code. I have tried the TS Wifi example with no luck and used the thermistor example to create this code. Had an existing account in TS and just added a new channel. The new channelID and write API key along with SSID and PW are in a separate file called Credentials.h (not shown here). Tried generating new write API key, no joy. /* * Monitor solar battery charger sending current, voltage, temperature * to Thingspeak * * Running on Adafruit ESP Hazzah breakout PID:2471 * Using FTDI Friend V1.0 PID:284 Jumpered for 5V power * * Board settings: * BOARD: Adafruit Feather HUZZAH ESP8266 * Flash Size: 4M (1M SPIFFS) * * ESP8266 Connections: * PIN VBATT - 6V BATTERY (+) (wht) WITH 1N4004 IN SERIES TO DROP SUPPLY BELOW 6V * PIN GND - BATT (-) (blk) * PIN 3V - INA219 VCC (red) * PIN GND - INA219 GND (blk) * PIN 5 SCL - I2C (grn) INA219(0x40) * PIN 4 SDA - I2C (yel) * * Loosely based on https://www.mathworks.com/help/thingspeak/read-and-post-temperature-data.html * * v2 11/18/19 pg * Add one-wire temp sensor * */ #include <ESP8266WiFi.h> #include <Wire.h> #include "ThingSpeak.h" #include "Credentials.h" #include <Adafruit_INA219.h> const uint8_t INA_ADDR = 0x40; Adafruit_INA219 ina219; bool INAConnected = false; float shuntvoltage = 0; float battvoltage = 0; float current_mA = 0; float loadvoltage = 0; float power_mW = 0; float batttemp = 0; unsigned int dataFieldOne = 1; // Field to write current data unsigned int dataFieldTwo = 2; // Field to write voltage data unsigned int dataFieldThree = 3; // Field to write temperature data WiFiClient client; uint32_t lastConnectionTime = 0; const unsigned long POSTING_INTERVAL = 20L * 1000L; // Post data every 20 seconds. /******************************************************/ void setup() { Serial.begin(115200); Serial.println(); // Initialize the INA219. // By default the initialization will use the largest range (32V, 2A). However // you can call a setCalibration function to change this range (see comments). ina219.begin(); // CHECK IF INA IS CONNECTED Wire.beginTransmission (INA_ADDR); if (Wire.endTransmission() == 0) { Serial.print (F("I2C device found at 0x")); Serial.println(INA_ADDR, HEX); INAConnected = true; } else Serial.println(F("******** NO INA219 *********")); Serial.printf("Connecting to %s ", ssid); WiFi.begin(ssid, pass); WiFi.config(ip, gateway, subnet); // Connect to WiFi network as fixed IP while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.print("\nConnected at IP:"); Serial.println( WiFi.localIP().toString().c_str()); ThingSpeak.begin(client); } // end setup /**********************************************************/ void loop() { // If interval time has passed since the last connection, send data to ThingSpeak. if (millis() - lastConnectionTime > POSTING_INTERVAL) { lastConnectionTime = millis(); if(INAConnected) { shuntvoltage = ina219.getShuntVoltage_mV(); loadvoltage = ina219.getBusVoltage_V(); current_mA = ina219.getCurrent_mA(); power_mW = ina219.getPower_mW(); battvoltage = loadvoltage + (shuntvoltage / 1000); batttemp = 0; Serial.println(""); Serial.print("Load Voltage: "); Serial.print(loadvoltage); Serial.println(" V"); Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV"); Serial.print("Batt Voltage: "); Serial.print(battvoltage); Serial.println(" V"); Serial.print("Current: "); Serial.print(current_mA); Serial.println(" mA"); Serial.print("Power: "); Serial.print(power_mW); Serial.println(" mW"); Serial.print("Bat Temp: "); Serial.print(batttemp); Serial.println(" degC"); } int httpCode = write2TSData(myChannelID,dataFieldOne, current_mA, dataFieldTwo, battvoltage, dataFieldThree, batttemp); if (httpCode == 200) { Serial.println("Channel write successful."); } else { Serial.println("Problem writing to channel. HTTP error code " + String(httpCode)); } } // end of interval timer } // end loop /******************************************************************************************** * Read data from a single field on a channel with readTSData. You can write a single value * to ThingSpeak using writeTSData and write multiple values simultaneously with write2TSdata. */ float readTSData( long TSChannel,unsigned int TSField ){ float data = ThingSpeak.readFloatField( TSChannel, TSField, myReadAPIKey ); Serial.println( " Data read from ThingSpeak: " + String( data, 9 ) ); return data; } // Use this function if you want to write a single field. int writeTSData( long TSChannel, unsigned int TSField, float data ){ int writeSuccess = ThingSpeak.writeField( TSChannel, TSField, data, myWriteAPIKey ); // Write the data to the channel if ( writeSuccess ){ Serial.println( String(data) + " written to Thingspeak." ); } return writeSuccess; } // Use this function if you want to write multiple fields simultaneously. int write2TSData( long TSChannel, unsigned int TSField1, float field1Data, unsigned int TSField2, long field2Data, unsigned int TSField3, long field3Data ){ ThingSpeak.setField( TSField1, field1Data ); ThingSpeak.setField( TSField2, field2Data ); ThingSpeak.setField( TSField3, field3Data ); int writeSuccess = ThingSpeak.writeFields( TSChannel, myWriteAPIKey ); return writeSuccess; }
David Evans in MATLAB Answers
최근 활동: 2022년 1월 17일

The following code runs on an Adafruit ESP32 Feather that connects to the internet via my ASUS RT-N66U router. The ESP32 is "remote" and is accessible only via wifi. It posts to ThingSpeak every 10 minutes and works fine for a day, sometimes a few days, but then it stops posting and returns error -301 ("failed to connect") with every attempt. It only starts posting again after a hard reboot. I suspected heap fragmentation, but free heap is constant at 247k (after an initial quick decline from 250k) and max allocatable heap is constant at 114k from the start. ESP32 hasn't lost wifi connectivity, since I can access the ESP32 via the router (and run the "server.on" commands). I also have an ESP8266 posting to ThingSpeak every five minutes and it has been online for months, so the problem probably isn't with the router or ISP. Even after the ESP32 stops posting, I can successfully manually post from a browser with https://api.thingspeak.com/update.json?api_key=xyz&field5=199, so it seems the problem is with the code. I'm running the latest ThingSpeak library, ESP library and core (but not developmental version), and Arduino IDE. Would appreciate suggestions on things to try or monitor. #include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #include <ArduinoOTA.h> #include <ESP_Mail_Client.h> #include <esp_int_wdt.h> // for hard reboot #include <esp_task_wdt.h>// ditto #include "ThingSpeak.h" // "always put this last in the list of includes" WebServer server(80); // OTA and server.on WiFiClient client; // TS only //**** definitions etc **** #define SMTP_HOST "smtp.gmail.com" #define SMTP_PORT 465 #define AUTHOR_EMAIL "xyz@gmail.com" #define AUTHOR_PASSWORD "abc" SMTPSession smtp; void smtpCallback(SMTP_Status status); ESP_Mail_Session session; SMTP_Message message; const char * myWriteAPIKey = "efg"; // TS const byte deltaDecreaseCM = 30; // threshold in cm... 12" = 30.48 cm const int distAvg = 1060; // average distance const unsigned long myChannelNumber = 123; // TS bool paused = false; bool savedPaused; bool intruder = false; bool alarmSounded = false; bool snowing = false; bool snowTriggeredOnce = false; bool distSaving = true; byte reqdNumBreaks = 6; byte lastTSalarmFlag; byte snowFactor = 1; byte savedSnowFactor; byte snowCount; byte saveDist[100]; byte saveIdx = 99; int distCurrent; int savedDistance; int lastTScode = 200; int wiFiFailsTS; unsigned long numIntruders; // can be very large if beam is blocked for a long time (eg. by parked car) unsigned long alarmTriggeredTime; unsigned long prevTSfailTime = 0; unsigned long startSnowingTime; unsigned long firstSnowTrigger; unsigned long pauseStartTime; unsigned long pauseDuration; //**** setup **** void setup() { Serial1.begin(115200); // TF03 default rate = 115200 WiFi.begin(); while (WiFi.waitForConnectResult() != WL_CONNECTED) { delay(5000); ESP.restart(); } setupMail(); server.on("/", handleRoot); server.on("/reboot", reBootMe); server.on("/postTS", doTSpost); server.on("/showTS", showTScode); server.onNotFound(handleNotFound); ArduinoOTA.begin(); server.begin(); ThingSpeak.begin(client); readTFxTimes(50); // clear serial1 buffer } //*************************************************************************************** //**** loop **** //*************************************************************************************** void loop() { ArduinoOTA.handle(); // this works even if posting to TS does not work server.handleClient(); // ditto unsigned long currTime = millis(); const unsigned long writeTSinterval = 600000UL; // post to TS every 10 min (and upon sounding alarm) static unsigned long prevTSwriteTime = 0; const unsigned long maxAlertInterval = 600000UL; // no duplicate alarms for 10 min after an alarm // reset pause flag if time is up if (paused && (currTime - pauseStartTime > pauseDuration)) { paused = false; } // reset alarm flag if time is up if (alarmSounded && (currTime - alarmTriggeredTime > maxAlertInterval)) { alarmSounded = false; } readTFxTimes(1); // read TF03 once every loop if (! paused && ! alarmSounded) { // chk for intruder, but only if not paused and not w/in 10 min of an alarm chkForIntruder(); if (intruder && (numIntruders == reqdNumBreaks * snowFactor)) soundAlarm(); // sound alarm if sufficient number of sequential brks } // post to thingSpeak if (prevTSfailTime) { // if an alarmFlag=1 write failed (posted too soon after an alarmFlag=0 post) if (currTime - prevTSfailTime > 20000UL) { // try again after 20 sec (15.1 sec didn't seem to work on 1/27 when there was a collision) prevTSfailTime = 0; prevTSwriteTime = currTime; writeThingSpeak(1, savedDistance, savedSnowFactor, savedPaused); //this will only do one re-try. If this fails again with -401 (for whatever reason) //it will just continue on with normal (alarmFlag=0) posts after 10 minutes. } } else if ((currTime - prevTSwriteTime > writeTSinterval) && (! intruder)) { prevTSwriteTime = currTime; writeThingSpeak(0, distCurrent, snowFactor, paused); // zero indicates no alarmFlag } } //*************************************************************************************** //**** writeThingSpeak **** //*************************************************************************************** void writeThingSpeak(byte alarmF, int distC, byte snowF, bool pausD) { if (WiFi.status() != WL_CONNECTED) { // should already be connected, but check again anyway wiFiFailsTS++; //this has never been > 1 while (WiFi.status() != WL_CONNECTED) { WiFi.begin(); delay(5000); } } int freeHeap = ESP.getFreeHeap(); int maxAllocatable = ESP.getMaxAllocHeap(); ThingSpeak.setField(1, distC); ThingSpeak.setField(2, alarmF); // 0 = no intruder; 1 = intruder; 4 = manual test post ThingSpeak.setField(3, snowF); // 1 = no snow; other = snowing ThingSpeak.setField(4, pausD); ThingSpeak.setField(5, lastTScode); ThingSpeak.setField(6, freeHeap); ThingSpeak.setField(7, maxAllocatable); ThingSpeak.setField(8, wiFiFailsTS); lastTScode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); readTFxTimes(50); // in case the above takes "a while". 100 = about one second of reads, so 50 is about half a second /* https://github.com/mathworks/thingspeak-arduino Return Codes Value Meaning 200 OK / Success 404 Incorrect API key (or invalid ThingSpeak server address) -101 Value is out of range or string is too long (> 255 characters) -201 Invalid field number specified -210 setField() was not called before writeFields() -301 Failed to connect to ThingSpeak <------------------------------- -302 Unexpected failure during write to ThingSpeak -303 Unable to parse response -304 Timeout waiting for server to respond -401 Point was not inserted (most probable cause is the rate limit of once every 15 seconds) 0 Other error */ } //**** chkForIntruder **** void chkForIntruder() { int deltaDist = distAvg - distCurrent; if (distSaving) { // not currently accessible (deleted the associated server.on) saveIdx = (saveIdx + 1) % 100; if (deltaDist < 0) { saveDist[saveIdx] = 0; } else { saveDist[saveIdx] = deltaDist; } } if (deltaDist > deltaDecreaseCM) { // if distance descreases more than the limit, then there's an intruder intruder = true; numIntruders++; // number of sequential breaks, actually } else { if (snowing) { if (millis() - startSnowingTime < 1800000UL) { if ((reqdNumBreaks / 2 < numIntruders) && (numIntruders < reqdNumBreaks)) snowCount++; } else { // time is up if (! snowCount) { // if snowCount == 0, reset flag and factor snowing = false; snowFactor = 1; } else { // snowCount was > 0, so need to keep checking... startSnowingTime = millis(); // reset time, so check again later snowCount = 0; // restart count for this new period } // end "else" (snow count > 0) } // end "else" (time is up) } else { // end "if snowing" if (snowTriggeredOnce) { if (millis() - firstSnowTrigger > 300000UL) { // triggered once, but time expired, so re-set flag snowTriggeredOnce = false; } else if ((reqdNumBreaks / 2 < numIntruders) && (numIntruders < reqdNumBreaks)) { // triggered once, time not expired, meets criteria...set snowing flag, etc. startSnowingTime = millis(); snowing = true; snowFactor = 4; snowTriggeredOnce = false; distSaving = false; } //end snowTriggeredOnce } else if ((reqdNumBreaks / 2 < numIntruders) && (numIntruders < reqdNumBreaks)) { // not triggered yet, but meets criteria, so set triggered once flag, etc. snowTriggeredOnce = true; firstSnowTrigger = millis(); } // end not triggered yet but meets criteria } // end "not snowing" intruder = false; numIntruders = 0; } // end "else" distance not decreased...so no intruder, and numIntruders reset to zero } //**** soundAlarm **** void soundAlarm() { alarmTriggeredTime = millis(); alarmSounded = true; sendMyMailNow(); //send an alert if (snowing && (startSnowingTime - alarmTriggeredTime < 5000)) { snowing = false; snowFactor = 1; } writeThingSpeak(1, distCurrent, snowFactor, paused); // 1 indicates intruder if (lastTScode == -401) { prevTSfailTime = millis(); savedDistance = distCurrent; savedSnowFactor = snowFactor; savedPaused = paused; } } //**** readTFxTimes **** void readTFxTimes(byte numOfReads) { for (byte i = 0; i < numOfReads; i++) { while (! readTF03once()) { //read until a number is obtained } } } //**** readTF03once **** bool readTF03once() { int check; // checksum byte uart[9]; // stores each byte of data returned by LiDAR (was int... I changed to byte) const byte HEADER = 0x59; // data package frame header...the letter "Y" in ASCII (was int... I changed to byte) if (Serial1.available()) { //check whether the serial port has data input if (Serial1.read() == HEADER) { // determine data package frame header = 0x59 uart[0] = HEADER; if (Serial1.read() == HEADER) { // determine data package frame header = 0x59 uart[1] = HEADER; for (byte i = 2; i < 9; i++) { // store rest of data to array uart[i] = Serial1.read(); } check = uart[0] + uart[1] + uart[2] + uart[3] + uart[4] + uart[5] + uart[6] + uart[7]; if (uart[8] == (check & 0xff)) { // check the received data as per protocols 0xff = 0b11111111 // Not sure why bitwise and (&) is used. distCurrent = uart[2] + uart[3] * 256; // calculate distance value return true; //got a reading } } } } distCurrent = 0; return false; //didn't get a reading } void handleRoot() { if (server.arg("pause") != "") { // i.e., if not zero, then user entered ...?pause=(a number) paused = true; pauseDuration = (unsigned long) server.arg("pause").toInt(); // in minutes pauseStartTime = millis(); if (pauseDuration <= 0) { // if neg, do nothing paused = false; } else if (pauseDuration > 1200) { // if large, limit to 1200 minutes = 20 hours pauseDuration = 1200UL; intruder = false; // so posting to TS continues during pause numIntruders = 0; } else { // otherwise, use received value intruder = false; // so posting to TS continues during pause numIntruders = 0; } pauseDuration *= 60000UL; // convert minutes to milliseconds server.send(200, "text/plain", "pausing"); } else { // not break or pause server.send(200, "text/plain", "ESP32 eye .151"); } } void reBootMe() { // run with /reboot // see e32hardReset in test_espB folder for basis of this server.send(200, "text/plain", "reboot in 2"); delay(2000); esp_task_wdt_init(1, true); esp_task_wdt_add(NULL); while (true); } void doTSpost() { // run with /postTS server.send(200, "text/plain", "posting a 2 to TS"); writeThingSpeak(2, distCurrent, snowFactor, paused); } void showTScode() { // run with /showTS char myCstr[15]; snprintf(myCstr, 15, "TScode=%d", lastTScode); server.send(200, "text/plain", myCstr); } void handleNotFound() { server.send(404, "text/plain", "404: Not found"); } void smtpCallback(SMTP_Status status) { Serial.println(status.info()); if (status.success()) { Serial.println("----------------"); Serial.printf("Message sent success: %d\n", status.completedCount()); Serial.printf("Message sent failled: %d\n", status.failedCount()); Serial.println("----------------\n"); struct tm dt; for (size_t i = 0; i < smtp.sendingResult.size(); i++) { SMTP_Result result = smtp.sendingResult.getItem(i); localtime_r(&result.timesstamp, &dt); Serial.printf("Message No: %d\n", i + 1); Serial.printf("Status: %s\n", result.completed ? "success" : "failed"); Serial.printf("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec); Serial.printf("Recipient: %s\n", result.recipients); Serial.printf("Subject: %s\n", result.subject); } Serial.println("----------------\n"); } } void setupMail() { smtp.debug(0); // 0 = none smtp.callback(smtpCallback); session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD; session.login.user_domain = "mydomain.net"; message.sender.name = "ESP Mail"; message.sender.email = AUTHOR_EMAIL; message.subject = "Test sending plain text Email"; message.addRecipient("Someone", "phoneNum@mms.cricketwireless.net"); message.text.content = "This is simple plain text message"; message.text.charSet = "us-ascii"; message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal; message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay; message.addHeader("Message-ID: <abcde.fghij@gmail.com>"); } void sendMyMailNow() { if (!smtp.connect(&session)) { Serial.println("failed to connec to smtp sesh"); return; } else if (!MailClient.sendMail(&smtp, &message)) { /* Start sending Email and close the session */ //Serial.println("Error sending Email, " + smtp.errorReason()); } }
Harvey Bernier in MATLAB Answers
최근 활동: 2021년 12월 4일

Hi, I'm new to this forum. I've setup a Thingspeak project to monitor the water level in a tank. The ESP32 microcontroler sends data to Thingspeak and it works great. I also wanted to get the data on my phone. I found the Thingshow app on the Google Play Store to retreive the data from my Thingspeak channel. The app can be easily configured to get the charts related to the 2 fields of my project on my phone. The app can also be configured to show gauges and other display features and that's what I want to see on my phone, current readings not charts. As requested by the app, I entered the channel project number, the read API key, the URL, the fields name to be red, etc. The gauges appeared on my phone but showing the above mentionned message "Field value unavailable". I also installed the IoT Thingspeak Monitor Widget which is configured the same way as the Thingshow app and it does display the 2 fields readings. But I would prefer to get the gauge display offered by Thingshow and use an app only when I wanted to look at the data, not a widget that is contineously poking the Thingspeak server. Does anybody out there uses Thingshow and ran in the same problem? If so a solution would be greatly appreciated. Thanks! Rv
Jonathan Baker in MATLAB Answers
최근 활동: 2021년 9월 7일

I am using an Arduino Uno R3 board and Ethernet shield. I replaced the Channel ID and the write API key with my own in the secrets.h file. It connects with DHCP ok. Arduino IDE 1.8.12 But comes back with error code -301. Serial Monitor: Initialize Ethernet with DHCP: DHCP assigned IP 10.10.1.170 Problem updating channel. HTTP error code -301 What am I missing? /* WriteMultipleFields Description: Writes values to fields 1,2,3 and 4 in a single ThingSpeak update every 20 seconds. Hardware: Arduino Ethernet !!! IMPORTANT - Modify the secrets.h file for this project with your network connection and ThingSpeak channel details. !!! Note: - Requires the Ethernet library ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize, and analyze live data streams in the cloud. Visit https://www.thingspeak.com to sign up for a free account and create a channel. Documentation for the ThingSpeak Communication Library for Arduino is in the README.md folder where the library was installed. See https://www.mathworks.com/help/thingspeak/index.html for the full ThingSpeak documentation. For licensing information, see the accompanying license file. Copyright 2018, The MathWorks, Inc. */ #include "ThingSpeak.h" #include <Ethernet.h> #include "secrets.h" byte mac[] = SECRET_MAC; // Set the static IP address to use if the DHCP fails to assign IPAddress ip(10, 10, 1, 76); IPAddress myDns(10, 10, 1, 1); EthernetClient client; unsigned long myChannelNumber = SECRET_CH_ID; const char * myWriteAPIKey = SECRET_WRITE_APIKEY; // Initialize our values int number1 = 0; int number2 = random(0,100); int number3 = random(0,100); int number4 = random(0,100); void setup() { Ethernet.init(10); // Most Arduino Ethernet hardware Serial.begin(115200); //Initialize serial // start the Ethernet connection: Serial.println("Initialize Ethernet with DHCP:"); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // Check for Ethernet hardware present if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); while (true) { delay(1); // do nothing, no point running without Ethernet hardware } } if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); } // try to congifure using IP address instead of DHCP: Ethernet.begin(mac, ip, myDns); } else { Serial.print(" DHCP assigned IP "); Serial.println(Ethernet.localIP()); } // give the Ethernet shield a second to initialize: delay(1000); ThingSpeak.begin(client); // Initialize ThingSpeak } void loop() { // set the fields with the values ThingSpeak.setField(1, number1); ThingSpeak.setField(2, number2); ThingSpeak.setField(3, number3); ThingSpeak.setField(4, number4); // write to the ThingSpeak channel int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); if(x == 200){ Serial.println("Channel update successful."); } else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); } // change the values number1++; if(number1 > 99){ number1 = 0; } number2 = random(0,100); number3 = random(0,100); number4 = random(0,100); delay(20000); // Wait 20 seconds to update the channel again
Sendhoran Manokaran in MATLAB Answers
최근 활동: 2021년 8월 16일

Hello. I am doing a Thingspeak project and I am having this issue that is printed out on only one of my MATLAB analyses which is: Error using matlab.internal.webservices.HTTPConnector/copyContentToByteArray (line 396) The server returned the status 429 with message "Too Many Requests" in response to the request to URL Error in readContentFromWebService (line 46) byteArray = copyContentToByteArray(connection); Error in webwrite (line 139) [varargout{1:nargout}] = readContentFromWebService(connection, options); Error in High humidity (line 8) result = webwrite(alert_url, jsonmessage, options); Can I know what this issue means? The rest of my analyses do not have an issue -- only one of them does.
Adam in MATLAB Answers
최근 활동: 2021년 5월 19일

I modified the WriteMultipleFields example to include a MAX31855 which measures the board temp and a K-type thermocouple. I seem to be getting the "Problem updating channel. HTTP error code -401" in my seriel monitor however it seems to updating my channel properly. I copied and pasted my API so I dont think there is a typo, especially since it updates the channel. Any ideas on how to fix this? or can it be left alone since it still works? Also, can you change the timezone in the visualization from GMT to a different zone? I updated my profile but that didn't do it I am using an Arduino Nano 33 IoT
Nathan Petrie in MATLAB Answers
최근 활동: 2020년 4월 17일

I have my ESP8266 connected to my Arduino Uno. (Through serial when not running code and through SoftwareSerial when running code) I have successfully updated a channel in ThingSpeak with both Arduino code and through the serial monitor. Now I want to use TalkBack. I started testing it using the serial monitor AT commands. However, it keeps giving me the following error (in json, in my code below, I get the text response because I don't specify a format): {"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}} I am sending the following commands: 1-------> AT+CIPSTART="TCP","api.thingspeak.com",80 Response: CONNECT OK 2-------> AT+CIPSEND=70 Response: OK 3-------> GET /talkbacks/<my_talkback_id>/commands/execute?api_key=<my_talkback_api_key> \r\n Response: Recv 70 bytes SEND OK +IPD,19:error_auth_requiredCLOSED That's when I get the above error (that's what the error looks like in json format). And yes, I am using the API key from the TalkBack page. In fact, I usually copy the GET line from my TalkBack's webpage. I use a character count website to get the size (68) then add two (to make 70) because of the NL and CR the serial monitor adds. This is how I did it for ThingSpeak and it works fine. Any help would be appreciated!
Marc Capafons Garcia in MATLAB Answers
최근 활동: 2020년 4월 13일

Hello! I am trying to create a 3d graph of these that have to be displayed and we got this error when I try to save and execute the matlab code ... I attach the error, the complete matlab code and the web from where the information was taken. Website of the information: https://es.mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/56910/versions/4/previews/html/ThingSpeakWeatherStation.html#2 Graph I want to create: Matlab code: % Channel ID to read data from readChannelID = 803557; % Specify date range dateRange = [datetime('March 7, 2016'),datetime('March 13, 2016')]; % Read data including the timestamp, and channel information. [data,time,channelInfo] = thingSpeakRead(readChannelID,'Fields',1:7,... 'DateRange',dateRange); % Create variables to store different sorts of data temperatureData = data(:,1); humidityData = data(:,2); pressureData = data(:,3); rainData = data(:,4); windSpeedData = data(:,5); windGustData = data(:,6); windDirectionData = data(:,7); % Create a day range vector dayRange = day(dateRange(1):dateRange(2)); % Pre-allocate matrix weatherData = zeros(length(dayRange),24); % Generate temperature 3D bar chart % Get temperature per whole clock for each day for m = 1:length(dayRange) % Loop over all days for n = 1:24 % Loop over 24 hours if any(day(time)==dayRange(m) & hour(time)==n); % Check if data exist for this specific time hourlyData = temperatureData((day(time)==dayRange(m) & hour(time)==n)); % Pull out the hourly temperature from the matrix weatherData(m,n) = hourlyData(1); % Assign the temperature at the time closest to the whole clock end end end % Plot figure h = bar3(datenum(dateRange(1):dateRange(2)), weatherData); for k = 1:length(h) % Change the face color for each bar h(k).CData = h(k).ZData; h(k).FaceColor = 'interp'; end title('Temperature Distribution') xlabel('Hour of Day') ylabel('Date') datetick('y','mmm dd') % Change the Y-Tick to display specified date format ax = gca; ax.XTick = 1:24; % Change the X-Tick to 24 hours ax.YTickLabelRotation = 30; % Rotate label for better display colorbar % Add a color bar to indicate the scaling of color % Generate humidity 3D bar chart % Get humidity per whole clock for each day for m = 1:length(dayRange) % Loop over all days for n = 1:24 % Loop over 24 hours if any(day(time)==dayRange(m) & hour(time)==n); % Check if data exist for this specific time hourlyData = humidityData((day(time)==dayRange(m) & hour(time)==n)); % Pull out the hourly humidity from the matrix weatherData(m,n) = hourlyData(1); % Assign the humidity at the time closest to the whole clock end end end % Plot figure h = bar3(datenum(dateRange(1):dateRange(2)), weatherData); for k = 1:length(h) % Change the face color for each bar h(k).CData = h(k).ZData; h(k).FaceColor = 'interp'; end title('Humidity Distribution') xlabel('Hour of Day') ylabel('Date') datetick('y','mmm dd') % Change the Y-Tick to display specified date format ax = gca; ax.XTick = 1:24; % Change the X-Tick to 24 hours ax.YTickLabelRotation = 30; % Rotate label for better display colorbar % Add a color bar to indicate the scaling of color Error we said: I would really appreciate your help. Thanks. Marc
JozsV in MATLAB Answers
최근 활동: 2020년 2월 23일

Hello! I'm using this simple code to send data to ThinkSpeak (ESP8266): GET /update?key=xxxxxxxxxxxxxxxx&field1=025.0 It's working fine, no problem. How can I send "sensor error" message to ThingSpeak? For example, the measured temeprature is out of range, unable to get temeprature data from the sensor etc. I would like to see errors in the graph, like in the attached picture. Is it possible? Thank you!
Clarry Christopherson in MATLAB Answers
최근 활동: 2020년 1월 29일

https://au.mathworks.com/help/thingspeak/write_things_network.html?s_tid=srchtitle on this page line 22 - "field 7: var7" forgot comma , "field7: var7,"
Marc Capafons Garcia in MATLAB Answers
최근 활동: 2020년 1월 15일

About two or three days ago when I accessed the web where the Iframes are embedded, some of them displayed a red "Field value unavailable" warning. This was not happening before and is not a problem with the data, because on the thingspeak website they are displayed without any problems. Also, when you leave the web open for a while, these warnings disappear, but whenever you load the web, they are displayed again.
Ari Rosti in MATLAB Answers
최근 활동: 2019년 12월 3일

Hi! I am uploading weather data to my ThingSpeak channels from couple of sources. Occasionally channel upload fails and the error message is then 429 Too many requests. Each time this has happened, previous request has been within 10-20 seconds. However, I have Home Licence and then message update interval limit is 1 second. So what is wrong?
Herberth Gracia in MATLAB Answers
최근 활동: 2019년 12월 3일

Hi MathWorks Community, I have a very strange problem and I hope you can help me. I have a code, this code does a simple lineal regression with the function FIT. This code works in my principal account (account 1) without problems or errors. This same code (copy - paste) does not work in other account (account 2). The only difference between both accounts is that the account 2 has a public channel. The error is this: 'fit' requires one of the following: Curve Fitting Toolbox Model-Based Calibration Toolbox Predictive Maintenance Toolbox Error in Correlation TvsH (line 32) fitObject = fit(temperatureData,humidityData,'poly1'); As I said before, I think this is a very strange error, because in the account 1, the code works perfectly, however in the account 2, it does not work... Somebody knows What can I do for solve this problem?, I need to use Matlab toolbox in account 2. Thanks for your attention, I hope you can help me.
CW in MATLAB Answers
최근 활동: 2019년 10월 21일

I've created a new channel with two fields, field1=temp, field2=humidity. I'm trying to do either a bulk_update.json and update both fields at once (with the intention of queing data and updating a few datapoints at once, or using update.json and updating both fields at once for the channel every so many seconds. I keep getting an error code returned in the JSON response, and the feeds never update. I also have tried pasting a URL for writing to one field and it returns "0". The fields in the channel never update. My account is said to be a Free account, and it says I have 3,000,000 messages remaining, but the response error I get tells me I've exceeded the message limit for the ThingSpeak license and I need to upgrade my acount??? Why is this happening when my account says I haven't written one data point yet. I'm trying to write every 20 seconds to avoid the 15 second limit for the free account. Trying to test this service to see if I may want to upgrade to a Home account...
Patrick Reid in MATLAB Answers
최근 활동: 2017년 4월 18일

% Channel ID to read data from readChannelID = 117***; % Temperature Field ID TemperatureFieldID = 3; % Channel Read API Key % If your channel is private, then enter the read API % Key between the '' below: readAPIKey = 'N7G********EMYID'; % TODO - Replace the [] with channel ID to write data to: writeChannelID = 182***; % TODO - Enter the Write API Key between the '' below: writeAPIKey = '5M8********5L2F'; %Temperature field to write to [tempC, timeStamp] = thingSpeakRead(readChannelID, 'Fields', TemperatureFieldID, 'numMinutes', 1440, 'ReadKey', readAPIKey); % Calculate the mimium temperature [minTempC, minTempIndex] = min(tempC); % Choose the timestamp at which the maximum temperature was measured timeMinTemp = timeStamp(minTempIndex); display(minTempC, 'Minimum Temperature for the last 24 hours is'); % Write the maximum temperature to another channel specified by the % 'writeChannelID' variable display(['Note: To successfully write data to another channel, ',... 'assign the write channel ID and API Key to ''writeChannelID'' and ',... '''writeAPIKey'' variables above. Also uncomment the line of code ',... 'containing ''thingSpeakWrite'' (remove ''%'' sign at the beginning of the line.)']) % Learn more about the THINGSPEAKWRITE function by going to the Documentation tab on % the right side pane of this page. thingSpeakWrite(writeChannelID, minTempC, 'timestamp', timeMinTemp, 'fields', 6, 'Writekey', writeAPIKey);

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.