1+ /* This sketch is used during the getting started tutorial when
2+ initialising a Arduino cloud-enabled board with the Arduino
3+ cloud for the first time.
4+
5+ This sketch is compatible with:
6+ - ESP8266 boards
7+ */
8+
9+ #include < ArduinoIoTCloud.h>
10+ #include < Arduino_ConnectionHandler.h>
11+
12+ #include " arduino_secrets.h"
13+
14+ String cloudSerialBuffer = " " ; // the string used to compose network messages from the received characters
15+ // handles connection to the network
16+ WiFiConnectionHandler ArduinoIoTPreferredConnection (SECRET_WIFI_NAME, SECRET_PASSWORD);
17+
18+ void setup () {
19+ setDebugMessageLevel (3 ); // used to set a level of granularity in information output [0...4]
20+ Serial.begin (9600 );
21+ while (!Serial); // waits for the serial to become available
22+ ArduinoCloud.setBoardId (SECRET_BOARD_ID);
23+ ArduinoCloud.setSecretDeviceKey (SECRET_DEVICE_KEY);
24+ ArduinoCloud.begin (ArduinoIoTPreferredConnection); // initialize a connection to the Arduino IoT Cloud
25+ pinMode (LED_BUILTIN, OUTPUT);
26+ }
27+
28+ void loop () {
29+ ArduinoCloud.update ();
30+ // check if there is something waiting to be read
31+ if (ArduinoCloud.connected ()) {
32+ if (CloudSerial.available ()) {
33+ char character = CloudSerial.read ();
34+ cloudSerialBuffer += character;
35+ // if a \n character has been received, there should be a complete command inside cloudSerialBuffer
36+ if (character == ' \n ' ) {
37+ handleString ();
38+ }
39+ } else { // if there is nothing to read, it could be that the last command didn't end with a '\n'. Check.
40+ handleString ();
41+ }
42+ // Just to be able to simulate the board responses through the serial monitor
43+ if (Serial.available ()) {
44+ CloudSerial.write (Serial.read ());
45+ }
46+ }
47+ }
48+ void handleString () {
49+ // Don't proceed if the string is empty
50+ if (cloudSerialBuffer.equals (" " )) {
51+ return ;
52+ }
53+ // Remove leading and trailing whitespaces
54+ cloudSerialBuffer.trim ();
55+ // Make it uppercase;
56+ cloudSerialBuffer.toUpperCase ();
57+ if (cloudSerialBuffer.equals (" ON" )) {
58+ digitalWrite (LED_BUILTIN, HIGH);
59+ } else if (cloudSerialBuffer.equals (" OFF" )) {
60+ digitalWrite (LED_BUILTIN, LOW);
61+ }
62+ sendString (cloudSerialBuffer);
63+ // Reset cloudSerialBuffer
64+ cloudSerialBuffer = " " ;
65+ }
66+ // sendString sends a string to the Arduino Cloud.
67+ void sendString (String stringToSend) {
68+ // send the characters one at a time
69+ char lastSentChar = 0 ;
70+ for (unsigned int i = 0 ; i < stringToSend.length (); i++) {
71+ lastSentChar = stringToSend.charAt (i);
72+ CloudSerial.write (lastSentChar);
73+ }
74+ // if the last sent character wasn't a '\n' add it
75+ if (lastSentChar != ' \n ' ) {
76+ CloudSerial.write (' \n ' );
77+ }
78+ }
0 commit comments