Results for
Hello! A few years ago i could write data to my thingspeak field with this code on arduino with ESP8266.
However today when i try this i only get errors. Instead I have to use this code. it is almost the same but connecting without SSL on port 80 instead.
Has anything changed on thingspeaks side? What do i do wrong? Here is a link to the full code if thats needed: https://github.com/kjellcompany/Arduino_701/blob/master/Thingspeak/Thingspeak.ino
Recently, 2nd Jan 2022 my logging has stopped. In My Account I see I have an expiry date of 10/Jan/2022 could this be the cause??? Specifically does a Free Account eventually expire and besides paying for a student or Home account is there anything I can do to continue using ThingSpeak at no charge? My message count is well below the maximum of 3 million per year.
Bonjour, J'utilise arduino Mega 2560 avec le shield Ethernet. Le sketch ino joint ci-après me permet de visualiser la jauge dans la page index.htm chargée sur la carte SD. ThingSpeak affiche bien le graph correspondant. Mais ma page web n'y a pas accès. Comment intégrer les codes dans la page ou dans le sketch pour cela ? Je vous joins la capture d'écran de cette page ainsi que les codes De la page et du sketch. Merci pour votre aide.
*********************************** Code Page "index.htm" ***********************************
<!DOCTYPE html>
<html>
<head>
<title>Arduino Internet Voltmeter</title>
<script>
var data_val = 0; // raw data from Arduino analog input (0 to 1023)
var volts = 0; // voltage calculated from Arduino analog raw data value
var num_updates = 0; // number of 200ms periods used to calculate time to send data to ThingSpeak
// gauge code
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('t W=v(f){W.2t.3T(A);A.B={Z:2u,19:1q,1h:1q,1J:U,1b:D,K:0,V:[\'0\',\'20\',\'40\',\'2A\',\'2B\',\'D\'],2r:10,2C:M,1E:U,2q:{2D:3,2E:2},2H:M,1c:{2j:10,2m:3y,2O:\'3v\'},J:{2P:\'#4h\',V:\'#31\',2r:\'#3k\',1J:\'#37\',1E:\'#37\',3e:\'#31\',1t:{2s:\'1e(3Y, 3d, 3d, 1)\',3c:\'1e(1Y, 5I, 5E, .9)\'}},1o:[{1n:20,1D:2A,1F:\'#3j\'},{1n:2A,1D:2B,1F:\'#36\'},{1n:2B,1D:D,1F:\'#5n\'}]};t g=0,1p=A,N=0,1S=0,1G=U;A.5d=v(a){N=f.1c?g:a;t b=(f.1b-f.K)/D;1S=a>f.1b?1S=f.1b+b:a<f.K?f.K-b:a;g=a;f.1c?3l():A.1g();C A};A.3m=v(a){N=g=a;A.1g();C A};A.4T=v(){g=N=1S=A.B.K;A.1g();C A};A.4R=v(){C g};A.13=v(){};v 2k(a,b){Q(t i 4P b){z(1H b[i]=="1W"&&!(4O.4y.2V.4p(b[i])===\'[1W 4n]\')&&i!=\'Z\'){z(1H a[i]!="1W"){a[i]={}}2k(a[i],b[i])}O{a[i]=b[i]}}};2k(A.B,f);A.B.K=1R(A.B.K);A.B.1b=1R(A.B.1b);f=A.B;N=g=f.K;z(!f.Z){4m 4j("4g 4d 4b 46 44 41 3Z 3W W 1W!");}t j=f.Z.5K?f.Z:2R.5v(f.Z),q=j.3u(\'2d\'),1i,1y,1A,14,17,u,1d;v 2M(){j.19=f.19;j.1h=f.1h;1i=j.4s(M);1d=1i.3u(\'2d\');1y=j.19;1A=j.1h;14=1y/2;17=1A/2;u=14<17?14:17;1i.2J=U;1d.3P(14,17);1d.G();q.3P(14,17);q.G()};2M();A.4Z=v(a){2k(A.B,a);2M();A.1g();C A};t k={4q:v(p){C p},4e:v(p){C E.1L(p,2)},4c:v(p){C E.1L(p,5)},3v:v(p){C 1-E.1O(E.5C(p))},5k:v(p){C 1-(v(p){Q(t a=0,b=1;1;a+=b,b/=2){z(p>=(7-4*a)/11){C-E.1L((11-6*a-11*p)/4,2)+E.1L(b,2)}}})(1-p)},4S:v(p){C 1-(v(p){t x=1.5;C E.1L(2,10*(p-1))*E.1T(20*E.1a*x/3*p)})(1-p)}};t l=2u;v 3S(d){t e=2v 3R;l=2x(v(){t a=2v 3R-e,1M=a/d.2m;z(1M>1){1M=1}t b=1H d.2g=="v"?d.2g:k[d.2g];t c=b(1M);d.3Q(c);z(1M==1){2b(l)}},d.2j||10)};v 3l(){l&&2b(l);t b=(1S-N),1n=N,29=f.1c;3S({2j:29.2j,2m:29.2m,2g:29.2O,3Q:v(a){N=1R(1n)+b*a;1p.1g()}})};q.5l="3O";A.1g=v(){z(!1i.2J){1d.3M(-14,-17,1y,1A);1d.G();t a=q;q=1d;3L();3K();3I();3H();3F();3D();3z();1i.2J=M;q=a;5G a}q.3M(-14,-17,1y,1A);q.G();q.4a(1i,-14,-17,1y,1A);z(!W.28){t b=2x(v(){z(!W.28){C}2b(b);2K();2L();z(!1G){1p.13&&1p.13();1G=M}},10)}O{2K();2L();z(!1G){1p.13&&1p.13();1G=M}}C A};v S(a){C a*E.1a/4J};v 1l(a,b,c){t d=q.4Y(0,0,0,c);d.1V(0,a);d.1V(1,b);C d};v 3L(){t a=u/D*5g,3x=u-a,2a=u/D*5q,5u=u-2a,1f=u/D*5z,5A=u-1f;3t=u/D*5F;q.G();z(f.2H){q.2o=3x;q.2n=\'1e(0, 0, 0, 0.5)\'}q.P();q.16(0,0,a,0,E.1a*2,M);q.L=1l(\'#42\',\'#43\',a);q.T();q.R();q.P();q.16(0,0,2a,0,E.1a*2,M);q.L=1l(\'#49\',\'#36\',2a);q.T();q.P();q.16(0,0,1f,0,E.1a*2,M);q.L=1l(\'#3j\',\'#3s\',1f);q.T();q.P();q.16(0,0,3t,0,E.1a*2,M);q.L=f.J.2P;q.T();q.G()};v 3H(){t r=u/D*2T;q.2e=2;q.2U=f.J.V;q.G();Q(t i=0;i<f.V.H;++i){t a=45+i*(1U/(f.V.H-1));q.1z(S(a));q.P();q.1K(0,r);q.F(0,r-u/D*15);q.1X();q.R();q.G()}z(f.2C){q.1z(S(2X));q.P();q.16(0,0,r,S(45),S(4N),U);q.1X();q.R();q.G()}};v 3I(){t r=u/D*2T;q.2e=1;q.2U=f.J.2r;q.G();t b=f.2r*(f.V.H-1);Q(t i=0;i<b;++i){t a=45+i*(1U/b);q.1z(S(a));q.P();q.1K(0,r);q.F(0,r-u/D*7.5);q.1X();q.R();q.G()}};v 3F(){t r=u/D*55;Q(t i=0;i<f.V.H;++i){t a=45+i*(1U/(f.V.H-1)),p=1w(r,S(a));q.1x=20*(u/1q)+"2i 2Y";q.L=f.J.3e;q.2e=0;q.2h="2f";q.27(f.V[i],p.x,p.y+3)}};v 3D(){z(!f.1J){C}q.G();q.1x=24*(u/1q)+"2i 2Y";q.L=f.J.1J;q.2h="2f";q.27(f.1J,0,-u/4.25);q.R()};v 3z(){z(!f.1E){C}q.G();q.1x=22*(u/1q)+"2i 2Y";q.L=f.J.1E;q.2h="2f";q.27(f.1E,0,u/3.25);q.R()};v 32(a){t b=f.2q.2E,34=f.2q.2D;a=1R(a);t n=(a<0);a=E.35(a);z(b>0){a=a.5t(b).2V().1j(\'.\');Q(t i=0,s=34-a[0].H;i<s;++i){a[0]=\'0\'+a[0]}a=(n?\'-\':\'\')+a[0]+\'.\'+a[1]}O{a=E.3O(a).2V();Q(t i=0,s=34-a.H;i<s;++i){a=\'0\'+a}a=(n?\'-\':\'\')+a}C a};v 1w(r,a){t x=0,y=r,1O=E.1O(a),1T=E.1T(a),X=x*1T-y*1O,Y=x*1O+y*1T;C{x:X,y:Y}};v 3K(){q.G();t a=u/D*2T;t b=a-u/D*15;Q(t i=0,s=f.1o.H;i<s;i++){t c=f.1o[i],39=(f.1b-f.K)/1U,1P=S(45+(c.1n-f.K)/39),1N=S(45+(c.1D-f.K)/39);q.P();q.1z(S(2X));q.16(0,0,a,1P,1N,U);q.R();q.G();t d=1w(b,1P),3a=1w(a,1P);q.1K(d.x,d.y);q.F(3a.x,3a.y);t e=1w(a,1N),3b=1w(b,1N);q.F(e.x,e.y);q.F(3b.x,3b.y);q.F(d.x,d.y);q.1C();q.L=c.1F;q.T();q.P();q.1z(S(2X));q.16(0,0,b,1P-0.2,1N+0.2,U);q.R();q.1C();q.L=f.J.2P;q.T();q.G()}};v 2L(){t a=u/D*12,1f=u/D*8,1u=u/D*3X,1r=u/D*20,2l=u/D*4,1B=u/D*2,38=v(){q.3f=2;q.3g=2;q.2o=10;q.2n=\'1e(5L, 3h, 3h, 0.45)\'};38();q.G();z(N<0){N=E.35(f.K-N)}O z(f.K>0){N-=f.K}O{N=E.35(f.K)+N}q.1z(S(45+N/((f.1b-f.K)/1U)));q.P();q.1K(-1B,-1r);q.F(-2l,0);q.F(-1,1u);q.F(1,1u);q.F(2l,0);q.F(1B,-1r);q.1C();q.L=1l(f.J.1t.2s,f.J.1t.3c,1u-1r);q.T();q.P();q.F(-0.5,1u);q.F(-1,1u);q.F(-2l,0);q.F(-1B,-1r);q.F(1B/2-2,-1r);q.1C();q.L=\'1e(1Y, 1Y, 1Y, 0.2)\';q.T();q.R();38();q.P();q.16(0,0,a,0,E.1a*2,M);q.L=1l(\'#3s\',\'#36\',a);q.T();q.R();q.P();q.16(0,0,1f,0,E.1a*2,M);q.L=1l("#47","#48",1f);q.T()};v 3i(x,y,w,h,r){q.P();q.1K(x+r,y);q.F(x+w-r,y);q.23(x+w,y,x+w,y+r);q.F(x+w,y+h-r);q.23(x+w,y+h,x+w-r,y+h);q.F(x+r,y+h);q.23(x,y+h,x,y+h-r);q.F(x,y+r);q.23(x,y,x+r,y);q.1C()};v 2K(){q.G();q.1x=40*(u/1q)+"2i 30";t a=32(g),2Z=q.4f(\'-\'+32(0)).19,y=u-u/D*33,x=0,2W=0.12*u;q.G();3i(-2Z/2-0.21*u,y-2W-0.4i*u,2Z+0.3n*u,2W+0.4k*u,0.21*u);t b=q.4l(x,y-0.12*u-0.21*u+(0.12*u+0.3o*u)/2,u/10,x,y-0.12*u-0.21*u+(0.12*u+0.3o*u)/2,u/5);b.1V(0,"#37");b.1V(1,"#3k");q.2U=b;q.2e=0.3n*u;q.1X();q.2o=0.3p*u;q.2n=\'1e(0, 0, 0, 1)\';q.L="#4o";q.T();q.R();q.3f=0.3q*u;q.3g=0.3q*u;q.2o=0.3p*u;q.2n=\'1e(0, 0, 0, 0.3)\';q.L="#31";q.2h="2f";q.27(a,-x,y);q.R()}};W.28=U;(v(){t d=2R,h=d.3r(\'4r\')[0],2S=4t.4u.4v().4w(\'4x\')!=-1,2Q=\'4z://4A-4B.4C/4D/4E/4F-7-4G.\'+(2S?\'4H\':\'4I\'),1I="@1x-4K {"+"1x-4L: \'30\';"+"4M: 2Q(\'"+2Q+"\');"+"}",1s,r=d.3w(\'1v\');r.2N=\'1I/4Q\';z(2S){h.2p(r);1s=r.2I;1s.3A=1I}O{4U{r.2p(d.4V(1I))}4W(e){r.3A=1I}h.2p(r);1s=r.2I?r.2I:(r.4X||d.3B[d.3B.H-1])}t b=2x(v(){z(!d.3C){C}2b(b);t a=d.3w(\'50\');a.1v.51=\'30\';a.1v.52=\'53\';a.1v.1h=a.1v.19=0;a.1v.54=\'56\';a.57=\'.\';d.3C.2p(a);58(v(){W.28=M;a.59.5a(a)},3y)},1)})();W.2t=[];W.2t.5b=v(a){z(1H(a)==\'5c\'){Q(t i=0,s=A.H;i<s;i++){z(A[i].B.Z.18(\'5e\')==a){C A[i]}}}O z(1H(a)==\'5f\'){C A[a]}O{C 2u}};v 3E(a){z(2G.3G){2G.3G(\'5h\',a,U)}O{2G.5i(\'5j\',a)}}3E(v(){v 2F(a){t b=a[0];Q(t i=1,s=a.H;i<s;i++){b+=a[i].1Z(0,1).5m()+a[i].1Z(1,a[i].H-1)}C b};v 3J(a){C a.5o(/^\\s+|\\s+$/g,\'\')};t c=2R.3r(\'5p\');Q(t i=0,s=c.H;i<s;i++){z(c[i].18(\'1k-2N\')==\'5r-5s\'){t d=c[i],B={},1m,w=2c(d.18(\'19\')),h=2c(d.18(\'1h\'));B.Z=d;z(w){B.19=w}z(h){B.1h=h}Q(t e=0,1s=d.3N.H;e<1s;e++){1m=d.3N.5w(e).5x;z(1m!=\'1k-2N\'&&1m.1Z(0,5)==\'1k-\'){t f=1m.1Z(5,1m.H-5).5y().1j(\'-\'),I=d.18(1m);z(!I){2z}5B(f[0]){2y\'J\':{z(f[1]){z(!B.J){B.J={}}z(f[1]==\'1t\'){t k=I.1j(/\\s+/);z(k[0]&&k[1]){B.J.1t={2s:k[0],3c:k[1]}}O{B.J.1t=I}}O{f.5D();B.J[2F(f)]=I}}26}2y\'1o\':{z(!B.1o){B.1o=[]}2w=I.1j(\',\');Q(t j=0,l=2w.H;j<l;j++){t m=3J(2w[j]).1j(/\\s+/),1Q={};z(m[0]&&m[0]!=\'\'){1Q.1n=m[0]}z(m[1]&&m[1]!=\'\'){1Q.1D=m[1]}z(m[2]&&m[2]!=\'\'){1Q.1F=m[2]}B.1o.3T(1Q)}26}2y\'1c\':{z(f[1]){z(!B.1c){B.1c={}}z(f[1]==\'2O\'&&/^\\s*v\\s*\\(/.5H(I)){I=3U(\'(\'+I+\')\')}B.1c[f[1]]=I}26}5J:{t n=2F(f);z(n==\'13\'){2z}z(n==\'V\'){I=I.1j(/\\s+/)}O z(n==\'2C\'||n==\'2H\'){I=I==\'M\'?M:U}O z(n==\'2q\'){t o=I.1j(\'.\');z(o.H==2){I={2D:2c(o[0]),2E:2c(o[1])}}O{2z}}B[n]=I;26}}}}t g=2v W(B);z(d.18(\'1k-3V\')){g.3m(1R(d.18(\'1k-3V\')))}z(d.18(\'1k-13\')){g.13=v(){3U(A.B.Z.18(\'1k-13\'))}}g.1g()}}});',62,358,'||||||||||||||||||||||||||ctx|||var|max|function||||if|this|config|return|100|Math|lineTo|save|length|attrValue|colors|minValue|fillStyle|true|fromValue|else|beginPath|for|restore|radians|fill|false|majorTicks|Gauge|||renderTo||||onready|CX||arc|CY|getAttribute|width|PI|maxValue|animation|cctx|rgba|r2|draw|height|cache|split|data|lgrad|prop|from|highlights|self|200|rOut|ss|needle|rIn|style|rpoint|font|CW|rotate|CH|pad2|closePath|to|units|color|imready|typeof|text|title|moveTo|pow|progress|ea|sin|sa|hlCfg|parseFloat|toValue|cos|270|addColorStop|object|stroke|255|substr||025||quadraticCurveTo|||break|fillText|initialized|cfg|r1|clearInterval|parseInt||lineWidth|center|delta|textAlign|px|delay|applyRecursive|pad1|duration|shadowColor|shadowBlur|appendChild|valueFormat|minorTicks|start|Collection|null|new|hls|setInterval|case|continue|60|80|strokeTicks|int|dec|toCamelCase|window|glow|styleSheet|i8d|drawValueBox|drawNeedle|baseInit|type|fn|plate|url|document|ie|81|strokeStyle|toString|th|90|Arial|tw|Led|444|padValue||cint|abs|ccc|888|shad|vd|pe|pe1|end|128|numbers|shadowOffsetX|shadowOffsetY|143|roundRect|eee|666|animate|setRawValue|05|045|012|004|getElementsByTagName|f0f0f0|r3|getContext|cycle|createElement|d0|250|drawUnits|cssText|styleSheets|body|drawTitle|domReady|drawNumbers|addEventListener|drawMajorTicks|drawMinorTicks|trim|drawHighlights|drawPlate|clearRect|attributes|round|translate|step|Date|_animate|push|eval|value|the|77|240|creating||when|ddd|aaa|specified||not|e8e8e8|f5f5f5|fafafa|drawImage|was|quint|element|quad|measureText|Canvas|fff|04|Error|07|createRadialGradient|throw|Array|babab2|call|linear|head|cloneNode|navigator|userAgent|toLocaleLowerCase|indexOf|msie|prototype|http|smart|ip|net|styles|fonts|digital|mono|eot|ttf|180|face|family|src|315|Object|in|css|getValue|elastic|clear|try|createTextNode|catch|sheet|createLinearGradient|updateConfig|div|fontFamily|position|absolute|overflow||hidden|innerHTML|setTimeout|parentNode|removeChild|get|string|setValue|id|number|93|DOMContentLoaded|attachEvent|onload|bounce|lineCap|toUpperCase|999|replace|canvas|91|canv|gauge|toFixed|d1|getElementById|item|nodeName|toLowerCase|88|d2|switch|acos|shift|122|85|delete|test|160|default|tagName|188'.split('|'),0,{}))
// function called periodically to get analog value from Arduino using Ajax
function GetArduinoInputs()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
document.getElementById("input3").innerHTML =
this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
data_val = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
// calculate voltage
volts = data_val * 3.5 / 1023;
// only send data to ThingSpeak every 20 seconds or 100 x 200ms
if (num_updates >= 100) {
num_updates = 0;
// send voltage to ThingSpeak
ThingSpeakSend("xxxxxxxxxxxxxxxx", volts); // insert your ThingSpeak Write API Key here
}
num_updates++;
}
}
}
}
request.open("GET", "ajax_inputs" + nocache, true);
request.send(null);
setTimeout('GetArduinoInputs()', 200); // send the request for Arduino analog data every 200ms
}
// function to send data to ThingSpeak
function ThingSpeakSend(api_write_key, voltage)
{
var ts_req = new XMLHttpRequest();
// GET request string - modify if more fields are needed
var req_str = "http://api.thingspeak.com/update?key=" + api_write_key + "&field1=" + voltage;
ts_req.onreadystatechange = function()
{
// not doing anything with response from ThingSpeak
}
// send the data to ThingSpeak
ts_req.open("GET", req_str, true);
ts_req.send(null);
}
</script>
</head>
<body onload="GetArduinoInputs()">
<h1>Arduino Internet Voltmeter</h1>
<p>Analog (A2): <span id="input3">...</span></p>
<canvas id="an_gauge_1" data-major-ticks="0 0.5 1 1.5 2 2.5 3 3.5" data-type="canv-gauge" data-min-value="0" data-max-value="3.5" data-onready="setInterval( function() { Gauge.Collection.get('an_gauge_1').setValue(volts);}, 200);"></canvas>
<!-- insert ThingSpeak chart code here -->
<iframe width="450" height="260" style="border: 1px solid #cccccc;" src="https://thingspeak.com/channels/1620920/charts/1?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=20&yaxismax=4&yaxismin=0"></iframe>
<!-- REPLACE THIS COMMENT WITH YOUR THINGSPEAK GRAPH -->
</body>
</html>********************************************* Code "eth_websrv_SD_Ajax_gauge.ino" : *********************************************
#include <Ethernet.h> #include <SD.h> #include <ThingSpeak.h>
// size of buffer used to capture HTTP requests #define REQ_BUF_SZ 50
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x1A, 0x71 };
IPAddress ip(192, 168, 1, 17); // IP address, may need to change depending on network
EthernetServer server(80); // create a server at port 80
File webFile; // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0; // index into HTTP_req buffer
void setup()
{
// disable Ethernet chip
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
Serial.begin(9600); // for debugging
// initialize SD card
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("ERROR - SD card initialization failed!");
return; // init failed
}
Serial.println("SUCCESS - SD card initialized.");
// check for index.htm file
if (!SD.exists("index.htm")) {
Serial.println("ERROR - Can't find index.htm file!");
return; // can't find index file
}
Serial.println("SUCCESS - Found index.htm file."); Ethernet.begin(mac, ip); // initialize Ethernet device
server.begin(); // start to listen for clients
Serial.print ("*\n -> Le serveur est sur l'adresse : ");
Serial.println(Ethernet.localIP());
}void loop()
{
EthernetClient client = server.available(); // try to get client
if (client) // got client?
{
boolean currentLineIsBlank = true; while (client.connected())
{
if (client.available()) // client data available to read
{
char c = client.read(); // read 1 byte (character) from client
// buffer first part of HTTP request in HTTP_req array (string)
// leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
if (req_index < (REQ_BUF_SZ - 1)) {
HTTP_req[req_index] = c; // save HTTP request character
req_index++;
}
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
// remainder of header follows below, depending on if
// web page or XML page is requested
// Ajax request - send XML file
if (StrContains(HTTP_req, "ajax_inputs")) {
// send rest of HTTP header
client.println("Content-Type: text/xml");
client.println("Connection: keep-alive");
client.println(); // send XML file containing input states
XML_response(client);
}
else { // web page request
// send rest of HTTP header
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
// send web page
webFile = SD.open("index.htm"); // open web page file
if (webFile) {
while(webFile.available()) {
client.write(webFile.read()); // send web page to client
}
webFile.close();
}
}
// display received HTTP request on serial port
Serial.print(HTTP_req);
// reset buffer index and all buffer elements to 0
req_index = 0;
StrClear(HTTP_req, REQ_BUF_SZ);
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}// send the XML file containing analog value
void XML_response(EthernetClient cl)
{
int analog_val;
cl.print("<?xml version = \"1.0\" ?>");
cl.print("<inputs>");
// read analog pin A2
analog_val = analogRead(2);
cl.print("<analog>");
cl.print(analog_val);
cl.print("</analog>");
cl.print("</inputs>");
}// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
for (int i = 0; i < length; i++) {
str[i] = 0;
}
}
// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
char found = 0;
char index = 0;
char len;
len = strlen(str);
if (strlen(sfind) > len) {
return 0;
}
while (index < len) {
if (str[index] == sfind[found]) {
found++;
if (strlen(sfind) == found) {
return 1;
}
}
else {
found = 0;
}
index++;
}
return 0; }
My dear friend Ram and I have finished our latest movie series. You can watch the final movie , or see the whole series.
In this movie we show how you can use TimeControls and Reacts to control devices or to schedule your MATLAB code that you can write in ThingSpeak. We also discuss a bit about channel sharing.
Is it possible to use the REST API to create ThingHTTP requests?
I am using TX and RX pin of arduino connect to RX and TX pin of NodeMCU. The data does not received, the data upload to thingspeak is zero.
Hi Everyone,
Today mistakenly i clear the working channel instead of testing channel which have more then 27000 Environmental Sensor readings so is there any option where i can get back my that data?
Thank you.
Hi!
I'm trying to use a mix of Arduino Nano + SIM800L + RTC DS3231 + 2x PZEM-004T to achieve the goal of upload the two Energy readings every 24h to Thingspeak channel. My sketch is this https://pastebin.com/a6Zn8HaV, i'm in doubt if the use of String class for the GET job is correct.
Could you help me?
Thanks
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
I have android 2.4 and 4.4 mobile device. I tried yesterday night, they are good working. Send data to my chanels and receive data good working. Same program android 6.0 good working yesterday night and tonight. But tonight, android 2.4 and 4.4 mobile device give 1101 error.
COMO FACO PARA COLOCAR EM TEMPO REAL VIA CODIGO AT + CLBS a localizacao, alguem pode me ajudar ????
we are doing a project on health monitoring system. We have made all the required changes in the code but our data is not being uploaded in thingspeak.It would be of great help if you can suggest some way.
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#include <SoftwareSerial.h>
float pulse = 0;
float temp = 0;
SoftwareSerial ser(9,10);
String apiKey = "xxxxxxxxxxxxxxxx"; // Variables
int pulsePin = A0; // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 7 ; // pin to blink led at each beat
int fadePin = 13; // pin to do fancy classy fading blink at each beat
int fadeRate = 0; // used to fade LED on with PWM on fadePin// Volatile Variables, used in the interrupt service routine!
volatile int BPM; // int that holds raw Analog in 0. updated every 2mS
volatile int Signal; // holds the incoming raw data
volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when nota "live beat".
volatile boolean QS = false; // becomes true when Arduoino finds a beat. // Regards Serial OutPut -- Set This Up to your needs
static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse
volatile int rate[10]; // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0; // used to determine pulse timing
volatile unsigned long lastBeatTime = 0; // used to find IBI
volatile int P = 512; // used to find peak in pulse wave, seeded
volatile int T = 512; // used to find trough in pulse wave, seeded
volatile int thresh = 525; // used to find instant moment of heart beat, seeded
volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM void setup()
{
lcd.begin(16, 2);
pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat!
pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat!
Serial.begin(115200); // we agree to talk fast!
interruptSetup(); // sets up to read Pulse Sensor signal every 2mS// IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
// UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
// analogReference(EXTERNAL);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Patient Health");
lcd.setCursor(0,1);
lcd.print(" Monitoring ");
delay(4000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Initializing....");
delay(5000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Getting Data....");
ser.begin(9600);
ser.println("AT");
delay(1000);
ser.println("AT+GMR");
delay(1000);
ser.println("AT+CWMODE=3");
delay(1000);
ser.println("AT+RST");
delay(5000);
ser.println("AT+CIPMUX=1");
delay(1000); String cmd="AT+CWJAP=\"Harshini Arulkumaran\",\"prythian\"";
ser.println(cmd);
delay(1000);
ser.println("AT+CIFSR");
delay(1000);
} // Where the Magic Happens
void loop()
{
serialOutput();
if (QS == true) // A Heartbeat Was Found
{ // BPM and IBI have been Determined
// Quantified Self "QS" true when arduino finds a heartbeat
fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED with pulse
serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
QS = false; // reset the Quantified Self flag for next time
}
ledFadeToBeat(); // Makes the LED Fade Effect Happen
delay(20); // take a break
read_temp();
esp_8266();
}
void ledFadeToBeat()
{
fadeRate -= 15; // set LED fade value
fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers!
analogWrite(fadePin,fadeRate); // fade LED
}
void interruptSetup()
{
// Initializes Timer2 to throw an interrupt every 2mS.
TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER
OCR2A = 0X7C; // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}
void serialOutput()
{ // Decide How To Output Serial.
if (serialVisual == true)
{
arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial Monitor Visualizer
}
else
{
sendDataToSerial('S', Signal); // goes to sendDataToSerial function
}
}
void serialOutputWhenBeatHappens()
{
if (serialVisual == true) // Code to Make the Serial Monitor Visualizer Work
{
Serial.print("Heart-Beat Detected"); //ASCII Art Madness
Serial.print("BPM: ");
Serial.println(BPM);
}
else
{
sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix
sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix
}
}
void arduinoSerialMonitorVisual(char symbol, int data )
{
const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 1024; // sensor maximum, discovered through experiment
int sensorReading = data; // map the sensor range to a range of 12 options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
// do something different depending on the
// range value:
switch (range)
{
case 0:
Serial.println(""); /////ASCII Art Madness
break;
case 1:
Serial.println("---");
break;
case 2:
Serial.println("------");
break;
case 3:
Serial.println("---------");
break;
case 4:
Serial.println("------------");
break;
case 5:
Serial.println("--------------|-");
break;
case 6:
Serial.println("--------------|---");
break;
case 7:
Serial.println("--------------|-------");
break;
case 8:
Serial.println("--------------|----------");
break;
case 9:
Serial.println("--------------|----------------");
break;
case 10:
Serial.println("--------------|-------------------");
break;
case 11:
Serial.println("--------------|-----------------------");
break;
}
} void sendDataToSerial(char symbol, int data )
{
Serial.print(symbol);
Serial.println(data);
}
ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124
{
cli(); // disable interrupts while we do this
Signal = analogRead(pulsePin); // read the Pulse Sensor
sampleCounter += 2; // keep track of the time in mS with this variable
int N = sampleCounter - lastBeatTime; // monitor the time since the last beat to avoid noise
// find the peak and trough of the pulse wave if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI
{
if (Signal < T) // T is the trough
{
T = Signal; // keep track of lowest point in pulse wave
}
}
if(Signal > thresh && Signal > P)
{ // thresh condition helps avoid noise
P = Signal; // P is the peak
} // keep track of highest point in pulse wave
// NOW IT'S TIME TO LOOK FOR THE HEART BEAT
// signal surges up in value every time there is a pulse
if (N > 250)
{ // avoid high frequency noise
if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )
{
Pulse = true; // set the Pulse flag when we think there is a pulse
digitalWrite(blinkPin,HIGH); // turn on pin 13 LED
IBI = sampleCounter - lastBeatTime; // measure time between beats in mS
lastBeatTime = sampleCounter; // keep track of time for next pulse if(secondBeat)
{ // if this is the second beat, if secondBeat == TRUE
secondBeat = false; // clear secondBeat flag
for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup
{
rate[i] = IBI;
}
}
if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE
{
firstBeat = false; // clear firstBeat flag
secondBeat = true; // set the second beat flag
sei(); // enable interrupts again
return; // IBI value is unreliable so discard it
}
// keep a running total of the last 10 IBI values
word runningTotal = 0; // clear the runningTotal variable
for(int i=0; i<=8; i++)
{ // shift data in the rate array
rate[i] = rate[i+1]; // and drop the oldest IBI value
runningTotal += rate[i]; // add up the 9 oldest IBI values
}
rate[9] = IBI; // add the latest IBI to the rate array
runningTotal += rate[9]; // add the latest IBI to runningTotal
runningTotal /= 10; // average the last 10 IBI values
BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM!
QS = true; // set Quantified Self flag
// QS FLAG IS NOT CLEARED INSIDE THIS ISR
pulse = BPM;
}
}
if (Signal < thresh && Pulse == true)
{ // when the values are going down, the beat is over
digitalWrite(blinkPin,LOW); // turn off pin 13 LED
Pulse = false; // reset the Pulse flag so we can do it again
amp = P - T; // get amplitude of the pulse wave
thresh = amp/2 + T; // set thresh at 50% of the amplitude
P = thresh; // reset these for next time
T = thresh;
}
if (N > 2500)
{ // if 2.5 seconds go by without a beat
thresh = 512; // set thresh default
P = 512; // set P default
T = 512; // set T default
lastBeatTime = sampleCounter; // bring the lastBeatTime up to date
firstBeat = true; // set these to avoid noise
secondBeat = false; // when we get the heartbeat back
}
sei(); // enable interrupts when youre done!
}// end isr
void esp_8266()
{
// TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80
String cmd = "AT+CIPSTART=4,\"TCP\",\"";
cmd += "192.168.137.1"; // api.thingspeak.com
cmd += "\",80";
ser.println(cmd);
Serial.println(cmd);
if(ser.find("Error"))
{
Serial.println("AT+CIPSTART error");
return;
}
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr +="&field1=";
getStr +=String(temp);
getStr +="&field2=";
getStr +=String(pulse);
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=4,";
cmd += String(getStr.length());
ser.println(cmd);
Serial.println(cmd);
delay(1000);
ser.print(getStr);
Serial.println(getStr); //thingspeak needs 15 sec delay between updates
delay(3000);
}
void read_temp()
{
int temp_val = analogRead(A1);
float mv = (temp_val/1024.0)*5000;
float cel = mv/10;
temp = (cel*9)/5 + 32;
Serial.print("Temperature:");
Serial.println(temp);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("BPM :");
lcd.setCursor(7,0);
lcd.print(BPM);
lcd.setCursor(0,1);
lcd.print("Temp.:");
lcd.setCursor(7,1);
lcd.print(temp);
lcd.setCursor(13,1);
lcd.print("F");
}Dear all, I am using the micro:bit with ESP-01s and the CO2 sensor to monitor indoor air quality. Thingspeak cannot show the data eventhough the ESP is connected to the wifi (checked with the router). Failed to talk to my ESP even I have setup a new channel many times. Can anyone advise me what to do?
Thank you for your help in advance.
hello, when I add a visualization, it is written "Field value unavailable" can somebody assist ?
many thanks
Hi, I'm trying to send with a serial connection a signal. The signal is just a byte (uint8) that I want to send to my evaluation board every 1 millisecond using Simulink. How can I do that? I tried using the Serial Send block, but the result is different from what I expected to see. Then I tried to use the To instrument block, but I don't know why there isn't the port COM 5 so I couldn't use it.
The third movie in our new series is live. We focus on MATLAB Analysis and Visualizations in this video. You can see how to set up code to preprocess your data and how to add custom visualizations.
So far I haven't found an option to change the channel's name, neither on website nor in the API. Is it possible to change the channel name?
Hi, I am currently working on IOT control using ZYBO-Z7 FPGA with the Pmod ESP32, my goal is to read multiple data across 8 fields simultaneously, my current method is reading data from individual fields manually using the code given from this user from a digilent forum (https://forum.digilentinc.com/topic/21634-retrieve-data-from-thingspeak-through-using-pmod-esp32/), this method makes the control slow as I have to individually wait for 8 fields of data one by one. My current solution I am testing out is to read json data using the C++ code below, however the json file is a placed in constant and can only read from that specific array and does not update real time data from thingspeak, how do I get my ZYBO-Z7 to process multiple data from a single feed with 8 fields all from one json URL? Much needed help please and thanks.
/*
* This workspace attempts to parse (deserialize) a serialize json data
* from thingspeak (see project_4_1). The code below was extracted (with some editing) from
* arduinojson.org/v5/assistant after I input the serialize json data
* from project_4_1: {"channel":{"id":1410948,"name":"testing","latitude":"0.0","longitude":"0.0","field1":"temp","field2":"ph","created_at":"2021-06-08T07:08:42Z","updated_at":"2021-06-09T04:58:00Z","last_entry_id":3},"feeds":[{"created_at":"2021-06-08T08:05:31Z","entry_id":1,"field1":"63"},{"created_at":"2021-06-08T08:07:35Z","entry_id":2,"field1":"76"},{"created_at":"2021-06-08T08:14:50Z","entry_id":3,"field1":"56"}]}
* The extracted code from arduinojson assistant was tested in
* https://wandbox.org/permlink/T07A43gUP3EuZjaF
*/
#include <iostream> //if complained of "unresolved inclusion", just build project #include <ArduinoJson-v5.13.5.h>
#include "xparameters.h" #include "xil_printf.h" #include "sleep.h" #include "stdio.h" #include "xtime_l.h" #include "stdlib.h" //added #include "string.h" #include "xgpiops.h"
extern"C"{
#include "PmodESP32.h"
}
#ifdef __MICROBLAZE__ #define HOST_UART_DEVICE_ID XPAR_AXI_UARTLITE_0_BASEADDR #define HostUart XUartLite #define HostUart_Config XUartLite_Config #define HostUart_CfgInitialize XUartLite_CfgInitialize #define HostUart_LookupConfig XUartLite_LookupConfig #define HostUart_Recv XUartLite_Recv #define HostUartConfig_GetBaseAddr(CfgPtr) (CfgPtr->RegBaseAddr) #include "xuartlite.h" #include "xil_cache.h" #else #define HOST_UART_DEVICE_ID XPAR_PS7_UART_1_DEVICE_ID #define HostUart XUartPs #define HostUart_Config XUartPs_Config #define HostUart_CfgInitialize XUartPs_CfgInitialize #define HostUart_LookupConfig XUartPs_LookupConfig #define HostUart_Recv XUartPs_Recv #define HostUartConfig_GetBaseAddr(CfgPtr) (CfgPtr->BaseAddress) #include "xuartps.h" #endif
#define PMODESP32_UART_BASEADDR XPAR_PMODESP32_0_AXI_LITE_UART_BASEADDR #define PMODESP32_GPIO_BASEADDR XPAR_PMODESP32_0_AXI_LITE_GPIO_BASEADDR #define BLOCK_SIZE 40
void EnableCaches(); void DisableCaches(); void DemoInitialize(); void DemoRun(); void DemoCleanup();
void receiveData(XTime time); void setWifiMode(void); void connectWifi(void); void establishConnection(void); void cipsend(void);
PmodESP32 ESP32; HostUart myHostUart;
XTime TimeStart; XTime TimeEnd;
int countdown =60;
char *ptr;
XGpioPs_Config *ConfigPtr; static XGpioPs Gpio;
u8 light; u8 light1; //ALS
u16 eCO2; u16 TVOC; u8 buf[5]; //AQS
u8 recv_buffer; u32 num_received;
const float ReferenceVoltage = 3.3;
int sec = 0; int min = 0; int hour = 0; int x = 0; int j = 0; int status; int fakecount1 = 0; int fakecount2 = 0; int floatmotor = 0; int floatpumpspoil = 0; int motorreal = 0; int DosingDone = 0;
int led1status = 0; int led234status = 0; int pumpstatus = 0; int motorstatus = 0; int pumpbroken = 0; int checkingEC = 0;
float ECvalue = 0; float PHvalue = 0;
void DemoInitialize () {
HostUart_Config *CfgPtr; EnableCaches(); ESP32_Initialize(&ESP32, PMODESP32_UART_BASEADDR, PMODESP32_GPIO_BASEADDR); CfgPtr = HostUart_LookupConfig(HOST_UART_DEVICE_ID); HostUart_CfgInitialize(&myHostUart, CfgPtr, HostUartConfig_GetBaseAddr(CfgPtr));
ConfigPtr = XGpioPs_LookupConfig(XPAR_PS7_GPIO_0_DEVICE_ID); XGpioPs_CfgInitialize(&Gpio, ConfigPtr, ConfigPtr->BaseAddr);
XGpioPs_SetDirectionPin(&Gpio, 13, 1); XGpioPs_SetOutputEnablePin(&Gpio, 13,1); //pin1 JF1 layer 1 LED #
XGpioPs_SetDirectionPin(&Gpio, 10, 1); XGpioPs_SetOutputEnablePin(&Gpio, 10,1); //pin2 JF2 layer 2, 3, 4 LED #
}
void DemoRun() {
setWifiMode(); connectWifi(); establishConnection(); cipsend();
}
void DemoCleanup() {
DisableCaches();
}
int main() {
DemoInitialize(); DemoRun();
free(ptr);
const size_t capacity = JSON_OBJECT_SIZE(10) + 140; DynamicJsonBuffer jsonBuffer(capacity);
//const char* json = "{\"created_at\":\"2021-11-19T05:33:15Z\",\"entry_id\":134,\"field1\":\"0\",\"field2\":\"1\",\"field3\":\"1\",\"field4\":\"1\",\"field5\":\"2\",\"field6\":\"2\",\"field7\":\"2\",\"field8\":\"10\"}";
JsonObject& root = jsonBuffer.parseObject(json);
const char* created_at = root["created_at"]; // "2021-11-19T05:33:15Z" int entry_id = root["entry_id"]; // 134 const char* field1 = root["field1"]; // "0" const char* field2 = root["field2"]; // "1" const char* field3 = root["field3"]; // "1" const char* field4 = root["field4"]; // "1" const char* field5 = root["field5"]; // "2" const char* field6 = root["field6"]; // "2" const char* field7 = root["field7"]; // "2" const char* field8 = root["field8"]; // "10"
if(root["field1"] == "1")
{
xil_printf("1");
}
else if(root["field1"] == "0")
{
xil_printf("0");
}
else
{
xil_printf("error reading");
}
if(root["field2"] == "1")
{
xil_printf("1");
}
else if(root["field2"] == "0")
{
xil_printf("0");
}
else
{
xil_printf("error reading");
}
if(root["field3"] == "1")
{
xil_printf("1");
}
else if(root["field3"] == "0")
{
xil_printf("0");
}
else
{
xil_printf("error reading");
}
if(root["field4"] == "1")
{
xil_printf("1");
}
else if(root["field4"] == "0")
{
xil_printf("0");
}
else
{
xil_printf("error reading");
}
if(root["field5"] == "1")
{
xil_printf("1");
}
else if(root["field5"] == "0")
{
xil_printf("0");
}
else
{
xil_printf("error reading");
}
DemoCleanup();
return 0; }
void setWifiMode(void){
u8 tx[]="AT+CWMODE=3\r\n";
u32 num = strlen((char *) tx);
xil_printf((char *) tx);
ESP32_SendBuffer(&ESP32, tx, num);
usleep(100000);
receiveData(1);
}
void connectWifi(void){
u8 tx[] = "AT+CWJAP=\"eee-iot\",\"gr3enChess30\"\r\n";
u32 num = strlen((char *) tx);
xil_printf((char *) tx);
ESP32_SendBuffer(&ESP32, tx, num);
usleep(100000);
receiveData(9);
}
void receiveData(XTime time){
XTime tEnd, tCur;
u8 recv_buffer=0;
u32 num_received=0;
XTime_GetTime(&tCur);
tEnd = tCur + (time * COUNTS_PER_SECOND);
do
{
num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
if(num_received >0){
num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
xil_printf("%c", recv_buffer); }
if(tCur == tCur + COUNTS_PER_SECOND){
countdown = countdown -1;
}
else
XTime_GetTime(&tCur);
} while (tCur < tEnd);}
void receiveData2(XTime time){
XTime tEnd, tCur;
u8 recv_buffer=0;
u32 num_received=0;
int i=0;
int max_index = BLOCK_SIZE-1; ptr = (char*) malloc(sizeof(int)*BLOCK_SIZE); //compare with project_4_3 or _4_1 where (int*) is not required because it is a C file in those projects
if(ptr==NULL)
{
perror("some error");
//return 1;
} XTime_GetTime(&tCur);
tEnd = tCur + (time * COUNTS_PER_SECOND);
do
{
num_received = ESP32_Recv(&ESP32, &recv_buffer,1);
if(num_received >0){
num_received = ESP32_Recv(&ESP32, &recv_buffer,1); if(i > max_index)
{
ptr=(char*) realloc(ptr, (max_index+1 + BLOCK_SIZE)*sizeof(int)); //compare with project_4_3 or _4_1 where (int*) in realloc is not required because it is a C file in those projects
if(ptr == NULL)
{
perror("insufficient memory!");
break;
}
//printf("\nReallocated!");
max_index += BLOCK_SIZE;
}
ptr[i]=recv_buffer; i++;
//} }
if(tCur == tCur + COUNTS_PER_SECOND){
countdown = countdown -1;
}
else
XTime_GetTime(&tCur);
} while (tCur < tEnd);}
void establishConnection(void){
u8 tx[] = "AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80\r\n";
u32 num = strlen((char *) tx);
ESP32_SendBuffer(&ESP32, tx, num);
receiveData(1);
}
void cipsend(void){
u8 command[150];
u8 finalcmd[50];
sprintf((char*)command, "GET https://api.thingspeak.com/channels/1572052/feeds/last.json/?api_key=xxxxxxxxxxxxxxxx\r\n");
u32 length = strlen((char*)command);
sprintf((char*)finalcmd, "AT+CIPSEND=%d\r\n", (int)length);
u32 cmdlength =strlen((char*)finalcmd);
xil_printf("Length %d\r\n", length);
xil_printf((char *)finalcmd);
ESP32_SendBuffer(&ESP32, finalcmd, cmdlength);
usleep(100000);
xil_printf((char *)command);
ESP32_SendBuffer(&ESP32, command, length);
receiveData2(1);}
void EnableCaches() {
#ifdef __MICROBLAZE__
#ifdef XPAR_MICROBLAZE_USE_ICACHE
Xil_ICacheEnable();
#endif
#ifdef XPAR_MICROBLAZE_USE_DCACHE
Xil_DCacheEnable();
#endif
#endif
}
void DisableCaches() {
#ifdef __MICROBLAZE__
#ifdef XPAR_MICROBLAZE_USE_ICACHE
Xil_ICacheDisable();
#endif
#ifdef XPAR_MICROBLAZE_USE_DCACHE
Xil_DCacheDisable();
#endif
#endif
}
i am trying to decode the below sketch to integrate TTNv3 to thingspeak.
can someone help me with this issue
#include <lmic.h> #include <dht.h> #include <hal/hal.h> #include <SPI.h> dht DHT; #define DHT11_PIN 5 #define PIN_A A0
float temperature,humidity; float tem,hum;
unsigned int count = 1; //For times count
String datastring1=""; String datastring2=""; String datastring3="";
static uint8_t mydata[11] = {0x01,0x67,0x00,0x00,0x02,0x68,0x00,0x03,0x65,0x00,0x00};
/* LoRaWAN NwkSKey, network session key
This is the default Semtech key, which is used by the prototype TTN
network initially.
ttn*/
static const PROGMEM u1_t NWKSKEY[16] = { 0x72, 0x13, 0xF8, 0xF0, 0x9A, 0x3C, 0xF9, 0xE5, 0xE6, 0x01, 0xDA,0xAC, 0x32, 0xBA, 0x37 };
/* LoRaWAN AppSKey, application session key
This is the default Semtech key, which is used by the prototype TTN
network initially.
ttn*/
static const u1_t PROGMEM APPSKEY[16] = { 0x2F, 0xF5, 0xF4, 0x08, 0x4E, 0x37, 0x20, 0x02, 0xBA, 0x2B, 0xED, 0x40, 0x24, 0xA2, 0x945 };
/* LoRaWAN end-device address (DevAddr) See http://thethingsnetwork.org/wiki/AddressSpace ttn*/ static const u4_t DEVADDR = 0x260D0CA5;
/* These callbacks are only used in over-the-air activation, so they are
left empty here (we cannot leave them out completely unless
DISABLE_JOIN is set in config.h, otherwise the linker will complain).*/
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
static osjob_t initjob,sendjob,blinkjob;
/* Schedule TX every this many seconds (might become longer due to duty cycle limitations).*/ const unsigned TX_INTERVAL = 10;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 10,
.rxtx = LMIC_UNUSED_PIN,
.rst = 9,
.dio = {2, 6, 7},
};
void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println("OP_TXRXPEND, not sending");
} else {
dhtTem();
light();
// Prepare upstream data transmission at the next possible time.
// LMIC_setTxData2(1,datasend,sizeof(datasend)-1,0);
LMIC_setTxData2(1, mydata, sizeof(mydata), 0);
Serial.println("Packet queued");
Serial.print("LMIC.freq:");
Serial.println(LMIC.freq);
Serial.println("Receive data:"); }
// Next TX is scheduled after TX_COMPLETE event.
}void onEvent (ev_t ev) {
Serial.print(os_getTime());
Serial.print(": ");
Serial.println(ev);
switch(ev) {
case EV_SCAN_TIMEOUT:
Serial.println(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Serial.println(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Serial.println(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Serial.println(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
Serial.println(F("EV_JOINED"));
break;
case EV_RFU1:
Serial.println(F("EV_RFU1"));
break;
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
if(LMIC.dataLen) {
// data received in rx slot after tx
Serial.print(F("Data Received: "));
Serial.write(LMIC.frame+LMIC.dataBeg, LMIC.dataLen);
Serial.println();
}
// Schedule next transmission
os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
break;
case EV_LOST_TSYNC:
Serial.println(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Serial.println(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Serial.println(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Serial.println(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Serial.println(F("EV_LINK_ALIVE"));
break;
default:
Serial.println(F("Unknown event"));
break;
}
}
void setup() {
// initialize digital pin as an output.
Serial.begin(9600);
while(!Serial);
Serial.println("Connect to TTN and Send data to mydevice(Use DHT11 Sensor):"); #ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif // LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
/*LMIC_setClockError(MAX_CLOCK_ERROR * 1/100);
Set static session parameters. Instead of dynamically establishing a session
by joining the network, precomputed session parameters are be provided.*/
#ifdef PROGMEM
/* On AVR, these values are stored in flash and only copied to RAM
once. Copy them to a temporary buffer here, LMIC_setSession will
copy them into a buffer of its own again.*/
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif for (int channel=0; channel<8; ++channel) {
LMIC_disableChannel(channel);
}
for (int channel=16; channel<72; ++channel) {
LMIC_disableChannel(channel);
} // Disable link check validation
LMIC_setLinkCheckMode(0); // TTN uses SF9 for its RX2 window.
LMIC.dn2Dr = DR_SF9; // Set data rate and transmit power (note: txpow seems to be ignored by the library)
LMIC_setDrTxpow(DR_SF7,14); // Start job
do_send(&sendjob);
}
void dhtTem()
{
int16_t tem1;
temperature = DHT.read11(DHT11_PIN); //Temperature detection
tem = DHT.temperature*1.0;
float humidity = DHT.read11(DHT11_PIN);
float hum = DHT.humidity* 1.0; Serial.print(F("########### "));
Serial.print(F("NO."));
Serial.print(count);
Serial.println(F(" ###########"));
Serial.println(F("The temperautre and humidity :"));
Serial.print(F("["));
Serial.print(tem);
Serial.print(F("℃"));
Serial.print(F(","));
Serial.print(hum);
Serial.print(F("%"));
Serial.print(F("]"));
Serial.println("");
count++;
tem1=(tem*10);
mydata[2] = tem1>>8;
mydata[3]= tem1;
mydata[6] = hum * 2;}
void light(){
int16_t lux;
int val,val1;
val=analogRead(PIN_A);
// Serial.print(F("a:"));
//Serial.println(val);
delay(500);
val1=val*1.0;
lux=val1;
mydata[9]=lux>>8;
mydata[10]=lux;
//Serial.print(lux);
}
void loop() {
os_runloop_once();
}
Hi there,
I have tried to get the data on thingspeak via integrating it on the things Network. but the GPS data I am receiving on the thingspeak is delayed by 2 mins.
is there any way I can code to send JSON file straight on thingspeak from the sensor or the gateway?
Following is the ardiuno sketch
#include <lmic.h> #include <hal/hal.h> #include <SPI.h> #include <SoftwareSerial.h> #include <TinyGPS.h> TinyGPS gps; SoftwareSerial ss(3, 4); // Arduino RX, TX to conenct to GPS module.
static void smartdelay(unsigned long ms);
unsigned int count = 1; //For times count
String datastring1=""; String datastring2=""; String datastring3=""; uint8_t datasend[20]; //Used to store GPS data for uploading
char gps_lon[20]={"\0"}; //Storage GPS info
char gps_lat[20]={"\0"}; //Storage latitude
char gps_alt[20]={"\0"}; //Storage altitude
float flat, flon,falt;
static uint8_t mydata[] = "Hello, world!"; //For test using.
/* LoRaWAN NwkSKey, network session key
This is the default Semtech key, which is used by the prototype TTN
network initially.
ttn*/
static const PROGMEM u1_t NWKSKEY[16] = { 0xE4, 0x2A, 0x93, 0x96, 0xF7, 0xC9, 0x65, 0x9E, 0xF8, 0x90, 0xC6, 0xA0, 0x1A, 0x88, 0xF7, 0x47 };
/* LoRaWAN AppSKey, application session key
This is the default Semtech key, which is used by the prototype TTN
network initially.
ttn*/
static const u1_t PROGMEM APPSKEY[16] = { 0x75, 0x43, 0x26, 0xA1, 0x82, 0x79, 0x7F, 0xCF, 0x3C, 0x1D, 0xBF, 0xF9, 0xBF, 0xCB, 0xC6, 0xD9 };
/* LoRaWAN end-device address (DevAddr) See http://thethingsnetwork.org/wiki/AddressSpace ttn*/ static const u4_t DEVADDR = 0x260111D1;
/* These callbacks are only used in over-the-air activation, so they are
left empty here (we cannot leave them out completely unless
DISABLE_JOIN is set in config.h, otherwise the linker will complain).*/
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
static osjob_t initjob,sendjob,blinkjob;
/* Schedule TX every this many seconds (might become longer due to duty cycle limitations).*/ const unsigned TX_INTERVAL = 20;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 10,
.rxtx = LMIC_UNUSED_PIN,
.rst = 9,
.dio = {2, 6, 7},
};
void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println("OP_TXRXPEND, not sending");
} else {
GPSRead();
GPSWrite();
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1,datasend,sizeof(datasend)-1,0);
//LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
Serial.println("Packet queued");
Serial.print("LMIC.freq:");
Serial.println(LMIC.freq);
Serial.println("");
Serial.println("");
Serial.println("Receive data:"); }
// Next TX is scheduled after TX_COMPLETE event.
}void onEvent (ev_t ev) {
Serial.print(os_getTime());
Serial.print(": ");
Serial.println(ev);
switch(ev) {
case EV_SCAN_TIMEOUT:
Serial.println("EV_SCAN_TIMEOUT");
break;
case EV_BEACON_FOUND:
Serial.println("EV_BEACON_FOUND");
break;
case EV_BEACON_MISSED:
Serial.println("EV_BEACON_MISSED");
break;
case EV_BEACON_TRACKED:
Serial.println("EV_BEACON_TRACKED");
break;
case EV_JOINING:
Serial.println("EV_JOINING");
break;
case EV_JOINED:
Serial.println("EV_JOINED");
break;
case EV_RFU1:
Serial.println("EV_RFU1");
break;
case EV_JOIN_FAILED:
Serial.println("EV_JOIN_FAILED");
break;
case EV_REJOIN_FAILED:
Serial.println("EV_REJOIN_FAILED");
break;
case EV_TXCOMPLETE:
Serial.println("EV_TXCOMPLETE (includes waiting for RX windows)");
if(LMIC.dataLen) {
// data received in rx slot after tx
Serial.print("Data Received: ");
Serial.write(LMIC.frame+LMIC.dataBeg, LMIC.dataLen);
Serial.println();
}
// Schedule next transmission
os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
break;
case EV_LOST_TSYNC:
Serial.println("EV_LOST_TSYNC");
break;
case EV_RESET:
Serial.println("EV_RESET");
break;
case EV_RXCOMPLETE:
// data received in ping slot
Serial.println("EV_RXCOMPLETE");
break;
case EV_LINK_DEAD:
Serial.println("EV_LINK_DEAD");
break;
case EV_LINK_ALIVE:
Serial.println("EV_LINK_ALIVE");
break;
default:
Serial.println("Unknown event");
break;
}
}
void setup() {
// initialize digital pin as an output.
Serial.begin(9600);
ss.begin(9600);
while(!Serial);
Serial.println("LoRa GPS Example---- ");
Serial.println("Connect to TTN");
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif // LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
/*LMIC_setClockError(MAX_CLOCK_ERROR * 1/100);
Set static session parameters. Instead of dynamically establishing a session
by joining the network, precomputed session parameters are be provided.*/
#ifdef PROGMEM
/* On AVR, these values are stored in flash and only copied to RAM
once. Copy them to a temporary buffer here, LMIC_setSession will
copy them into a buffer of its own again.*/
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif // Disable link check validation
LMIC_setLinkCheckMode(0); // TTN uses SF9 for its RX2 window.
LMIC.dn2Dr = DR_SF9; // Set data rate and transmit power (note: txpow seems to be ignored by the library)
LMIC_setDrTxpow(DR_SF7,14); // Start job
do_send(&sendjob);
}void GPSRead()
{
unsigned long age;
gps.f_get_position(&flat, &flon, &age);
falt=gps.f_altitude(); //get altitude
flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6;
flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6;//save six decimal places
falt == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : falt, 2;//save two decimal places
}
void GPSWrite()
{
/*Convert GPS data to format*/
datastring1 +=dtostrf(flat, 0, 4, gps_lat);
datastring2 +=dtostrf(flon, 0, 4, gps_lon);
//datastring3 +=dtostrf(falt, 0, 2, gps_alt);
if(flon!=1000.000000)
{
strcat(gps_lon,",");
strcat(gps_lon,gps_lat);
//strcat(gps_lon,",");
//strcat(gps_lon,gps_alt);
int i = 0;
for(i = 0; i < 2; i++)
{
//datasend.toFloat();
atof(gps_lon);
//Serial.println((char*)datasend);
Serial.println("Testing converted data:");
Serial.println(gps_lon);
// atof(gps_alt);
// Serial.print(gps_alt);
} strcpy(datasend,gps_lon); //the format of datasend is longtitude,latitude,altitude
Serial.print("########### ");
Serial.print("NO.");
Serial.print(count);
Serial.println(" ###########");
Serial.println("The longtitude and latitude are:");
Serial.print("[");
Serial.print((char*)datasend);
Serial.print("]");
Serial.print("");
/*
for(int k = 0; k < 20;k++)
{
Serial.print("[");
Serial.print(datasend[k], HEX);
Serial.print("]");
}
Serial.println("");
Serial.println("");*/
count++;
} int32_t lng = flat * 10000;
int32_t lat = flon * 10000; datasend[0] = lat;
datasend[1] = lat >> 8;
datasend[2] = lat >> 16; datasend[3] = lng;
datasend[4] = lng >> 8;
datasend[5] = lng >> 16;
smartdelay(1000);
}static void smartdelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (ss.available())
{
gps.encode(ss.read());
}
} while (millis() - start < ms);
}
void loop() {
os_runloop_once();
}