-
Notifications
You must be signed in to change notification settings - Fork 216
/
ThingSpeak.h
1451 lines (1328 loc) · 52.5 KB
/
ThingSpeak.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
ThingSpeak(TM) Communication Library For Arduino
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.
ThingSpeak ( https://www.thingspeak.com ) is a free IoT service for building
systems that collect, analyze, and react to their environments.
Copyright 2015, The MathWorks, Inc.
See the accompaning licence file for licensing information.
*/
/**
@mainpage
*
* \ref ThingSpeakClass "For technical documentation, visit this page"
*
* ThingSpeak offers free data storage and analysis of time-stamped numeric or alphanumeric data.
* Users can access ThingSpeak by visiting http://thingspeak.com and creating a ThingSpeak user account.
*
* ThingSpeak stores data in channels. Channels support an unlimited number of timestamped observations (think of these as rows in a spreadsheet).
* Each channel has up to 8 fields (think of these as columns in a speadsheet).
*
* Channels may be public, where anyone can see the data, or private, where only the owner and select users can read the data.
* Each channel has an associated Write API Key that is used to control who can write to a channel.
* In addition, private channels have one or more Read API Keys to control who can read from private channel.
* An API Key is not required to read from public channels. Each channel can have up to 8 fields. One field is created by default.
*
* You can visualize and do online analytics of your data on ThingSpeak using the built in version of MATLAB, or use the desktop version of MATLAB to get
* deeper historical insight. Visit https://www.mathworks.com/hardware-support/thingspeak.html to learn more.
*
* <h3>Compatible Hardware</h3>
* * <a href="http://www.arduino.cc">Arduino</a> or compatible using a wired or Wi-Fi ethernet shield (we have tested with <a href="http://www.arduino.cc/en/Main/ArduinoBoardUno">Uno</a> and <a href="http://www.arduino.cc/en/Main/ArduinoBoardMega2560">Mega</a>)
* * <a href="http://www.arduino.cc/en/Main/ArduinoBoardYun">Arduino Yun</a> running OpenWRT-Yun Release 1.5.3 (November 13th, 2014) or later. There are known issues with earlier versions. Visit [this page](http://www.arduino.cc/en/Main/Software) to get the latest version.
* * Particle <a href="https://store.particle.io/?product=spark-core">Core</a> or <a href="https://store.particle.io/?product=particle-photon">Photon</a> (Formally Spark)
*
* <h3>Examples</h3>
* The library includes several examples to help you get started. These are accessible in the Examples/ThingSpeak menu off the File menu in the Arduino IDE.
* * <b>CheerLights:</b> Reads the latest <a href="http://www.cheerlights.com">CheerLights</a> color on ThingSpeak, and sets an RGB LED.
* * <b>ReadLastTemperature:</b> Reads the latest temperature from the public <a href="https://thingspeak.com/channels/12397">MathWorks weather station</a> in Natick, MA on ThingSpeak.
* * <b>ReadPrivateChannel:</b> Reads the latest voltage value from a private channel on ThingSpeak.
* * <b>ReadWeatherStation:</b> Reads the latest weather data from the public <a href="https://thingspeak.com/channels/12397">MathWorks weather station</a> in Natick, MA on ThingSpeak.
* * <b>WriteMultipleVoltages:</b> Reads analog voltages from pins 0-7 and writes them to the 8 fields of a channel on ThingSpeak.
* * <b>WriteVoltage:</b> Reads an analog voltage from pin 0, converts to a voltage, and writes it to a channel on ThingSpeak.
*/
#ifndef ThingSpeak_h
#define ThingSpeak_h
//#define PRINT_DEBUG_MESSAGES
//#define PRINT_HTTP
#include "Arduino.h"
#include <Client.h>
#define THINGSPEAK_URL "api.thingspeak.com"
#define THINGSPEAK_IPADDRESS IPAddress(184,106,153,149)
#define THINGSPEAK_PORT_NUMBER 80
#define TS_USER_AGENT "tslib-arduino/1.0 (ESP8266 Basic)"
#define FIELDNUM_MIN 1
#define FIELDNUM_MAX 8
#define FIELDLENGTH_MAX 255 // Max length for a field in ThingSpeak is 255 bytes (UTF-8)
#define TIMEOUT_MS_SERVERRESPONSE 5000 // Wait up to five seconds for server to respond
#define OK_SUCCESS 200 // OK / Success
#define ERR_BADAPIKEY 400 // Incorrect API key (or invalid ThingSpeak server address)
#define ERR_BADURL 404 // Incorrect API key (or invalid ThingSpeak server address)
#define ERR_OUT_OF_RANGE -101 // Value is out of range or string is too long (> 255 bytes)
#define ERR_INVALID_FIELD_NUM -201 // Invalid field number specified
#define ERR_SETFIELD_NOT_CALLED -210 // setField() was not called before writeFields()
#define ERR_CONNECT_FAILED -301 // Failed to connect to ThingSpeak
#define ERR_UNEXPECTED_FAIL -302 // Unexpected failure during write to ThingSpeak
#define ERR_BAD_RESPONSE -303 // Unable to parse response
#define ERR_TIMEOUT -304 // Timeout waiting for server to respond
#define ERR_NOT_INSERTED -401 // Point was not inserted (most probable cause is the rate limit of once every 15 seconds)
/**
* @brief This library 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.
*/
class ThingSpeakClass
{
public:
ThingSpeakClass()
{
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
};
/**
* @brief Initializes the ThingSpeak library and network settings using a custom installation of ThingSpeak.
* @param client EthernetClient, YunClient, TCPClient, or WiFiClient created earlier in the sketch
* @param customHostName Host name of a custom install of ThingSpeak
* @param port Port number to use with a custom install of ThingSpeak
* @return Always returns true
* @comment This does not validate the information passed in, or generate any calls to ThingSpeak.
* @code
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetClient client;
#include "ThingSpeak.h"
void setup() {
Ethernet.begin(mac);
ThingSpeak.begin(client,"api.thingspeak.com", 80);
}
* @endcode
*/
bool begin(Client & client, const char * customHostName, unsigned int port)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::tsBegin (client: Client URL: "); Serial.print(customHostName); Serial.println(")");
#endif
this->setClient(&client);
this->setServer(customHostName, port);
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
return true;
};
/**
* @brief Initializes the ThingSpeak library and network settings using a custom installation of ThingSpeak.
* @param client EthernetClient, YunClient, TCPClient, or WiFiClient created earlier in the sketch
* @param customIP IP address of a custom install of ThingSpeak
* @param port Port number to use with a custom install of ThingSpeak
* @return Always returns true
* @comment This does not validate the information passed in, or generate any calls to ThingSpeak.
* @code
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetClient client;
#include "ThingSpeak.h"
void setup() {
Ethernet.begin(mac);
ThingSpeak.begin(client,IPAddress(184,106,153,149), 80);
}
* @endcode
*/
bool begin(Client & client, IPAddress customIP, unsigned int port)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::tsBegin (client: Client IP: "); Serial.print(customIP); Serial.println(")");
#endif
this->setClient(&client);
this->setServer(customIP, port);
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
return true;
};
/**
* @brief Initializes the ThingSpeak library and network settings using the ThingSpeak.com service.
* @param client EthernetClient, YunClient, TCPClient, or WiFiClient created earlier in the sketch
* @return Always returns true
* @comment This does not validate the information passed in, or generate any calls to ThingSpeak.
* @code
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetClient client;
#include "ThingSpeak.h"
void setup() {
Ethernet.begin(mac);
ThingSpeak.begin(client);
}
* @endcode
*/
bool begin(Client & client)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::tsBegin");
#endif
this->setClient(&client);
this->setServer();
resetWriteFields();
this->lastReadStatus = OK_SUCCESS;
return true;
};
/**
* @brief Write an integer value to a single field in a ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to write to.
* @param value Integer value (from -32,768 to 32,767) to write.
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark Visit https://thingspeak.com/docs/channels for more information about channels, API keys, and fields. ThingSpeak limits the number of writes to a channel to once every 15 seconds.
* @code
void loop() {
int sensorValue = analogRead(A0);
ThingSpeak.writeField(myChannelNumber, 1, sensorValue, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeField(unsigned long channelNumber, unsigned int field, int value, const char * writeAPIKey)
{
#ifdef SPARK
// On Spark, int and long are the same, so map to the long version
return writeField(channelNumber, field, (long)value, writeAPIKey);
#else
char valueString[10]; // int range is -32768 to 32768, so 7 bytes including terminator, plus a little extra
itoa(value, valueString, 10);
return writeField(channelNumber, field, valueString, writeAPIKey);
#endif
};
/**
* @brief Write a long value to a single field in a ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to write to.
* @param value Long value (from -2,147,483,648 to 2,147,483,647) to write.
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark Visit https://thingspeak.com/docs/channels for more information about channels, API keys, and fields. ThingSpeak limits the number of writes to a channel to once every 15 seconds.
* @code
void loop() {
int sensorValue = analogRead(A0);
ThingSpeak.writeField(myChannelNumber, 1, sensorValue, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeField(unsigned long channelNumber, unsigned int field, long value, const char * writeAPIKey)
{
char valueString[15]; // long range is -2147483648 to 2147483647, so 12 bytes including terminator
ltoa(value, valueString, 10);
return writeField(channelNumber, field, valueString, writeAPIKey);
};
/**
* @brief Write a floating point value to a single field in a ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to write to.
* @param value Floating point value (from -999999000000 to 999999000000) to write. If you need more accuracy, or a wider range, you should format the number using <tt>dtostrf</tt> and writeField().
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark Visit https://thingspeak.com/docs/channels for more information about channels, API keys, and fields. ThingSpeak limits the number of writes to a channel to once every 15 seconds.
* @code
void loop() {
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);
ThingSpeak.writeField(myChannelNumber, 1, voltage, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeField(unsigned long channelNumber, unsigned int field, float value, const char * writeAPIKey)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::writeField (channelNumber: "); Serial.print(channelNumber); Serial.print(" writeAPIKey: "); Serial.print(writeAPIKey); Serial.print(" field: "); Serial.print(field); Serial.print(" value: "); Serial.print(value,5); Serial.println(")");
#endif
char valueString[20]; // range is -999999000000.00000 to 999999000000.00000, so 19 + 1 for the terminator
int status = convertFloatToChar(value, valueString);
if(status != OK_SUCCESS) return status;
return writeField(channelNumber, field, valueString, writeAPIKey);
};
/**
* @brief Write a string to a single field in a ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to write to.
* @param value String to write (UTF8 string). ThingSpeak limits this field to 255 bytes.
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark Visit https://thingspeak.com/docs/channels for more information about channels, API keys, and fields. ThingSpeak limits the number of writes to a channel to once every 15 seconds.
* @code
void loop() {
int sensorValue = analogRead(A0);
if (sensorValue > 512) {
ThingSpeak.writeField(myChannelNumber, 1, "High", myWriteAPIKey);
}
else {
ThingSpeak.writeField(myChannelNumber, 1, "Low", myWriteAPIKey);
}
delay(20000);
}
* @endcode
*/
int writeField(unsigned long channelNumber, unsigned int field, const char * value, const char * writeAPIKey)
{
return writeField(channelNumber, field, String(value), writeAPIKey);
};
/**
* @brief Write a String to a single field in a ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to write to.
* @param value Character array (zero terminated) to write (UTF8). ThingSpeak limits this field to 255 bytes.
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark Visit https://thingspeak.com/docs/channels for more information about channels, API keys, and fields. ThingSpeak limits the number of writes to a channel to once every 15 seconds.
* @code
void loop() {
int sensorValue = analogRead(A0);
String meaning;
if (sensorValue < 400) {
meaning = String("Too Cold!");
} else if (sensorValue > 600) {
meaning = String("Too Hot!");
} else {
meaning = String("Just Right");
}
ThingSpeak.writeField(myChannelNumber, 1, meaning, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeField(unsigned long channelNumber, unsigned int field, String value, const char * writeAPIKey)
{
// Invalid field number specified
if(field < FIELDNUM_MIN || field > FIELDNUM_MAX) return ERR_INVALID_FIELD_NUM;
// Max # bytes for ThingSpeak field is 255
if(value.length() > FIELDLENGTH_MAX) return ERR_OUT_OF_RANGE;
#ifdef PRINT_DEBUG_MESSAGES
#ifdef SPARK
Spark.publish(SPARK_PUBLISH_TOPIC, "writeField (" + String(channelNumber) + ", " + String(writeAPIKey) + ", " + String(field) + ", " + String(value) + ")", SPARK_PUBLISH_TTL, PRIVATE);
#else
Serial.print("ts::writeField (channelNumber: "); Serial.print(channelNumber); Serial.print(" writeAPIKey: "); Serial.print(writeAPIKey); Serial.print(" field: "); Serial.print(field); Serial.print(" value: \""); Serial.print(value); Serial.println("\")");
#endif
#endif
String postMessage = String("field") + String(field) + "=" + value;
return writeRaw(channelNumber, postMessage, writeAPIKey);
};
/**
* @brief Set the value of a single field that will be part of a multi-field update.
* To write multiple fields at once, call setField() for each of the fields you want to write, and then call writeFields()
* @param field Field number (1-8) within the channel to set
* @param value Integer value (from -32,768 to 32,767) to set.
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setLatitude(), setLongitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setField(unsigned int field, int value)
{
#ifdef SPARK
// On Spark, int and long are the same, so map to the long version
return setField(field, (long)value);
#else
char valueString[10]; // int range is -32768 to 32768, so 7 bytes including terminator
itoa(value, valueString, 10);
return setField(field, valueString);
#endif
};
/**
* @brief Set the value of a single field that will be part of a multi-field update.
* To write multiple fields at once, call setField() for each of the fields you want to write, and then call writeFields()
* @param field Field number (1-8) within the channel to set
* @param value Long value (from -2,147,483,648 to 2,147,483,647) to write.
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setLatitude(), setLongitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setField(unsigned int field, long value)
{
char valueString[15]; // long range is -2147483648 to 2147483647, so 12 bytes including terminator
ltoa(value, valueString, 10);
return setField(field, valueString);
};
/**
* @brief Set the value of a single field that will be part of a multi-field update.
* To write multiple fields at once, call setField() for each of the fields you want to write, and then call writeFields()
* @param field Field number (1-8) within the channel to set
* @param value Floating point value (from -999999000000 to 999999000000) to write. If you need more accuracy, or a wider range, you should format the number yourself (using <tt>dtostrf</tt>) and setField() using the resulting string.
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setLatitude(), setLongitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setField(unsigned int field, float value)
{
char valueString[20]; // range is -999999000000.00000 to 999999000000.00000, so 19 + 1 for the terminator
int status = convertFloatToChar(value, valueString);
if(status != OK_SUCCESS) return status;
return setField(field, valueString);
};
/**
* @brief Set the value of a single field that will be part of a multi-field update.
* To write multiple fields at once, call setField() for each of the fields you want to write, and then call writeFields()
* @param field Field number (1-8) within the channel to set
* @param value String to write (UTF8). ThingSpeak limits this to 255 bytes.
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setLatitude(), setLongitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setField(unsigned int field, const char * value)
{
return setField(field, String(value));
};
/**
* @brief Set the value of a single field that will be part of a multi-field update.
* To write multiple fields at once, call setField() for each of the fields you want to write, and then call writeFields()
* @param field Field number (1-8) within the channel to set
* @param value String to write (UTF8). ThingSpeak limits this to 255 bytes.
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setLatitude(), setLongitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setField(unsigned int field, String value)
{
#ifdef PRINT_DEBUG_MESSAGES
#ifdef SPARK
Spark.publish(SPARK_PUBLISH_TOPIC, "setField " + String(field) + " to " + String(value), SPARK_PUBLISH_TTL, PRIVATE);
#else
Serial.print("ts::setField (field: "); Serial.print(field); Serial.print(" value: \""); Serial.print(value); Serial.println("\")");
#endif
#endif
if(field < FIELDNUM_MIN || field > FIELDNUM_MAX) return ERR_INVALID_FIELD_NUM;
// Max # bytes for ThingSpeak field is 255 (UTF-8)
if(value.length() > FIELDLENGTH_MAX) return ERR_OUT_OF_RANGE;
this->nextWriteField[field - 1] = value;
return OK_SUCCESS;
};
/**
* @brief Set the latitude of a multi-field update.
* To record latitude, longitude and elevation of a write, call setField() for each of the fields you want to write, setLatitude() / setLongitude() / setElevation(), and then call writeFields()
* @param latitude Latitude of the measurement (degrees N, use negative values for degrees S)
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setField(), setLongitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
setLatitude(42.2833);
setLongitude(-71.3500);
setElevation(100);
delay(20000);
}
* @endcode
*/
int setLatitude(float latitude)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::setLatitude(latitude: "); Serial.print(latitude,3); Serial.println("\")");
#endif
this->nextWriteLatitude = latitude;
return OK_SUCCESS;
};
/**
* @brief Set the longitude of a multi-field update.
* To record latitude, longitude and elevation of a write, call setField() for each of the fields you want to write, setLatitude() / setLongitude() / setElevation(), and then call writeFields()
* @param longitude Longitude of the measurement (degrees E, use negative values for degrees W)
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setField(), setLatitude(), setElevation(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
setLatitude(42.2833);
setLongitude(-71.3500);
setElevation(100);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setLongitude(float longitude)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::setLongitude(longitude: "); Serial.print(longitude,3); Serial.println("\")");
#endif
this->nextWriteLongitude = longitude;
return OK_SUCCESS;
};
/**
* @brief Set the elevation of a multi-field update.
* To record latitude, longitude and elevation of a write, call setField() for each of the fields you want to write, setLatitude() / setLongitude() / setElevation(), and then call writeFields()
* @param elevation Elevation of the measurement (meters above sea level)
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setField(), setLatitude(), setLongitude(), writeFields()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
setLatitude(42.2833);
setLongitude(-71.3500);
setElevation(100);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int setElevation(float elevation)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::setElevation(elevation: "); Serial.print(elevation,3); Serial.println("\")");
#endif
this->nextWriteElevation = elevation;
return OK_SUCCESS;
};
/**
* @brief Write a multi-field update.
* Call setField() for each of the fields you want to write, setLatitude() / setLongitude() / setElevation(), and then call writeFields()
* @param channelNumber Channel number
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @see setField(), setLatitude(), setLongitude(), setElevation()
* @code
void loop() {
int sensor1Value = analogRead(A0);
float sensor2Voltage = analogRead(A1) * (5.0 / 1023.0);
String sensor3Meaning;
int sensor3Value = analogRead(A2);
if (sensor3Value < 400) {
sensor3Meaning = String("Too Cold!");
} else if (sensor3Value > 600) {
sensor3Meaning = String("Too Hot!");
} else {
sensor3Meaning = String("Just Right");
}
long timeRead = millis();
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
setLatitude(42.2833);
setLongitude(-71.3500);
setElevation(100);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeFields(unsigned long channelNumber, const char * writeAPIKey)
{
String postMessage = String("");
bool fFirstItem = true;
for(size_t iField = 0; iField < 8; iField++)
{
delay(0);
if(this->nextWriteField[iField].length() > 0)
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("field") + String(iField + 1) + String("=") + this->nextWriteField[iField];
fFirstItem = false;
this->nextWriteField[iField] = "";
}
}
delay(0);
if(!isnan(nextWriteLatitude))
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("lat=") + String(this->nextWriteLatitude);
fFirstItem = false;
this->nextWriteLatitude = NAN;
}
delay(0);
if(!isnan(this->nextWriteLongitude))
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("long=") + String(this->nextWriteLongitude);
fFirstItem = false;
this->nextWriteLongitude = NAN;
}
delay(0);
if(!isnan(this->nextWriteElevation))
{
if(!fFirstItem)
{
postMessage = postMessage + String("&");
}
postMessage = postMessage + String("elevation=") + String(this->nextWriteElevation);
fFirstItem = false;
this->nextWriteElevation = NAN;
}
delay(0);
if(fFirstItem)
{
// setField was not called before writeFields
return ERR_SETFIELD_NOT_CALLED;
}
return writeRaw(channelNumber, postMessage, writeAPIKey);
};
/**
* @brief Write a raw POST to a ThingSpeak channel
* @param channelNumber Channel number
* @param postMessage Raw URL to write to ThingSpeak as a string. See the documentation at https://thingspeak.com/docs/channels#update_feed.
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark This is low level functionality that will not be required by most users.
* @code
void loop() {
const char postMessage[] = "field1=23&created_at=2014-12-31%2023:59:59";
ThingSpeak.setField(1, sensor1Value);
ThingSpeak.setField(2, sensor2Voltage);
ThingSpeak.setField(3, sensor3Meaning);
ThingSpeak.setField(4, timeRead);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeRaw(unsigned long channelNumber, const char * postMessage, const char * writeAPIKey)
{
return writeRaw(channelNumber, String(postMessage), writeAPIKey);
};
/**
* @brief Write a raw POST to a ThingSpeak channel
* @param channelNumber Channel number
* @param postMessage Raw URL to write to ThingSpeak as a String. See the documentation at https://thingspeak.com/docs/channels#update_feed.
* @param writeAPIKey Write API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return HTTP status code of 200 if successful. See getLastReadStatus() for other possible return values.
* @remark This is low level functionality that will not be required by most users.
* @code
void loop() {
String postMessage = String("field1=23&created_at=2014-12-31%2023:59:59");
ThingSpeak.writeRaw(myChannelNumber, postMessage, myWriteAPIKey);
delay(20000);
}
* @endcode
*/
int writeRaw(unsigned long channelNumber, String postMessage, const char * writeAPIKey)
{
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::writeRaw (channelNumber: "); Serial.print(channelNumber); Serial.print(" writeAPIKey: "); Serial.print(writeAPIKey); Serial.print(" postMessage: \""); Serial.print(postMessage); Serial.println("\")");
#endif
if(!connectThingSpeak())
{
// Failed to connect to ThingSpeak
return ERR_CONNECT_FAILED;
}
postMessage = postMessage + String("&headers=false");
#ifdef PRINT_DEBUG_MESSAGES
#ifdef SPARK
Spark.publish(SPARK_PUBLISH_TOPIC, "Post " + postMessage, SPARK_PUBLISH_TTL, PRIVATE);
#else
Serial.print(" POST \"");Serial.print(postMessage);Serial.println("\"");
#endif
#endif
postMessage = postMessage + String("\n");
delay(0);
// Post data to thingspeak
if(!this->client->print("POST /update HTTP/1.1\n")) return abortWriteRaw();
delay(0);
if(!writeHTTPHeader(writeAPIKey)) return abortWriteRaw();
delay(0);
if(!this->client->print("Content-Type: application/x-www-form-urlencoded\n")) return abortWriteRaw();
delay(0);
if(!this->client->print("Content-Length: ")) return abortWriteRaw();
delay(0);
if(!this->client->print(postMessage.length())) return abortWriteRaw();
delay(0);
if(!this->client->print("\n\n")) return abortWriteRaw();
delay(0);
if(!this->client->print(postMessage)) return abortWriteRaw();
String entryIDText = String();
int status = getHTTPResponse(entryIDText);
if(status != OK_SUCCESS)
{
client->stop();
return status;
}
long entryID = entryIDText.toInt();
#ifdef PRINT_DEBUG_MESSAGES
Serial.print(" Entry ID \"");Serial.print(entryIDText);Serial.print("\" (");Serial.print(entryID);Serial.println(")");
#endif
client->stop();
#ifdef PRINT_DEBUG_MESSAGES
Serial.println("disconnected.");
#endif
if(entryID == 0)
{
// ThingSpeak did not accept the write
status = ERR_NOT_INSERTED;
}
return status;
};
/**
* @brief Read the latest string from a private ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to read from.
* @param readAPIKey Read API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return Value read (UTF8 string), or empty string if there is an error. Use getLastReadStatus() to get more specific information.
* @code
void loop() {
String message = ThingSpeak.readStringField(myChannelNumber, 1, myReadAPIKey);
Serial.print("Latest message is: ");
Serial.println(message);
delay(30000);
}
* @endcode
*/
String readStringField(unsigned long channelNumber, unsigned int field, const char * readAPIKey)
{
if(field < FIELDNUM_MIN || field > FIELDNUM_MAX)
{
this->lastReadStatus = ERR_INVALID_FIELD_NUM;
return("");
}
#ifdef PRINT_DEBUG_MESSAGES
Serial.print("ts::readStringField(channelNumber: "); Serial.print(channelNumber);
if(NULL != readAPIKey)
{
Serial.print(" readAPIKey: "); Serial.print(readAPIKey);
}
Serial.print(" field: "); Serial.print(field); Serial.println(")");
#endif
delay(0);
return readRaw(channelNumber, String(String("/fields/") + String(field) + String("/last")), readAPIKey);
}
/**
* @brief Read the latest string from a public ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to read from.
* @return Value read (UTF8), or empty string if there is an error. Use getLastReadStatus() to get more specific information.
* @code
void loop() {
String message = ThingSpeak.readStringField(myChannelNumber, 1);
Serial.print("Latest message is: ");
Serial.println(message);
delay(30000);
}
* @endcode
*/
String readStringField(unsigned long channelNumber, unsigned int field)
{
return readStringField(channelNumber, field, NULL);
};
/**
* @brief Read the latest float from a private ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to read from.
* @param readAPIKey Read API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return Value read, or 0 if the field is text or there is an error. Use getLastReadStatus() to get more specific information. Note that NAN, INFINITY, and -INFINITY are valid results.
* @code
void loop() {
float voltage = ThingSpeak.readFloatField(myChannelNumber, 1, myReadAPIKey);
Serial.print("Latest voltage is: ");
Serial.print(voltage);
Serial.println("V");
delay(30000);
}
* @endcode
*/
float readFloatField(unsigned long channelNumber, unsigned int field, const char * readAPIKey)
{
return convertStringToFloat(readStringField(channelNumber, field, readAPIKey));
};
/**
* @brief Read the latest float from a public ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to read from.
* @return Value read, or 0 if the field is text or there is an error. Use getLastReadStatus() to get more specific information. Note that NAN, INFINITY, and -INFINITY are valid results.
* @code
void loop() {
float voltage = ThingSpeak.readFloatField(myChannelNumber, 1);
Serial.print("Latest voltage is: ");
Serial.print(voltage);
Serial.println("V");
delay(30000);
}
* @endcode
*/
float readFloatField(unsigned long channelNumber, unsigned int field)
{
return readFloatField(channelNumber, field, NULL);
};
/**
* @brief Read the latest long from a private ThingSpeak channel
* @param channelNumber Channel number
* @param field Field number (1-8) within the channel to read from.
* @param readAPIKey Read API key associated with the channel. *If you share code with others, do _not_ share this key*
* @return Value read, or 0 if the field is text or there is an error. Use getLastReadStatus() to get more specific information.
* @code
void loop() {
long value = ThingSpeak.readLongField(myChannelNumber, 1, myReadAPIKey);
Serial.print("Latest value is: ");
Serial.print(value);
delay(30000);
}
* @endcode
*/
long readLongField(unsigned long channelNumber, unsigned int field, const char * readAPIKey)
{
// Note that although the function is called "toInt" it really returns a long.