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)
Armand in MATLAB Answers
上次活动时间: 2024-12-30

Hi, I've just tried to upload the example sketch ReadField with an Arduino R4, updating the library with WifiS3.h rather than Wifi.h. The network connection is OK. Unfortunately, I get an error code 0 in the Serial Monitor : "Problem reading channel. HTTP error code 0" I d'ont konw what is wrong here and how to fix it. I've read it could be result to the update rate, but the delay of the example seemes to be sufficient (15s).
Cécilia Facca in MATLAB Answers
上次活动时间: 2024-7-29

Hello :) This is my first big project using Arduino components, so I don't really understand everything, that's why I encounter so many difficulties. My goal is to send data from my ultrasonic sensor (HC-SR04) to Thingspeak using an Arduino UNO and a GSM SIM800c. Material : Arduino UNO ; GSM SIM 800c shield (https://www.eagle-robotics.com/accueil/257-shield-sim800c-arduino.html) ; Ultrasonic sensor (HC-SR04) ; Cables for my ultrasonic sensor ; Cable to connect my Arduino to my computer. I want to send data to Thinspeak from everywhere, so I can't use Wifi. I found a solution on google : https://github.com/707amitkumar/Send-Data-on-cloud-using-gsm-800c/blob/main/gsmangthingspeak.txt In order to send data to my channel on thingspeak, I did use the code mentionned on the link and I just changed the part concerning the data to send (because I want to send data from my ultrasonic sensor) : #include <SoftwareSerial.h> SoftwareSerial gprsSerial(7,8); #include <String.h> #include <HCSR04.h> const int trigPin = 2 ; const int echoPin = 3 ; UltraSonicDistanceSensor distanceSensor(trigPin, echoPin) ; void setup() { gprsSerial.begin(9600); // the GPRS baud rate Serial.begin(9600); // the GPRS baud rate delay(1000); } void loop() { float distance = distanceSensor.measureDistanceCm(); Serial.print("Distance = "); Serial.print(distance); Serial.println(" cm"); 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=\"tango.lu\"");//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=F2WFEAUL58M062LM&field1=0" + String(distance) ; 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); } When I run this code to my Arduino, I notice 2 problems : The piece of information is "sent" to my Thingspeak Channel but it doesn't match with the data sent from my sensors (It always show "0" on Thingspeak while the sensor sends a positive value : 2. I can notice that my code doesn't run as well as expected because the Serial Monitor dislay this : I really don't kow what to do... And I thank you in advance for any help you may give me. I hope my english is not so bad and you cand understand me :) I wish you a good day, Cécilia.
Andrés in MATLAB Answers
上次活动时间: 2024-5-14

Espero puedan ayudarme por favor, explico mi problema, en este momento estoy manejando una ESP32 mediante Arduino, que conectado con un sensor de movimiento, envíe notificaciones a Telegram y a su vez, necesito que envíe datos a ThingSpeak, he hecho todo lo posible, pero cuando va a enviar la información a ThingSpeak, aparece el error -301 en el monitor serial, dejaré el código para ver si me pueden ayudar, agradezco su ayuda. Quisiera clarar que no es problema de red ya que lo he intentado con diferentes redes locales, gracias. #include <WiFi.h> #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> #include <ArduinoJson.h> #include <ThingSpeak.h> const char* ssid = "******"; const char* password = "*******"; #define BOTtoken "*********" // Tu Bot Token (Obtener de Botfather) #define CHAT_ID "*******" unsigned long channelID = ********; const char * writeAPIKey = "*********"; WiFiClientSecure client; UniversalTelegramBot bot(BOTtoken, client); const int buzPin = 25; const int motionSensor = 27; bool motionDetected = false; // Indica cuando se detecta movimiento void IRAM_ATTR detectsMovement() { motionDetected = true; } void handleNewMessages(int numNewMessages) { for (int i=0; i<numNewMessages; i++) { String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID){ bot.sendMessage(chat_id, "Usuario No Autorizado", ""); continue; } String text = bot.messages[i].text; if (text == "/alarma_on") { bot.sendMessage(chat_id, "Alarma activada", ""); digitalWrite(buzPin, HIGH); } if (text == "/alarma_off") { bot.sendMessage(chat_id, "Alarma desactivada", ""); digitalWrite(buzPin, LOW); } } } void setup() { Serial.begin(115200); // PIR Motion Sensor mode INPUT_PULLUP pinMode(motionSensor, INPUT_PULLUP); pinMode(buzPin, OUTPUT); // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING); Serial.print("Connecting Wifi: "); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); delay(5000); Serial.println("Inicializando ThingSpeak..."); ThingSpeak.begin(client); Serial.println("ThingSpeak inicializado correctamente"); bot.sendMessage(CHAT_ID, "Bot iniciado", ""); } void loop() { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); while(numNewMessages) { handleNewMessages(numNewMessages); numNewMessages = bot.getUpdates(bot.last_message_received + 1); } if(motionDetected){ bot.sendMessage(CHAT_ID, "Movimiento detectado!!", ""); motionDetected = false; delay(5000); int writeResult = ThingSpeak.writeField(channelID, 1,1, writeAPIKey); if (writeResult == 200) { Serial.println("Datos enviados correctamente a ThingSpeak"); } else { Serial.print("Error al enviar datos a ThingSpeak. Código de error: "); Serial.println(writeResult); } } }
Mukhtar Hussain in MATLAB Answers
上次活动时间: 2024-4-25

I want to collect the AD8232 ECG sensor data through Arduino and ECG sensor AD8232 then, send that collected ECG data to IOT website ThingSpeak . Can somebody provide me with a proper Arduino code for sending the ECG sensor data to ThingSpeak website !
Chris Nas in MATLAB Answers
上次活动时间: 2024-4-19

Hey, I am currently programming something in ArduinoIDE for an ESP8266 to read my sensor data that is already uploaded to TS. For this, I use the function: ThingSpeak.readMultipleFields(CHANNELID,READKEY). Unfortunately, I found that the server no longer returns the correct data. Here some debug Log from the Arduino library right after caling ThingSpeak.readMultipleFields(CHANNELID,READKEY): ts::readRaw (channelNumber: 13xxxxx readAPIKey: H89OOxxYFXxxxxxx suffixURL: "/feeds/last.txt?status=true&location=true") Connect to default ThingSpeak: api.thingspeak.com:80...Success. GET "/channels/13xxxxx/feeds/last.txt?status=true&location=true" Got Status of 200 Content Length: 210 Found end of header Response: "{"created_at":"2021-04-06T20:25:06Z","entry_id":5,"field1":null,"field2":null,"field3":null,"field4":null,"field5":"27.82000","field6":"28.96680","latitude":null,"longitude":null,"elevation":null,"status":null}" Read: "{"created_at":"2021-04-06T20:25:06Z","entry_id":5,"field1":null,"field2":null,"field3":null,"field4":null,"field5":"27.82000","field6":"28.96680","latitude":null,"longitude":null,"elevation":null,"status":null}" disconnected. As you can see, field 4 returns "null". When reading the same Channel and field with the function: ThingSpeak.readFloatField(CHANNELID,FIELD ID,READKEY) I get: ts::readStringField(channelNumber: 13xxxxx readAPIKey: H89OOxxYFXxxxxxx field: 4) ts::readRaw (channelNumber: 13xxxxx readAPIKey: H89OOxxYFXxxxxxx suffixURL: "/fields/4/last") Connect to default ThingSpeak: api.thingspeak.com:80...Success. GET "/channels/13xxxxx/fields/4/last" Got Status of 200 Content Length: 8 Found end of header Response: "29.94141" Read: "29.94141" disconnected. And this is the right value. Im using the latest Version from TS arduino Library. I already opend an issue on Github but there is no reaction on it. https://github.com/mathworks/thingspeak-arduino/issues/80 Does anyone have any ideas? Greetings!
Shivam Sinha in MATLAB Answers
上次活动时间: 2024-3-12

I am making a project in arduino mega using ultrasonic sensor and some LEDs. I want to transfer the data collected by my ultrasonic distance sensor to thingspeak channel. Can some one please tell me how to do this?
Imrul Hasan in MATLAB Answers
上次活动时间: 2023-10-11

0. at command => AT Fail 0. at command => AT+CWMODE=1 Fail 0. at command => AT+CWJAP="knapsack","namespace" Fail 0. at command => AT+CIPMUX=1 Fail 0. at command => AT+CIPSTART=0,"TCP","api.thingspeak.com",80 #include <SoftwareSerial.h> #define RX 2 #define TX 3 //#define RX 19 //#define TX 18 String AP = "knapsack"; //AP NAME String PASS = "namespace"; //AP PASSWORD String API = "FNFJ7KDHJK4F3IU2"; //Write API KEY String HOST = "api.thingspeak.com"; String PORT = "80"; String field = "Random"; 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); // Replace with your own sensor code } 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; }
Hans Scharler in Discussions
上次活动时间: 2023-9-21

The ThingSpeak Communication Library for Arduino, ESP8266 and ESP32 enables an Arduino or other compatible hardware to write or read data to or from ThingSpeak, an open data platform for the Internet of Things with MATLAB analytics and visualization. Link: <https://github.com/mathworks/thingspeak-arduino> Installation: In the Arduino IDE, choose Sketch/Include Library/Manage Libraries. Click the ThingSpeak Library from the list, and click the Install button. Compatible Hardware: * Arduino/Genuino or compatible using a WiFi Shield * Arduino/Genuino or compatible using a WiFi Shield 101 (Use the WiFi101 library version 0.13.0 or older.) * Arduino/Genuino or compatible using an Ethernet Shield * Arduino/Genuino or compatible using a MKR ETH Shield * Arduino MKR1000 * Arduino MKR1010 * Arduino VIDOR 4000 * Arduino GSM 14000 * Arduino Uno WiFi Rev2 * Arduino Yún (Rev1 and Rev2) * ESP8266 programming directly (tested with SparkFun ESP8266 Thing - Dev Board and NodeMCU 1.0 module) * ESP8266 via AT commands * ESP32 (tested with SparkFun ESP32 Thing) Tutorial: <https://nothans.com/thingspeak-tutorials/arduino/send-data-to-thingspeak-with-arduino> ThingSpeak Communication Library for Arduino, ESP8266 and ESP32 Along with some performance improvements, the latest version of the library supports reading from multiple fields of a channel to your device with a single command. ThingSpeak.readMultipleFields(ChannelNumber); Mr Chris, How do i read a field value at a specific timestamp The Arduino library doesn't include the ability to read a particular timestamp. We've chosen a reduced number of features to keep the footprint smaller. The best way to achieve the result you are looking for is to use the REST API call for <https://www.mathworks.com/help/thingspeak/readdata.html Read Data> with the start and end parameters to get the date you are interested in. There is an example in the documentation that shows how to send a REST call but its a POST. You need a GET. Instead of these lines in that code: client.println( "POST /update HTTP/1.1" ); client.println( "Host: api.thingspeak.com" ); client.println( "Connection: close" ); client.println( "Content-Type: application/x-www-form-urlencoded" ); client.println( "Content-Length: " + String( postData.length() ) ); client.println(); client.println( postData ); Serial.println( postData ); Use something like this, changing the URL for your needs: url = 'https://api.thingspeak.com/channels/9/feeds.csv?start=2011-11-11%2010:10:10&end=2011-11-11%2011:11:11" client.println(String("GET ") + url); Thank you Chris. you are the best. Hello sir, Where should I move the secrets.h file such as the one for ESP32 https://github.com/mathworks/thingspeak-arduino/tree/master/examples/ESP32/WriteSingleField Already checked the instructions at https://www.arduino.cc/en/Guide/Libraries but I cannot find a method to add a bare .h -file (only .zip files). The secrets file should be located in then same directory as the .ino file. You can create a new file in the Arduino IDE using the plus button by the tabs near the top. hi i was ending data to my channel and then i dont know what happend my channel dosent recive any value plz if u could help me bc my project discussion next week ,if we could speak on e-mail or telegram i apriceat that Start a new question on MATLAB answers pelase. You can see the ask a question button if you scroll past the discussion section. Be sure to include your problem description, your hardware, what youve tried, what you observed, and perhaps even a small snippet of the code you think is causing the problem. I have done some basic testing of the ThingSpeak Communication Arduino library with the Raspberry Pi Pico W board using the Philhower Arduino-Pico implementation for Arduino {Arduino-Pico} and it appears to work correctly. However, there is one complaint generated when building code using the Thingspeak library and that is a warning as follows: WARNING: library ThingSpeak claims to run on avr, esp8266, sam, samd, esp32, samd_beta, megaavr architecture(s) and may be incompatible with your current board which runs on rp2040 architecture(s). To remove this warning, add 'rp2040' to the list of architectures in the "library.properties" file. Hi, I have Arduino UNO SMD, how could I connect it to THingSpeak ? which example should i use ?? Thank you You will need some way to connect the device to a network. Wi-Fi is probably the easiest and most versatile. There is a Wi-Fi adapter board for UNO or you can use an esp32 to connect the UNO to Wi-Fi. In this configuration, you use serial communication to send data from the UNO to the ESP. Since the ESP32 is about as powerful (or more) than the UNO, my preference is just to use the ESP32 directly and skip the UNO. arduino esp32 esp8266
Desmond Hanan in Discussions
上次活动时间: 2023-7-26

I was testing some sensors using code that I've run before successfully on an Arduino device to update to thingspeak, but I keep getting the http error code -302. if true % code #include <SPI.h> #include <WiFi101.h> #include <Wire.h> #include <secrets_new.h> #include <ThingSpeak.h> #include <SD.h> char ssid[] = SECRET_SSID; // your network SSID (name) WiFiClient client; unsigned long myChannelNumber = SECRET_CH_ID; const char * myWriteAPIKey = SECRET_WRITE_APIKEY; int soil_moisture_2cm = 0; int soil_moisture_5cm = 0; int soil_temperature_2cm = 0; int soil_temperature_5cm = 0; void setup() { // put your setup code here, to run once: WiFi.setPins(8,7,4,2); Wire.begin(); delay(1000); Serial.begin(9600); if (WiFi.status() == WL_NO_SHIELD) { Serial.println("Communication with WiFi module failed!"); // don't continue while (true); } String fv = WiFi.firmwareVersion(); if (fv != "1.0.0") { Serial.println("Please upgrade the firmware"); } ThingSpeak.begin(client); } void loop() { if(WiFi.status() != WL_CONNECTED){ Serial.print("Attempting to connect to SSID: "); Serial.println(SECRET_SSID); while(WiFi.status() != WL_CONNECTED){ WiFi.begin(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network Serial.print("."); delay(5000); } Serial.println("\nConnected."); } soil_moisture_2cm = analogRead(A0); soil_moisture_5cm = analogRead(A1); soil_temperature_2cm = analogRead(A2); soil_temperature_5cm = analogRead(A3); ThingSpeak.setField(1, soil_moisture_2cm); ThingSpeak.setField(2, soil_moisture_5cm); ThingSpeak.setField(3, soil_temperature_2cm); ThingSpeak.setField(4, soil_temperature_5cm); int y = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); if(y == 200){ Serial.println("Channel 2 update successful."); } else{ Serial.println("Problem updating channel 2. HTTP error code " + String(y)); } delay(30000); } end Can't update fields to thing speak Did you start experiencing this problem recently? Can you tell us more about the wifi shield you are using? We have recently upgraded our <https://www.mathworks.com/products/thingspeak/system-requirements.html system requirements> to require TLS 1.2. See the system requirements for additional details. Can you also try updating your channel in a browser address bar, just to make sure that works? Its a good basic step to limit out other problems. Many of the errors in the library have to do with connectivity. Can you restart your router and your Adruino device and try again? Hi Christopher, I am having similar problem my channel stopped recieving data from my devices starting from Dec 14th, before that it was working for years. I can update my channel through the browser though. Do you have information about the WiFi shield? Is it possible to upgrade its firmware? No idea, I use ESP8266 ESP12 module with WIFI embedded. It is from 6 years ago it worked as it is during this period. WOW thank god, I'm not the only one here!!! I've been struggling for more than a week now, banging my head for answers in hope for finding someone with the same problem as me! Yesss indeed the last msg I got from my sensors on the field was on the 13th of December. I tried everything I even opened a complaint ticket with my M2M GSM provider hoping the problem is from their end. On a separate test device, I managed to get the problem fixed by removing the SSL from the HTTP request I send from the GSM module (sim800L) then it worked fine ... I'm not that concerned about security since this is a research project for the University, however, I would really not prefer to drive all across Jordan (it's a big desert in case you don't know) to update the code on every device I have on the field. Please help us fix this!!! I was hesitant to open a new discussion regarding this topic but since I'm not the only one facing the problem ill open a new discussion and post a sample code thanks armen for sharing your experience, i hope changing the SSL works for you as well To be clear, Armen's code does not appear to be using WiFiClientSecure and HTTPS with SSL/TLS. This is unlikely to be related to any changes we made on ThingSpeak. Ghaith, can you share the code on your device? Is the SIM800L module doing the SSL/TLS handshakes? What versions of SSL/TLS do those modules support? Ahaa I didn't check armens code actually, but i was so happy to see someone with the same problem date as me. To give you a clear picture: Im using arduino pro mini with SIM800L and Im collecting weather data remotely using GPRS HTTPS posts to Thingspeak's API (writing bulk csv data). tens of these devices were functioning seamlessly for the past 3 years until the 14th of December, when they all went silent. This is a simple code that had been working before the 14th (or the release i read about <https://www.mathworks.com/matlabcentral/discussions/thingspeak/731230-is-the-thingspeak-site-updated-today/2418060#reply_2418060 here> ) #include <SoftwareSerial.h> SoftwareSerial mySerial(8, 7); // RX, TX Pins #define GSMswitch 9 // select the pin for the switch to turn the GSM on/off void setup() { pinMode(GSMswitch, OUTPUT); digitalWrite(GSMswitch, HIGH); Serial.begin(9600); Serial.println("Salamzzz"); mySerial.begin(9600); delay(8000); } void loop() { gsm_sendhttp(); } void gsm_sendhttp() { mySerial.println("AT"); delay(500); ShowResponse(); Serial.println(""); mySerial.println(F("AT+SAPBR=3,1,Contype,GPRS")); delay(100); ShowResponse(); Serial.println(""); mySerial.println(F("AT+SAPBR=3,1,APN,m2ms.orange.jo")); //change according to network - Umniah "mySerial.println(F("AT+SAPBR=3,1,APN,net"));" - Zain "mySerial.println(F("AT+SAPBR=3,1,APN,zain"));" delay(100); ShowResponse(); Serial.println(""); mySerial.println(F("AT+SAPBR =1,1")); delay(100); ShowResponse(); Serial.println(""); mySerial.println(F("AT+SAPBR=2,1")); delay(5000);//absolute minumum 1000ms ShowResponse(); Serial.println(""); // wdt_reset(); mySerial.println(F("AT+HTTPINIT")); delay(100); ShowResponse(); Serial.println(""); mySerial.println("AT+HTTPSSL=1"); delay(100); ShowResponse(); Serial.println(""); mySerial.println(F("AT+HTTPPARA=CID,1")); delay(100); ShowResponse(); Serial.println(""); mySerial.println(F("AT+HTTPPARA=URL,https://api.thingspeak.com/channels/******/bulk_update.csv")); //to change channel simply replace the 6-digit number between "channels/" and "/bulk_update.csv" delay(200); while(mySerial.available()>0){ Serial.write(mySerial.read());delay(1);} Serial.println(""); mySerial.println(F("AT+HTTPPARA=CONTENT,application/x-www-form-urlencoded")); delay(200); ShowResponse(); Serial.println(""); ShowResponse(); Serial.println(""); mySerial.println(F("AT+HTTPDATA=400,2000")); //absolute minumum 1000ms delay(200); ShowResponse(); Serial.println(""); mySerial.print(F("write_api_key=******************&time_format=relative&updates=1,1,2,3")); delay(2000); //absolute minumum 1000ms ShowResponse(); Serial.println(""); mySerial.println(F("AT+HTTPACTION=1")); delay(500); //absolute minumu 5000ms mySerial.println(F("AT+HTTPREAD")); delay(100); //absolute minumu 5000ms ShowResponse(); Serial.println(""); } void ShowResponse(){ while(mySerial.available()>0){ Serial.write(mySerial.read()); delay(20); } } for this same code to work again now i have to omit the AT+HTTPSSL=1 part and use HTTP instead of HTTPS I will check the Product Identification (ATI command) for the SIM800L modules I have, and check what firmware is installed then get back to you on that. I guess I should update the firmware. is that right? thanks Vinod Based on Google searches and the app note <https://www.simcom.com/product/SIM800.html here>, I think you need to add this AT command to enable TLS 1.2 on the SIM800 module: +SSLOPT=1,1. I believe you may also need to update the firmware on the SIM800L module so it can do HTTPS over TLS1.2. Earlier versions of TLS are vulnerable to attacks and are no longer supported when making secure connections to ThingSpeak. Hi @Christopher I tried restarting all of the devices including wifi router, no luck. Should I update firmware of my ESP8266? Here is my code sending and recieving data to Thingspeak: if true % code endbool sendDataToThingspeak(int fieldID, int workingTimeRemaining) { if(WiFi.status() == WL_CONNECTED) { // Use WiFiClient class to create TCP connections WiFiClientSecure client; if (!client.connect(host, httpsPort)) { SERIAL_PRINTLN("connection failed"); return false; } // We now create a URI for the request String url = "/update?api_key="; url += writeAPIKey; url += String("&field") + fieldID + "="; url += workingTimeRemaining; SERIAL_PRINT("Requesting URL: "); SERIAL_PRINTLN(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(1000); // 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_PRINTLN(); SERIAL_PRINTLN("closing connection"); return true; } return false; } bool getIntFromThingspeak(int fieldID, int & value) { if(WiFi.status() == WL_CONNECTED) { // Use WiFiClient class to create TCP connections WiFiClientSecure client; if (!client.connect(host, httpsPort)) { SERIAL_PRINTLN("connection failed"); return false; } // We now create a URI for the request String url = "/channels/79666/fields/"; url += fieldID; url += "/last.json?api_key="; url += readAPIKey; SERIAL_PRINT("Requesting URL: "); SERIAL_PRINTLN(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(100); value = 0; // Read all the lines of the reply from server and print them to Serial String findString = String("\"field") + fieldID + "\":\""; if(client.find(findString.c_str())) { String line = client.readStringUntil('\"'); value = line.toInt(); SERIAL_PRINT(line); } SERIAL_PRINTLN(); SERIAL_PRINTLN("closing connection"); return true; } return false; } Ditto Galiath, thanks for sharing. I am also glad to hear I am not the only one with the problem :). Was you able to solve the issue rather than removeing the SSL? Secure channel is not crucial in my case either. I am just curious to know whether there is a final solution for this. My code stnippet sending and recieveing data from Thingspeak is following: bool sendDataToThingspeak(int fieldID, int workingTimeRemaining) { if(WiFi.status() == WL_CONNECTED) { // Use WiFiClient class to create TCP connections WiFiClientSecure client; if (!client.connect(host, httpsPort)) { SERIAL_PRINTLN("connection failed"); return false; } // We now create a URI for the request String url = "/update?api_key="; url += writeAPIKey; url += String("&field") + fieldID + "="; url += workingTimeRemaining; SERIAL_PRINT("Requesting URL: "); SERIAL_PRINTLN(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(1000); // 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_PRINTLN(); SERIAL_PRINTLN("closing connection"); return true; } return false; } bool getIntFromThingspeak(int fieldID, int & value) { if(WiFi.status() == WL_CONNECTED) { // Use WiFiClient class to create TCP connections WiFiClientSecure client; if (!client.connect(host, httpsPort)) { SERIAL_PRINTLN("connection failed"); return false; } // We now create a URI for the request String url = "/channels/79666/fields/"; url += fieldID; url += "/last.json?api_key="; url += readAPIKey; SERIAL_PRINT("Requesting URL: "); SERIAL_PRINTLN(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(100); value = 0; // Read all the lines of the reply from server and print them to Serial String findString = String("\"field") + fieldID + "\":\""; if(client.find(findString.c_str())) { String line = client.readStringUntil('\"'); value = line.toInt(); SERIAL_PRINT(line); } SERIAL_PRINTLN(); SERIAL_PRINTLN("closing connection"); return true; } return false; } Yes, definitely upgrade the firmware when you can. Be sure you update the libraries and board files before programming as well. Since you appear to be writing directly from the ESP8266, you could probably benefit greatly from using the <https://github.com/mathworks/thingspeak-arduino ThingSpeak library> in your code as well. @Christopher I have updated the code to match to the latest Tingspeak examples. Please see the code below. Also Updated NodeMCU ESP8266 module with the latest firmware. I still get folloiwing error when it tries to read an integer filed: >>Problem reading channel. HTTP error code -301 I have also tried with a different WIFI device (My phone's hotspot), the same result. It can connect to the router but can't send/recieve data from Thingspeak. bool sendIntToThingspeak_T(int fieldID, int value) { if(WiFi.status() == WL_CONNECTED) { // Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different // pieces of information in a channel. Here, we write to field 1. int x = ThingSpeak.writeField(homeSweetHomeChannelNumber, fieldID, value, readAPIKey); if(x == 200) { Serial.println("Channel update successful."); } else Serial.println("Problem updating channel. HTTP error code " + String(x)); } return false; } bool getIntFromThingspeak_T(int fieldID, int & value) { if(WiFi.status() == WL_CONNECTED) { // Use WiFiClient class to create TCP connections float valueOut = ThingSpeak.readLongField(homeSweetHomeChannelNumber, fieldID, readAPIKey); // Check the status of the read operation to see if it was successful int statusCode = ThingSpeak.getLastReadStatus(); if(statusCode == 200) { value = valueOut; SERIAL_PRINTLN("VentBot remainting: " + String(valueOut)); return true; } else SERIAL_PRINTLN("Problem reading channel. HTTP error code " + String(statusCode)); } return false; } An update: it started to work normally when I changed WiFiClientSecure to WiFiClient. I think it is the same case as Ghaith also shared, there must be something changed/broken in the secure connection. I'd recommend using secure connections. See <https://www.mathworks.com/matlabcentral/discussions/thingspeak/733560-writing-to-field-with-ssl-https-443/2421920#reply_2421920 the instructable linked here> for what you need to do to update the firmware on your esp8266. I also meet the same question. Could you tell me how to change WiFiClientSecure to WiFiClient? Simply renaming declaration of WiFiClientSecure to WiFiClient will do the work, but I suggest to make the secure connection work if it is important for your application. @Vinod provided the instructions. arduino upload
Lorenzo Scavarda in Discussions
上次活动时间: 2023-7-24

Good morning, I am working on a smart garden project with an Arduino MKR WIFI 1010 and I am using Thingspeak as dashboard for monitoring some quantities (e.g. temperature, humidity, moisture, etc.). However, I would like to add a widget in order to change the state of my relay connected to the waterpump, for example if the variable "waterpump_state" is 0 turn off the pump, otherwise turning on. Do you think is it possible to implement it on Thingspeak? Among the predefined widget I have not found any useful in this sense. Thanks in advance, Lorenzo widget to control a Relay Totally possible. You can build the button in a private plugin, using the plugins app. Here is sample javascript. function loadXMLDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be performed when the document is ready: document.getElementById("demo").innerHTML = xhttp.responseText; } }; xhttp.open("GET", "https://api.thingspeak.com/update?api_key=Y0A92ZT5UMPKK3N1&field1=36&field2=255&field3=250&field4=254&field5=0&field6=3600&field7=0&field8=9", true); xhttp.send(); } function loadXMLDocOff() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be performed when the document is ready: document.getElementById("demo").innerHTML = xhttp.responseText; } }; xhttp.open("GET", "https://api.thingspeak.com/update?api_key=Y0A92ZT5UMPKK3N1&field1=0&field2=0&field3=0&field4=20&field5=0&field6=3600&field7=0&field8=9", true); xhttp.send(); } </script> with this very simple html section <html> <head> <!-- NOTE: This plugin will not be visible on public views of a channel. If you intend to make your channel public, consider using the MATLAB Visualization App to create your visualizations. --> </head> <body> <div id="demo"></div> <div id="button"><button type="button" onclick="loadXMLDoc()">Lights On</button> </div> <div id="offbutton"><button type="button" onclick="loadXMLDocOff()">Lights Off</button> </div> </body> </html> smart garden arduino waterpump
Roxy in MATLAB Answers
上次活动时间: 2023-5-7

I am trying to collect battery voltage data from arduino parts and upload it from arduino into my Thingspeak channel. So far, I have troubleshot the hardware/wiring aspect, and that doesn't seem to be the issue. At this point, I am assuming the issue is with the code or the Thingspeak channel. Since my arduino board (elegoo arduino Uno R3) is hooked up to my computer using a USB cord, I tried using an HTTP GET request in order to send the information to the Thingspeak channel. I am under a time crunch and am unable to access any kind of Wifi or Ethernet shield, so that is why I am using the USB cord. I could be completely wrong in using the HTTP GET request --I am quite the novice here! Here is the code so far: #include <SoftwareSerial.h> SoftwareSerial Serial1(2, 3); // RX, TX // Define variables float voltage; unsigned long previousMillis = 0; const long interval = 60000; // Upload interval (in milliseconds) String apiKey = "P5LPXSRJT0G4K7VA"; String field = "field1"; String server = "api.thingspeak.com"; String channelID = "2131761"; void setup() { Serial.begin(9600); Serial1.begin(9600); } void loop() { // Read voltage from sensor voltage = analogRead(A0) * 0.0049; // convert analog reading to voltage (0-5V) voltage = voltage * 5.17; // adjust the voltage to reflect the actual voltage // Print voltage to serial monitor Serial.print("Voltage: "); Serial.print(voltage); Serial.println(" V"); // Get current timestamp unsigned long currentMillis = millis(); // Check it's time to upload to ThingSpeak if (currentMillis - previousMillis >= interval) { // Update timestamp previousMillis = currentMillis; // Construct HTTP GET request String getRequest = "GET /update?api_key="; getRequest += apiKey; getRequest += "&"; getRequest += field; getRequest += "="; getRequest += String(voltage); getRequest += "&"; getRequest += "field2=Times"; getRequest += " HTTP/1.1\r\n"; getRequest += "Host: "; getRequest += server; getRequest += "\r\n"; getRequest += "Connection: close\r\n\r\n"; getRequest += "X-THINGSPEAK-CLIENT: arduino\r\n"; getRequest += "Content-Type: application/x-www-form-urlencoded\r\n"; getRequest += "Content-Length: "; getRequest += String(voltage); getRequest += "\r\n"; getRequest += "Host: api.thingspeak.com\r\n"; getRequest += "User-Agent: Arduino/1.0.0\r\n"; getRequest += "\r\n"; getRequest += "\r\n"; getRequest += channelID; // Send HTTP GET request to ThingSpeak via serial communication Serial1.println(getRequest); // Print response from ThingSpeak to serial monitor while (Serial1.available()) { Serial.write(Serial1.read()); } Serial.println(); } delay(1000); } Again, I really have no clue what I am doing here, so I am not surprised if what I have is entirely wrong. Any feedback is greatly appreciated!
Stuart in Discussions
上次活动时间: 2023-3-30

Hello, I am setting up a home energy monitoring system, all started from a blank sheet in arduino and its really working very well. I would like to send data to thinkspeak which is not time dependant, i.e. send the X and Y values and format as a bar graph. The reason is, i have 12 channels monitoring energy (Wh) and i have this in an array which i plot on a local LCD and throughout the day the bars grow in height as the usage attributed to that channel grows. How can i do something similar in thing speak which by default applies a time stamp to received data. Very simply, each channel has an ID (0-11) and a number associated with the accumulative Wh. I have a similar thing in excel for development where my serial port data is saved to a csv which excell imports every minute and updates a bar graph a bit like this; Ive had a good look (perhaps not good enough!) and i just cant see how this may be acheived with thingspeak without a clumbersome combination of 2 channels (given each channel has 8 fields) and then using a matlab visualisation to pull it all together. Perhaps its not has hard / messy as it sounds? I am paid user so can create extra channels if required. Thanks, Stuart Writing X & Y values for a bar graph, not time dependant Nice project! I think a MATLAB vis plus channels would not be too hard / messy (I have 100 of both). But there may be a simpler way. Is all the data in ThingSpeak now? Does the data you use to make the plot come from ThingSpeak? If so, then we can definitely do it with just a MATLAB vis (no extra channels required) As a paid user, you can set the MATLAB visualization plot to autoupdate as well.(though I think it is every 5 minutes that it will autorefresh) Alternatively, you could use one channel, and write the 12 values you want to the channel, and then set the plot to only show the last 12 entries. Set the type as bar or column. Then you get something like this, though the axis still shows time. If you wrote timestamps (created_at) with your values where the timestamps has the present time to the minute, but then were 1 second apart starting with 1 second then 2 seconds, etc, then the scale at the bottom would roughly have the label that you want. So I tried that, and you have to expand the plot to get the axis to do what you want, but it was fun to try. Here it is: I know its a big hack, so if you need help wiht the MATLAB code for a custom vis, let us know what format the data in in and we can give you some hints. Christoper, many thanks for your feedback, very usefull and informative! Ive not started to post the array to thingspeak, before i started i wanted to have a fair idea of how to do it. The data is sampled and processed in the Arduino (ESP8266) to provide a local display (via UDP on local LAN), aggregate total instantaneous power and aggregate total energy and the individual channel results. I build the arrays in the arduino so i can send them via UDP to the displays. Essentially i would like to replicate these online for live viewing and later analysis once i lean that. The latter one certainly makes sense to me, i can work through the array and post values, but im thinking, if i post a result to a channel say every second and show the 12 values on the chart the bars will build 0, 1, 2... 12, | 0, 1, 2...12... etc so as the data ripples along i would end up with, for example, channel 6, 7, 8, ... 0, 1, 2. This is one of my existing ThinkSpeak postings; if (enaElec == 1) // from the setup, are we sending this data { // Electricity values transmission ThingSpeak.setField(1, float(elecTimeLastp)); //time between pulses ThingSpeak.setField(2, elecPulseCount); // ThingSpeak.setField(3, elecElapsedkWh); // ThingSpeak.setField(4, elecPowerIn); // ThingSpeak.setField(5, elecPower); // ThingSpeak.setStatus(myElecStatus); // write to the ThingSpeak channel int elecx = ThingSpeak.writeFields(elecChannel, elecWriteAPIKey); if (elecx == 200) { Serial.println("Elec Channel update successful."); } else { Serial.println("Elec Problem updating channel; " + String(elecx)); } } It would be great if ThingSpeak could add into any future development plans the ability to write X & Y data eg: ThingSpeak.setField(n, x_val, y_val) where for me, n could simply be 1, x_val is 1-12 and y_val the data to plot? The data is all pretty simple, just decimal values. Or is that your thoughts of using created_at? it is used to define the X value and this could be stamped as 00:01:00 to 00:12:00 for example and just run through these same 12 time values as the created_at? ThingSpeak is at heart timestamped data. That is how the database is organized, so you have to use that dimension to store your data. I was trying to use the timestamps to provide something of an X axis so you would get the plot for free in ThingSpeak field charts. The right was to do it is really with MATLAB analysis or visualizations. You can aready write ThingSpeak.setField(1,x_val); ThingSpeak.setField(2,y_val); then these two points will be correlated in time and you can use that to plot them. So you can choose to write your data across 12 fields (which needs two cahnnes as you state above) or you can write it sequentially to the same field and use your knowlege that the data is modulo 12 to read it and product the plot. plotData=thingSpeakRead(mychannelID, 'numpoints',12); bar[plotData]; One other option would be to encode the data in a single field since there are 256 characters availalbe. myString=String(yval1)+ "_" + ...String(yval12) ThingSpeak.setField(1,myString) plotData=thingSpeakRead(mychannelID); plotData=str2double(strsplit(plotData,"_")); bar(plotData); You can see the MATLAB code is pretty simple (2-3 lines) and you can juice it up to make your plots look rally classy with custom labels. bar graph arduino x y data energy
Ctreb in MATLAB Answers
上次活动时间: 2023-2-12

Hello, I tried posting some values from my ESP8266 to thingspeak but it failed with an 401 error. To be sure that the error was not in my code I tred loading the example code "WriteMultipleFields" with no changes, created a new channel and renewed the API key mulitple times. This is the error message: Connected. ts::setField (field: 1 value: "0") ts::setField (field: 2 value: "3") ts::setField (field: 3 value: "31") ts::setField (field: 4 value: "88") ts::setStatus(status: field1 is less than field2") Connect to default ThingSpeak: api.thingspeak.com:80...Success. ts::writeFields (channelNumber: 964373 writeAPIKey: XXXXXXXXXXXXXXXX Got Status of 200 Content Length: 1 Found end of header Response: "0" Entry ID "0" (0) disconnected. Problem updating channel. HTTP error code -401 Any suggestions on what could be wrong?
University of the Incarnate Word in MATLAB Answers
上次活动时间: 2023-2-7

I have two seperate temperature sensors connected to arduino and I would like for them to read data on the same field in Thingspeak. For example, have one graph showing two lines on it in different colors, each representing one of the temperature sensor data. Is this possible? If so, how can it be done? Thank you
George in Discussions
上次活动时间: 2023-1-14

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
George in Discussions
上次活动时间: 2022-12-18

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
George in Discussions
上次活动时间: 2022-12-10

Hi there, I am trying to reach out to anyone who has successfully completed the project of building a weather station using an Arduino MKRFOX1200 board, a dht11 sensor across the Sigfox and Thingspeak networks. I’ve been attempting to build the weather station over the SigFox and things.io network for over a year now but I was unsuccessful. I then found this tutorial on how to build this using Thingspeak: https://create.arduino.cc/projecthub/masteruan/arduino-mkr-fox-1200-sigfox-meteo-station-423609 . I have now been attempting to build it using this network but am still unsuccessful. My SigFox and arduino is working. I made the arduino code convert temperature to Celsius (rather than Kelvin which is what the tutorial does). However, I am unable to access the location of the device on Thingspeak (my SigFox atlas is activated) and I am getting humidity values of approximately -30k. Please may someone assist me or give me a detailed approach on how to fix these issues. My goal is to have my thingspeak like this: https://thingspeak.com/channels/227248. I have followed the tutorial and projecthub but I cannot figure out why I am obtaining a confusing humidity reading. Please please may someone help. Thank you so much for your time. Weather station using dht11 sensor, Thingspeak and Sigfox This sounds like a hardware problem more than a ThingSpeak problem. You could try the projecthub if they have a forum or perhaps Arduino, though that is a stretch again since the problem seems to be with the sensor. I recomend drastic simplification. Write a program to read the sensor from your Arduino and output it to the serial monitor. Once you have that working, add another layer of complexity one at a time. Hi there, that makes sense, I will do that, thank you. However, I also wanted to know if you knew how to sned the location of the device per reading from Sigfox to Thingspeak (my Sigfox Atlas is enabled). I have found sources to do this with thethings.io but i am unsure on how to do it using thingspeak. When i try to do the "channel location" option on thingspeak, it gives me a default poaition og Lat.=0 and Long.=0. However, on my "device" tab on Sigfox, i can see a pretty accurate computed location of where my device is. How do I send this to Thingspeak? I am unsure on how to create a callback for this. Please may you assist if you can. Thank you The channel location is the base location of the device, such as your business or home. The device location parameters are in the channel feed data. See the Write data documentation for the parameters. https://api.thingspeak.com/update?api_key=xxxxxxxxxxxxxxxx&field1=10&lat=40.2&long=50.1&elevation=200 Here is code to create a map from that data. You can create a MATLAB visualization to run this code and add it to your channel. Note the change from the word alititude to elevation. I modified this code from a different application, so if you get errors please let me know so I can fix it. myChannel=999999999999999; ReadAPIKey='xxxxxxxxxxxxxxxx'; myData=thingSpeakRead(myChannel,'ReadKey', ReadAPIKey,'numpoints',260,'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; %ax=gca; %ax.ZoomLevel=15; %probably dont need this since scale is set above Thank you very much for this helpful response. Will this line of code (https://api.thingspeak.com/update?api_key=xxxxxxxxxxxxxxxx&field1=10&lat=40.2&long=50.1&elevation=200) be the Sigfox callback? Also, when running the MATLAB visualization code, i get the following error: "Channel ID must be a positive integer." . However, I do not see where my Channel ID is being used (nor where it could be a negative or not an integer). How could i ammend this? Or where is it reading my channel ID? Sorry, I've never used Sigfox, I probably should check it out. If you find out, please let us know. Regarding the error the channel ID is the first line in the code. The channel ID must exist. myChannel=999999999999999; Channel 999999999999999 does not exist. Change it to your channel ID. Also be sure to change the Read API key. So where would the line: "https://api.thingspeak.com/update?api_key=xxxxxxxxxxxxxxxx&field1=10&lat=40.2&long=50.1&elevation=200" be used? As previously I would have assumed it to be a SigFox callback And I see, thank you. I got this error: "Warning: 'Unable to read 260 points as requested. Only 68 points available in the channel. Error using . Unrecognized table variable name 'lat'." Where could I change the number of points? Would it affect the output? Also, where can i define the variable "lat"? sigfox thingspeak mkrfox1200 dht11 location arduino humidity weather station
MathWorks Internet of Things Team in MATLAB Answers
上次活动时间: 2022-11-26

I want to write information for controlling a device in my ThingSpeak channel, can I store the control parameters in ThingSpeak and read all of the paremeters at once back to the device? I'd like to be able to read multiple fields without having to make multiple calls to the ThingSpeak readfield command on my Arduino or esp32 or ESP8266. Is this possible?
farhan in MATLAB Answers
上次活动时间: 2022-11-19

function varargout = Program_Gui_Project(varargin) % PROGRAM_GUI_PROJECT MATLAB code for Program_Gui_Project.fig % PROGRAM_GUI_PROJECT, by itself, creates a new PROGRAM_GUI_PROJECT or raises the existing % singleton*. % % H = PROGRAM_GUI_PROJECT returns the handle to a new PROGRAM_GUI_PROJECT or the handle to % the existing singleton*. % % PROGRAM_GUI_PROJECT('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PROGRAM_GUI_PROJECT.M with the given input arguments. % % PROGRAM_GUI_PROJECT('Property','Value',...) creates a new PROGRAM_GUI_PROJECT or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Program_Gui_Project_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Program_Gui_Project_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Program_Gui_Project % Last Modified by GUIDE v2.5 18-Oct-2022 11:00:27 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Program_Gui_Project_OpeningFcn, ... 'gui_OutputFcn', @Program_Gui_Project_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Program_Gui_Project is made visible. function Program_Gui_Project_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Program_Gui_Project (see VARARGIN) % Choose default command line output for Program_Gui_Project handles.output = hObject; % Update handles structure guidata(hObject, handles); movegui(hObject,'center'); % UIWAIT makes Program_Gui_Project wait for user response (see UIRESUME) % uiwait(handles.figure1); clear all; global a; a = arduino('COM4','Uno'); configurePin(a,'D7','DigitalOutput'); configurePin(a,'D8','DigitalOutput'); % --- Outputs from this function are returned to the command line. function varargout = Program_Gui_Project_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % memanggil menu "browse file" [nama_file, nama_folder] = uigetfile('*.jpg'); %jika ada nama file yang dipilih maka akan mengeksekusi perintah di bawah %ini if ~isequal(nama_file,0) % membaca file citra rgb Img = imread(fullfile(nama_folder,nama_file)); % menampilkan citra rgb pada axes axes(handles.axes1) imshow(Img) title('Citra RGB') %menampilkan nama file pada edit text set(handles.edit1,'String',nama_file) %menyimpan variabel Img pada lokasi handles agar dapat dipanggil oleh %pushbutton yang lain handles.Img = Img; guidata(hObject, handles) else % jika tidak ada nama file yang dipilih maka akan kembali return end % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % memanggil variabel Img yg ada dilokasi handles Img = handles.Img; % melakukan konversi citra rgb menjadi citra grayscale Img_gray = rgb2gray(Img); %figure, imshow(Img_gray) % melakukan konversi citra grayscale menjadi citra biner bw = imbinarize(Img_gray); % figure, imshow(bw) % melakukan operasi komplemen bw = imcomplement(bw); % figure, imshow(bw) % melakukan operasi morfologi filling holes bw = imfill(bw,'holes'); %menampilkan citra biner pada axes axes(handles.axes2) imshow(bw) title('Citra Biner') %menyimpan variabel bw pada lokasi handles agar dapat dipanggil oleh %pushbutton yang lain handles.bw = bw; guidata(hObject, handles) % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % memanggil variabel Img dan bw yang ada di lokasi handles Img = handles.Img; bw = handles.bw; % ekstraksi ciri % melakukan konversi citra rgb menjadi citra hsv HSV = rgb2hsv(Img); % figure, imshow(HSV) % mengekstrak komponen h, s, dan v pada citra hsv H = HSV(:,:,1); %hue S = HSV(:,:,2); % Saturation V = HSV(:,:,3); % Value % menambah nilai pixel background menjadi nol H(~bw) = 0; S(~bw) = 0; % menghitung nilai rat2 h,s, danv Hue = sum(sum(H))/sum(sum(bw)); Saturation = sum(sum(S))/sum(sum(bw)); Value = sum(sum(V))/sum(sum(bw)); % menghitung luas objek Luas = sum(sum(bw)); % mengisi variabel ciri_latih dengan ciri hasil ekstraksi ciri_uji(1,1) = Hue; ciri_uji(1,2) = Saturation; ciri_uji(1,3) = Value; ciri_uji(1,4) = Luas; % menampilkan ciri hasil ekstraksi pada tabel ciri_tabel = cell(4,2); ciri_tabel{1,1} = 'Hue'; ciri_tabel{2,1} = 'Saturation'; ciri_tabel{3,1} = 'Value'; ciri_tabel{4,1} = 'Luas'; ciri_tabel{1,2} = num2str(Hue); ciri_tabel{2,2} = num2str(Saturation); ciri_tabel{3,2} = num2str(Value); ciri_tabel{4,2} = num2str(Luas); set(handles.uitable1,'Data',ciri_tabel,'RowName',1:4) %menyimpan variabel ciri_uji pada lokasi handles agar dapat dipanggil oleh %pushbutton yang lain handles.ciri_uji = ciri_uji; guidata(hObject, handles) % --- Executes on button press in pushbutton4. function pushbutton4_Callback(hObject, eventdata, handles) % hObject handle to pushbutton4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % memanggil ciri_uji yang ada di lokasi handles ciri_uji = handles.ciri_uji; % memanggil model naive bayes hasil pelatihan load Mdl % membaca kelas keluaran hasil pengujian hasil_uji = predict(Mdl,ciri_uji); % menampilkan kelas keluaran pengujian set(handles.edit2,'String',hasil_uji{1}) function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton5. function pushbutton5_Callback(hObject, eventdata, handles) % hObject handle to pushbutton5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % mereset tampilan GUI set(handles.edit1,'String',[]) set(handles.edit2,'String',[]) axes(handles.axes1) cla reset set(gca,'XTick',[]) set(gca,'YTick',[]) axes(handles.axes2) cla reset set(gca,'XTick',[]) set(gca,'YTick',[]) set(handles.uitable1,'Data',[],'RowName',{'' '' ''}) % --- Executes on button press in pushbutton6. function pushbutton6_Callback(hObject, eventdata, handles) global a; writeDigitalPin(a, 'D7', 1); writeDigitalPin(a, 'D8', 1); % hObject handle to pushbutton6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton7. function pushbutton7_Callback(hObject, eventdata, handles) global a; writeDigitalPin(a, 'D7', 0); writeDigitalPin(a, 'D8', 0); % hObject handle to pushbutton7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
Jun Hyuk Jeon in MATLAB Answers
上次活动时间: 2022-10-25

I apllied codes on Arduino and sends data regularly. In Serial Monitor there's no problem here. But ThingSpeak doesn't receive humid and CO2 data regularly. setting update value is 2 second, so It can recieve light and temperature data every 2 second. Only humidity and CO2 doesn't record every 2 second. I need help. Is there anything wrong? #if 0 #include <SoftwareSerial.h> SoftwareSerial esp8266(2, 3); //esp8266 시리얼 통신 설정 #define BAUDRATE 9600 #else #define esp8266 Serial3 //esp8266선을 RX,TX3으로 수정 #define BAUDRATE 9600 #endif #include <Wire.h> //BH1750 조도센서 라이브러리 포함 #include <BH1750FVI.h> #include <DHT.h> //DHT22 라이브러리 포함 // 핀 설정 및 센서 기본 변수 설정 #define DEBUG true //esp 설정 #define DHTPIN A0 //DHT22 온습도 센서 핀 설정 #define DHTTYPE DHT22 #define MG_PIN A1 //MG811 CO2센서 핀 설정 #define BOOL_PIN 2 #define DC_GAIN 8.5 #define READ_SAMPLE_INTERVAL 5 #define READ_SAMPLE_TIMES 5 #define ZERO_POINT_VOLTAGE 0.220 #define REACTION_VOLTAGE 0.030 //라이브러리별 설정 DHT dht(DHTPIN, DHTTYPE); BH1750FVI::eDeviceMode_t DEVICEMODE = BH1750FVI::k_DevModeContHighRes; BH1750FVI LightSensor(DEVICEMODE); //전역변수 설정 float hum; float temp; float CO2Curve[3] = {2.602, ZERO_POINT_VOLTAGE, (REACTION_VOLTAGE / (2.602 - 3))}; float volts; //String형태로 입출력 변수 설정 String AP = "bime0304_2.5G"; //Wifi설정 String PASS = "bime0304"; String WApiKey = "CU8634SH66Q1MLO9"; //ThingSpeak 내 Write API String RApiKey = "XMP6OYHXR8RYX55A"; //ThingSpeak 내 Read API String HOST = "api.thingspeak.com"; String PORT = "80"; String fieldTemp = "field1"; //Air Temperature 필드1 설정(최대 8) String fieldHum = "field2"; //Air humidity 필드2 설정 String fieldLight = "field3"; //Light Intensity 필드3 설정 String fieldCO2 = "field4"; //CO2 센서 필드 4 설정 int countTrueCommand; //ESP8266 커맨드 카운트 함수 int countTimeCommand; boolean found = false; int percentage; //CO2센서 전역변수 설정 //CO2 계산 함수 int MGGetPercentage(float volts, float * pcurve) //MGGetPercentage 변수 { if ((volts / DC_GAIN ) >= ZERO_POINT_VOLTAGE) { return -1; } else { return pow(10, ((volts / DC_GAIN) - pcurve[1]) / pcurve[2] + pcurve[0]); } } float MGRead(int mg_pin) //MGRead변수 { int i; float v = 0; for (i = 0; i < READ_SAMPLE_TIMES; i++) { v += analogRead(mg_pin); delay(READ_SAMPLE_INTERVAL); } v = (v / READ_SAMPLE_TIMES) * 5 / 1024 ; return v; } void setup() { unsigned int i = 0; // Open Serial1 communications and wait for port to open: // 시리얼 1 통신 시작 및 열릴때까지 대기 esp8266.begin(BAUDRATE); //ESP8266 보드레이트 설정 esp8266.setTimeout(5000); dht.begin(); //온습도 시작 LightSensor.begin(); //조도 센서 시작 Serial.begin(9600); //시리얼 통신 시작 pinMode(BOOL_PIN, INPUT); digitalWrite(BOOL_PIN, HIGH); Serial.println("Thingspeak with ESP-01"); //ESPWiFi 셋팅 sendCommand("AT", 5, "OK"); sendCommand("AT+CWMODE=1", 5, "OK"); sendCommand("AT+CWJAP=\"" + AP + "\",\"" + PASS + "\"", 20, "OK"); //IP획득 및 표시 sendCommand("AT+CIFSR", 2, "OK"); delay(2000); } //반복 조건 void loop() { hum = dht.readHumidity(); //습도 읽는 함수 temp = dht.readTemperature(); //온도 읽는 함수 uint16_t lux = LightSensor.GetLightIntensity(); //조도 읽는 함수 volts = MGRead(MG_PIN); percentage = MGGetPercentage(volts, CO2Curve); Serial.print("\n"); if (digitalRead(BOOL_PIN) ) { Serial.print( "HIGH " ); } else { Serial.print( "LOW " ); } //시리얼 표시 Serial.print("Humidity: "); Serial.print(hum, 1); //습도 소수점 첫째 표시 Serial.print(" %, Temp: "); Serial.print(temp, 1); //온도 소수점 첫째 표시 Serial.print(" Celsius, "); Serial.print(lux); //조도 표시 Serial.print(" lux "); Serial.print(volts); //CO2볼트 표시 Serial.print("V "); if (percentage == -1) { //CO2 값 표시 Serial.print( "<400" ); } else { Serial.print(percentage); } Serial.print( "ppm " ); if (digitalRead(BOOL_PIN)) //CO2 BoolPin 상태 보고 { Serial.println( "HIGH" ); } else { Serial.println( "LOW" ); } //Thing Speak 서버에 업로드 sendCommand("AT+CIPMUX=1", 5, "OK"); //온도 String getData1 = "GET /update?api_key=" + WApiKey + "&" + fieldTemp + "=" + String(temp); sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK"); sendCommand("AT+CIPSEND=0," + String(getData1.length() + 4), 4, ">"); esp8266.println(getData1); countTrueCommand++; sendCommand("AT+CIPCLOSE=0", 5, "OK"); //습도 String getData2 = "GET /update?api_key=" + WApiKey + "&" + fieldHum + "=" + String(hum); sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK"); sendCommand("AT+CIPSEND=0," + String(getData2.length() + 4), 4, ">"); esp8266.println(getData2); countTrueCommand++; sendCommand("AT+CIPCLOSE=0", 5, "OK"); //조도 String getData3 = "GET /update?api_key=" + WApiKey + "&" + fieldLight + "=" + String(lux); sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK"); sendCommand("AT+CIPSEND=0," + String(getData3.length() + 4), 4, ">"); esp8266.println(getData3); countTrueCommand++; sendCommand("AT+CIPCLOSE=0", 5, "OK"); //CO2 String getData4 = "GET /update?api_key=" + WApiKey + "&" + fieldCO2 + "=" + String(percentage); sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK"); sendCommand("AT+CIPSEND=0," + String(getData4.length() + 4), 4, ">"); esp8266.println(getData4); countTrueCommand++; sendCommand("AT+CIPCLOSE=0", 5, "OK"); delay(1000); //딜레이 1초 } // ESP 커맨드 입력 및 전송상태 수신 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; }
NAGUBATHULA SATYA SRIRAM in MATLAB Answers
上次活动时间: 2022-10-18

Is there any way so that i can send the alert messages from arduino and thingspeak to both mobilephone and email.
NAGUBATHULA SATYA SRIRAM in MATLAB Answers
上次活动时间: 2022-9-27

while uploading the values to thingspeak iam facinga n issue in updating it to thingspeak . Iam able to transmit other values but not the do value. iam attching the code and the issue is underlined in the code. please help me in communicating to thing speak. Except DO value rest all other values are able to transmit to channel. /* WriteMultipleFields Description: Writes values to fields 1,2,3,4 and status in a single ThingSpeak update every 20 seconds. Hardware: Arduino Uno WiFi Rev2 !!! IMPORTANT - Modify the secrets.h file for this project with your network connection and ThingSpeak channel details. !!! Note: - Requires WiFiNINA library. - This example is written for a network using WPA encryption. For WEP or WPA, change the WiFi.begin() call accordingly. 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 2020, The MathWorks, Inc. */ #include <WiFiNINA.h> #include "secrets.h" #include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros // the libraries of the ph sensor and varibles defined #include <Wire.h> float calibration_value = 21.34-5.5; int phval = 0; unsigned long int avgval; int buffer_arr[10],temp; // the libraries of tds sensor and varibles are declared here #include <EEPROM.h> #include "GravityTDS.h" #define TdsSensorPin A1 GravityTDS gravityTds; float temperature = 25,tdsValue = 0; //the libraries of dissolved oxygen meter are declared here #include <Arduino.h> #define DO_PIN A2 #define VREF 5000 //VREF (mv) #define ADC_RES 1024 //ADC Resolution //Single-point calibration Mode=0 //Two-point calibration Mode=1 #define TWO_POINT_CALIBRATION 0 #define READ_TEMP (25) //Current water temperature ℃, Or temperature sensor function //Single point calibration needs to be filled CAL1_V and CAL1_T #define CAL1_V (1731) //mv #define CAL1_T (25) //℃ //Two-point calibration needs to be filled CAL2_V and CAL2_T //CAL1 High temperature point, CAL2 Low temperature point #define CAL2_V (1300) //mv #define CAL2_T (15) //℃ const uint16_t DO_Table[41] = { 14460, 14220, 13820, 13440, 13090, 12740, 12420, 12110, 11810, 11530, 11260, 11010, 10770, 10530, 10300, 10080, 9860, 9660, 9460, 9270, 9080, 8900, 8730, 8570, 8410, 8250, 8110, 7960, 7820, 7690, 7560, 7430, 7300, 7180, 7070, 6950, 6840, 6730, 6630, 6530, 6410}; uint8_t Temperaturet; uint16_t ADC_Raw; uint16_t ADC_Voltage; uint16_t DO; uint16_t dissolved; int16_t readDO(uint32_t voltage_mv, uint8_t temperature_c) { #if TWO_POINT_CALIBRATION == 0 uint16_t V_saturation = (uint32_t)CAL1_V + (uint32_t)35 * temperature_c - (uint32_t)CAL1_T * 35; return (voltage_mv * DO_Table[temperature_c] / V_saturation); #else uint16_t V_saturation = (int16_t)((int8_t)temperature_c - CAL2_T) * ((uint16_t)CAL1_V - CAL2_V) / ((uint8_t)CAL1_T - CAL2_T) + CAL2_V; return (voltage_mv * DO_Table[temperature_c] / V_saturation); #endif } //wifi and api keys are declared here char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) WiFiClient 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); String myStatus = ""; void setup() { Serial.begin(9600); // Initialize serial gravityTds.setPin(TdsSensorPin); gravityTds.setAref(5.0); //reference voltage on ADC, default 5.0V on Arduino UNO gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC gravityTds.begin(); //initialization while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo native USB port only } // check for the WiFi module: if (WiFi.status() == WL_NO_MODULE) { Serial.println("Communication with WiFi module failed!"); // don't continue while (true); } String fv = WiFi.firmwareVersion(); if (fv != "1.0.0") { Serial.println("Please upgrade the firmware"); } ThingSpeak.begin(client); //Initialize ThingSpeak } void loop() { // Connect or reconnect to WiFi if(WiFi.status() != WL_CONNECTED){ Serial.print("Attempting to connect to SSID: "); Serial.println(SECRET_SSID); while(WiFi.status() != WL_CONNECTED){ WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network Serial.print("."); delay(5000); } Serial.println("\nConnected."); } // TDS sensor values starts from here gravityTds.setTemperature(temperature); // set the temperature and execute temperature compensation gravityTds.update(); //sample and calculate tdsValue = gravityTds.getTdsValue(); // then get the value Serial.print(tdsValue,0); Serial.println("ppm"); delay(1000); // ph meter values and code here for(int i=0;i<10;i++) { buffer_arr[i]=analogRead(A0); delay(30); } for(int i=0;i<9;i++) { for(int j=i+1;j<10;j++) { if(buffer_arr[i]>buffer_arr[j]) { temp=buffer_arr[i]; buffer_arr[i]=buffer_arr[j]; buffer_arr[j]=temp; } } } avgval=0; for(int i=2;i<8;i++) avgval+=buffer_arr[i]; float volt=(float)avgval*5.0/1024/6; float ph_act = -5.70 * volt + calibration_value; Serial.println(ph_act); delay(1000); // dissolved oxygen meter starts from here Temperaturet = (uint8_t)READ_TEMP; ADC_Raw = analogRead(DO_PIN); ADC_Voltage = uint32_t(VREF) * ADC_Raw / ADC_RES; Serial.print("Temperaturet:\t" + String(Temperaturet) + "\t"); Serial.print("ADC RAW:\t" + String(ADC_Raw) + "\t"); Serial.print("ADC Voltage:\t" + String(ADC_Voltage) + "\t"); Serial.println("DO:\t" + String(readDO(ADC_Voltage, Temperaturet)) + "\t"); delay(1000); // set the fields with the values ThingSpeak.setField(1, ph_act); ThingSpeak.setField(2, tdsValue); ThingSpeak.setField(3, float(DO)); ThingSpeak.setField(4, Temperaturet); // figure out the status message if(number1 > number2){ myStatus = String("field1 is greater than field2"); } else if(number1 < number2){ myStatus = String("field1 is less than field2"); } else{ myStatus = String("field1 equals field2"); } // set the status ThingSpeak.setStatus(myStatus); // 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(15000); // Wait 20 seconds to update the channel again }
Jakub R in MATLAB Answers
上次活动时间: 2022-9-18

Hello, I have a problem to write a bulk-update using csv format. I have some experience with thingspeak using JSON update method, but I need to change it because *csv format would be more RAM-saving method in case of bulk update (less characters = less memory needed). I was trying to change my code written for JSON method to csv according to instructions: https://www.mathworks.com/help/thingspeak/bulkwritecsvdata.html but my example-string csv_feed is not accepted by Thingspeak server. I don't have ideas where is the problem, I tried to comment "//" some non-necessery lines, because in API's example, those lines doesn't appears in code. Thingspeak response code is always the same: 401, meaning "authorization required". But I wrote in code "write_api_key" properly I think (I'm sure that API key and channel number is the same as it is in channel settings on Thingspeak page). The key is authentic, I don't have important data on this channel and I'll change the key after getting rid problems with that code. Without success, I've been changing csv_feed content with diffrent time format (I'd like to use EPOCH time), diffrent number of commas representing field values and I'm still stuck with that code. Could anybody show my mistake? Thank you in advance, Jakub char csv_feed[] = "write_api_key%3DxxxxxxxxxxxxxxxxC%26time_format%3Dabsolute%26updates%3D1662883022%2C20%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C"; String csv_lenght = String(strlen(csv_feed)+1); if(client.connect(server, 80)){ client.println("POST /channels/647137/bulk_update.csv HTTP/1.1"); client.println("Host: api.thingspeak.com"); //client.println("User-Agent: mw.doc.bulk-update (Arduino ESP8266)"); //client.println("Connection: close"); client.println("Content-Type: application/x-www-form-urlencoded"); client.println("time_format: absolute"); //client.println("write_api_key: xxxxxxxxxxxxxxxx"); client.println("Content-Length: "+csv_lenght); client.println(); client.println(csv_feed);
Raúl Moreno Sánchez in Discussions
上次活动时间: 2022-6-26

I work with an Arduino device. I have subscribed separately two thingspeak devices that works properly. Every device has a channel and I would like to publish on both channel using an only device. I have added the second channel to the first device(see image). Althougt this device can publish on both channel separately, I can't publish at the same time (after a few seconds, obviously). When I try to publish both of then, no one works. One devive, two channel to publish Can you try to reproduce this with a desktop client? MATLAB or MQTTX perhpas? Is there a wait time that will work at all (say 20 seconds)? I use MQTT. This is the first Channel This is the second one Separately, it works properly. I need to manage both channel in a only device. My understanding: If you program your device to publish to channel 1, it works. If you pogram the device to publish to channel 2 it works. If you program the device to publish to channel 1 then wait 3 seconds and publish to channel 2, it fails. What if you program to publish to channel1, wait 30 seconds, then publish to channel 2? Does this work? Or alternatively, what if you use MQTT x to publish to a channel via an MQTT device. Then you publish to another channel with that same device, manaully, after 3 seconds, then after 30 seconds. What do you see? Does it work? "wait 30 seconds, then publish to channel 2?" I doesn't work. Indeed, I wait 1 min between Channel 1 and Channel 2 data transfer to thingspeak system (allways via MQTT device) Maybe it's not possible to do that. But, why not? I just tried with MQTTx and was sucessful to publish to two different channels with the same device. Can you share the topic structure you are using? And please show the data you are sending. You can redact you channel number if you wish, but I wont be able to access it if it is private. I sent field1=10 to the topic channels/1285400/publish and the same data to channels/1381616/publish I found the reason why it doesn't work. A sensor is broken. Thanks for your replay. arduino device

关于 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.