Main Content

Results for

I'm new and I'm doing work for college and I'm having a hard time doing this part, I can send the data to thingspeak, but I don't know how to get for example the status of field 1 and check if it is 1 or 0 , I want to do this so that later using esp32 I can turn on a real led, could someone please help me

here is my code, i want to recive an email notification when my "alerta" field increase.

   % Read the soil moisture channel data from the past two weeks.
  % Send an email and tell the user to add water if the value
  % is in the lowest 10 %.
  % Store the channel ID for the moisture sensor channel.
  channelID = 1425554;
  % Provide the ThingSpeak alerts API key.  All alerts API keys start with TAK.
  alertApiKey = 'TXXXXXXXXXXXX';
  % Set the address for the HTTTP call
  alertUrl="https://api.thingspeak.com/alerts/send";
  % webwrite uses weboptions to add required headers.  Alerts needs a ThingSpeak-Alerts-API-Key header.
  options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey]);
  % Set the email subject.
  alertSubject = sprintf("Alertas");
  % Read the recent data.
  Alerta = thingSpeakRead(channelID,'NumDays',30,'Fields',8);
      % Get the most recent point in the array of moisture data.
      lastValue = Alerta(end); 
      % Set the outgoing message
      if (lastValue<=Alerta)
         alertBody='alerta de anomalia de fluxo de agua';    
      end
   % Catch errors so the MATLAB code does not disable a TimeControl if it fails
  try
      webwrite(alertUrl, "body", alertBody , "subject", alertSubject, options);
  catch someException
      fprintf("Failed to send alert: %s\n", someException.message);
  end

How much storage limit or maximal storage thingspeak? and how much size (byte) per fields?

Hi. I am a begginer.

I did a sample "Calculate high and low temperatures" with matlab analysis. I want to write data in a specified field in the new channel. I do not know how to do that. I already replace the empty spaces with channel ID and Api key. Then, when i try to set the field that i want to, it returns an error.

Is it right doing like I mention here:

thingSpeakWrite(writeChannelID,'Fields',[2],maxTempF,'timestamp',timeMaxTemp,'WriteKey',writeAPIKey);

Hello folks,

I have a fits file of size (300,300,3) and I would like to access to each channel, but I can't with this code. Any idea please.

stokes = fitsread('stokes1.fits');

Iu = stokes(:,:,1); Ip = stokes(:,:,2); Theta = stokes(:,:,3);

fitswrite([Iu,Ip,Theta],'stokes.fits')

I'm a newbie in Thingspeak. I have tried manytime to upload my code using the example from library to thingspeak but nothing be happened. I'm using Esp6266. Would you mind helping me?

if true
/*
WriteMultipleFields
Description: Writes values to fields 1,2,3,4 and status in a single ThingSpeak update every 20 seconds.
Hardware: ESP8266 based boards
!!! IMPORTANT - Modify the secrets.h file for this project with your network connection and ThingSpeak channel details. !!!
Note:
- Requires ESP8266WiFi library and ESP8622 board add-on. See https://github.com/esp8266/Arduino for details.
- Select the target hardware from the Tools->Board menu
- 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 ESP8266WiFi.h #include "secrets.h" #include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros #include Arduino.h #include "Adafruit_SHT31.h" Adafruit_SHT31 sht31 = Adafruit_SHT31();

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;

String myStatus = "";

void setup() { Serial.begin(115200); // Initialize serial while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo native USB port only }

WiFi.mode(WIFI_STA); 
ThingSpeak.begin(client);  // Initialize ThingSpeak

sht31.begin(0x44);

}

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
   WiFi.begin(); Serial.print(".");
    delay(5000);     
  } 
  Serial.println("\nConnected.");
}

//+++++++++++++++++++++++++++SHT31 Sensor float t = sht31.readTemperature(); float h= sht31.readHumidity();

if (! isnan(t)) {  // check if 'is not a number'
  Serial.print("Temp *C = ");
  Serial.print(t);
  Serial.print("\t\t");
} 
if (! isnan(h)) {  // check if 'is not a number'
  Serial.print("Hum. % = ");
  Serial.println(h);
}
// set the fields with the values
ThingSpeak.setField(1,t);
ThingSpeak.setField(2,h);
// 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));
}
delay(20000); // Wait 20 seconds to update the channel again
}
end

Does Thingspeak Has MQTT support? If yes please navigate.

R SRIRANJANI RAMAKRISHNAN is our current top ThingSpeak related downloads contributor. Check out the Raspberry Pi and ThingSpeak model downloaded by over 50 users! And Barnard Richards has 10 new posts on our community in the last month. Please reach out to us for a free MathWorks T-Shirt. You can find contact information on my profile page. Thank you for your contributions and your posts!

Are you using ESP32 and want to help us develop functionality for it? We are looking to add support for ESP32 boards in MATLAB. If you have experience with ESP32 and care to share your workflows with us, please let me know here and we will reach out to you for a short interview.

Could you help me know what problem is in this code? I'm trying to show one plot by App Designer. Without App Designer, below code is working to make a plot. Could you let me know how I could make a plot by using the attached file? Thank you!

   properties (Access = private)
        TimePoints 
        Raw_Data % Data for only case & death
        Case
        Death
    end
    methods (Access = private)
        function startupFcn(app)
load covid_data.mat data;
app.Raw_Data = cell2mat(covid_data(2:end,3:end));
Temp = covid_data(1,3:end);
app.TimePoints = datetime(Temp);
app.Case = sum(app.Raw_Data(:,1:2:end));
app.Death = sum(app.Raw_Data(:,2:2:end));
yyaxis(app.UIAxes,"left");
plot(app.UIAxes,app.TimePoints,app.Case);
yyaxis(app.UIAxes,"right");
plot(app.UIAxes,app.TimePoints,app.Death);
        end

I have seen this before and so i added some debug prints to my python script to make sure the posts to the channel were happening. See attached it looks like data stopped posting today at ~ 9:15am AZ time but actually the debug prints show [200] as it should, Posts happen every 1 minute. Am I posting too often or why is response always [200] but it does not render? Sometimes it will 'disappear' and then start showing up again hours later...(just did it actually) thanks

I don't understand what the -301 error means when trying to write a field to ThingSpeak. I checked my key and my write ID is OK ... The same program on another Arduino Mega and shield W5100 (but on another channel) works well ... Does anyone have any idea what the meaning of this error code is to know in which direction to look! Thank you

code :

void thingspeak(float t, float h, float units, int lum, int TempInt){

ThingSpeak.setField(1, t);								
ThingSpeak.setField(2, h);								
ThingSpeak.setField(3, units);							
ThingSpeak.setField(4, lum);								
ThingSpeak.setField(5,TempInt);							
ThingSpeak.setStatus("Update OK: ");					
    /* écriture des champs dans ThingSpeak */
  int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);			
if(x == 200){										
  Serial.println(F("Update of ThingSpeak ok."));				
              } 									
  else err(6,x);									// error handling
                                                   		   }        		// end of function thingspeak

How to read a JSON output of another device and put data into thingspeak channel:

Maybe useful for others: just figured out, how to parse a JSON, search for a special entry and enter searched value into thingspeak. For this I used the "Get data from webpage" template. An internet search resolved the access to the UBIBOT-json output at "https://api.ubibot.com/channels?account_key=XXX". This is used as "spcify URL". Having several devices a unique search keyword is needed and added in the template for the "specify target string".

So even if the template is not 100% for JSON abjects, this is a quick and dirty method to read it out and use it for further analysis.

Full code is this:

% TODO - Specify URL of the page to read data from
url = 'https://api.ubibot.com/channels?account_key=yyy';
% TODO - Specify the target string to search in webpage
targetString = 'last_values":"{\"field3\":{\"value\":';
% TODO - Replace the [] with channel ID to write data to:
writeChannelID = 666;
% TODO - Enter the Write API Key between the '' below:
writeAPIKey = 'yxc';
%% Scrape the webpage %%
data = urlfilter(url, targetString);
%% Analyze Data %%
analyzedData = data;
%% Write Data %%
thingSpeakWrite(writeChannelID, analyzedData, 'WriteKey', writeAPIKey);

I want to use a microcontroller and esp8266 to control the relay and home appliance. For example, my water pump needs to be "ON" from 6 am to 10 pm and "OFF" from 10 pm to the next day at 6 am. In this case, I want the thingspeak channel's field to auto-update "1" at 6 am and auto-update "0" at 10 pm. I wonder if there a possibility. If it can be achieved, my esp can receive the latest data to control the relay and appliance.

Currently i am able to send the 2 decimal data to thingspeak field. But i stuck on how to write 3 decimal places data to that field. Hope u guys can help.Here is my coding. #include PubSubClient.h // library used to publish the data through mqtt broker #include WiFiEsp.h // library for ESP8266 wifi #include EEPROM.h // library that GravityTds use #include GravityTDS.h // library that GravityTds use #include OneWire.h // Include the libraries for temperature #include DallasTemperature.h // Include the libraries for temperature #include SoftwareSerial.h // library for software serial to display output on the serial monitor

#define TdsSensorPin A1 // set TdsSensorPin at pin A1 #define temperaturePin 2 // temperature sensor is connected into pin 2 on the Arduino

OneWire oneWire(temperaturePin); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) DallasTemperature tempsensor(&oneWire); // Pass our oneWire reference to Dallas Temperature. GravityTDS gravityTds; // define the gravityTds SoftwareSerial Esp8266(5, 6); // Rx, Tx set communication pin for esp8266 to uno WiFiEspClient Esp8266wifi; // set the esp8266 for the mqtt broker connnection PubSubClient client(Esp8266wifi); // set the esp8266 for the mqtt broker connnection

unsigned long previousMillis1 = 0; // used to delay without delay the system for sensor data unsigned long previousMillis2 = 0; // used to delay without delay the system for the send data to thingspeak float temperature; // variable to store temperature value int tdsValue; // variable to store tds value float EC; // variable to store EC value

char ssid[] = ""; // your network SSID (name) char pass[] = ""; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status String clientName="ESP-Thingspeak";

//char* topic="channels/<channelID/publish/<channelAPI> char* topic = "channels/1244171/publish/FOZYSFXXS4P6DE5N"; // topic to be published to the thingspeak with channel id and api code char* mqtt_server = "mqtt.thingspeak.com"; // set the server for the mqtt of thingspeak

void setup()

{

    Serial.begin(9600);                   // 9600 is the baud rate for the data to display to the serial monitor
    Esp8266.begin(9600);                  //9600 is the baud rate for the srial data connection of esp8266
    WiFi.init(&Esp8266);
    client.setServer(mqtt_server, 1883);  // set mqtt broker server and port
    tempsensor.begin();                   // begin temperature sensor library
    gravityTds.setPin(TdsSensorPin);      // set pin tds at declared variable 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                // arduino uno adc level  is a 10-bit ADC   
    gravityTds.begin();                   //initialization
    InitWiFi();   //call function to intialize wifi
Serial.print("Connecting to ");               // display on serial monitor
Serial.print(mqtt_server);
Serial.print(" as ");
Serial.println(clientName);
if (client.connect((char*) clientName.c_str()))                   // connect to the thingspeak with the client name
{
  Serial.println("Connected to MQTT broker");
    if (client.publish(topic, "Test send data"))                   // Test send data to the thingspeak
    {
      Serial.println("Testing send data succes");
    }
    else {
      Serial.println("Testing send data failed");
    }
  }
  else {
    Serial.println("MQTT connect failed");
    Serial.println("Will reset and try again...");
    abort();
  }
}
//this function is only for the initialization of the esp8266 to connect to the network & mqtt  and  initialize the sensor 

void loop(){ unsigned long currentMillis = millis(); //timer start

checkconnection();                             // calling function to check the connection
if (currentMillis - previousMillis1 >= 2000)  //delay without causing system delay
{
    previousMillis1 = currentMillis;       
    sensordata();                               // calling fucntion of the sensor data  
  }
if (currentMillis - previousMillis2 >= 2000) //delay without causing system delay
{
    previousMillis2 = currentMillis;       
senddata();                                   // calling fucntion to send data         // send one set of data in 2 seconds
}

}

void sensordata() { tempsensor.requestTemperatures(); // get temperatures temperature = tempsensor.getTempCByIndex(0); // set variable to the temperature sensor output gravityTds.setTemperature(temperature); // set the temperature and execute temperature compensation gravityTds.update(); //sample and calculate tdsValue = gravityTds.getTdsValue(); // then get the value of TDS EC = gravityTds.getEcValue()/1000; // get EC value Serial.println(temperature); // display sent data Serial.println(tdsValue); Serial.println(EC,3); Serial.println("Data Sent"); }

void senddata() {

String payload="field1=";     // payload to send to thingspeak using mqtt broker
payload+=temperature;         // field1=temperature&field2=tdsValue&field3=EC&status=MQTTPUBLISH
payload+="&field2=";          //// field1=26.9&field2=120&field3=0.2&status=MQTTPUBLISH
payload+=tdsValue;
payload+="&field3=";          //// field1=26.9&field2=120&field3=0.2&status=MQTTPUBLISH
payload+=EC,3;
payload+="&status=MQTTPUBLISH";
if (client.connected())         // if client connected
{
  Serial.println("Sending data ");
    if (client.publish(topic, (char*) payload.c_str()))   // send data to the thingspeak, topic (the channel id and channel api) -- payload is the data from sensor that will be sent to the thingspeak
    {
      Serial.println(temperature);                          // display sent data
      Serial.println(tdsValue);      
      Serial.println(EC,3);      
      Serial.println("Data Sent");
    }
    else 
    {
      Serial.println("Publish failed");
    }
}
}

void checkconnection() /// check connection if disconnected try to reconnect wifi and mqtt broker {

   if  ( status != WL_CONNECTED)
 Serial.println("Wifi Disconnected");
 {
  while ( status != WL_CONNECTED)
 {
  InitWiFi();                   // call function to start wifi // reconnect wifi
  }
 }
if (!client.connected())                  // if mqtt broker disconnected from thingspeak
{
   Serial.println("MQTT Disconnected");
 while (!client.connected())                    // while mqtt broker disconnected from thingspeak
{
 if (client.connect((char*) clientName.c_str()))          // reconnect to the server
{
  Serial.println("MQTT connected");
}
else 
{
  Serial.println("MQTT connect failed");
  Serial.println("Will reset and try again...");
}
}
}

} void InitWiFi() { // check for the presence of the module if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi module not present"); // don't continue // don't continue while (true); //keep looping until it detect esp8266 module }

// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
  Serial.print("Attempting to connect to WPA SSID: ");
  Serial.println(ssid);
  // Connect to WPA/WPA2 network
  status = WiFi.begin(ssid, pass);
}
// print your WiFi ESP8266 IP address
IPAddress ip = WiFi.localIP(); 
Serial.print("IP Address: ");
Serial.println(ip);
    // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
    // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI): ");
  Serial.println(rssi);
  delay (5000);
}

Hi,

I managed to get Thingspeak JSON data from my channel. However, I would like to know if theres any way to convert Thingspeak's JSON string data to decimal. I would really appreciate it if anyone could tell me how to convert it to decimal.

Currently, this is my JSON: { "created_at": "2020-10-08T09:24:00.0000000Z", "entry_id": 1, "field1": "0", "field2": "12", "field3": "1", "field4": "1", "field5": "1", "field6": "1" }

May I know if it is as simple as deleting the ""? For eg,

{ "created_at": "2020-10-08T09:24:00.0000000Z", "entry_id": 1, "field1": 0, "field2": 12, "field3": 1, "field4": 1, "field5": 1, "field6": 1 }

Hello, I want to create a sort of an alert to display the temperature health like in the image below:

i have found this code:

% This script uses the Air Quality Index (AQI) calculated 
% in "particulateConcentration" to display the appropriate text associated 
% with the index. 
% Copyright 2019 The MathWorks, Inc.
readChannelID = yourChannelID;
% TODO - Replace the [] with the Field ID to read data from:
fieldID1 = 1;
% Channel Read API Key 
% If your channel is private, then enter the read API
% Key between the '' below: 
readAPIKey = yourChannelReadKey;
returnAQI = thingSpeakRead(readChannelID, 'Field', fieldID1,'ReadKey', readAPIKey);
[airCondition, conditionIdx] = returnairhealth(returnAQI);
plotairhealth(airCondition, conditionIdx)
%% Plot Air Health
function plotairhealth(airCondition, conditionIdx)
vertices = [0 0; 1 0; 1 1; 0 1];
faces = [1 2 3 4];
% Use Look Up Table and air health condition to get color for reading
faceColorPatchLUT = [0 0.83 0; 0.44 0.95 0.52; 1 0.98 0.53; 0.95 0.98 0.22; 1 0.39 0.39; 1 0 0];
faceColorPatch = faceColorPatchLUT(conditionIdx,:);
airHealthPatch = patch('Faces',faces,'Vertices',vertices,'FaceColor',faceColorPatch);
hold on 
text(0.5,0.5,airCondition,'FontSize',16,'HorizontalAlignment','center')
hold off
% Remove Axis handle
axHandle = airHealthPatch.Parent;
axHandle.YTickLabel = [];
axHandle.XTickLabel = [];
end
%% Air Health Condition
function [airCondition,conditionIdx] = returnairhealth(returnAQI)
airCondition = {'Good';'Moderate';'Unhealthy for Sensitive Groups';'Unhealthy';'Very Unhealthy';'Hazardous'};
aqiLow = [0;51;101;151;201;301];
aqiHigh = [50;100;150;200;300;500];
lutAQI = table(airCondition,aqiLow,aqiHigh,'VariableNames',{'Air_Health','AQI_low','AQI_high'});
conditionIdx = find(returnAQI >= lutAQI.AQI_low & returnAQI <= lutAQI.AQI_high);
airCondition = string(lutAQI.Air_Health(conditionIdx));
end

However, i don't know howto adapt it to my case where i have only 2 cases : if my variable = 0 : the health is good and the color of the box is green else if my viariable = 1 ==> healt is dangerous and the color is red.

I created a problem in Cody that approximates e. To test the user's solution, I compare their solution to e. What I want to do instead is compare the user's solution to my reference solution. The question is how do I call the reference solution in the test suite?
This is currently my test suite.
sol=exp(1);
y_correct = playgame();
assessVariableEqual('y_correct',sol);
I created several problems recently in CODY. Some of them got removed automatically. I was curious as to why.
It is possible that the problems used latex in their description, so I am not sure if that was the reason they got rejected by the cody server.

Hello, I'm new to thingspeak, i want to combine 4 fields in one chart, i have used the code below

readChannelID = 1408944; % YOUR CHANNEL NUMBER
fieldID1 = 1; % YOUR FIELD NUMBER ie 1 to 8
fieldID2 = 3; % my case 1 Temp 2 Humid
readAPIKey = '19EJIJW6YBM7VS7N';
[data1, time1] = thingSpeakRead(readChannelID, 'Field',fieldID1,'NumDays',1,'ReadKey', readAPIKey);
[data2,time2] = thingSpeakRead(readChannelID, 'Field',fieldID2,'NumDays',1,'ReadKey', readAPIKey);
thingSpeakPlotYY(time1, data1, time2, data2,...
'YGrid1','on','YLabel1','% H.R.',...
'YLabel2','*C','XLabel','Fecha y hora',...
'Title','Tempix y Humix ultimas 24 horas');

However, an error occurs saying that the function thingSpeakPlotYY is unrecognized