Skip to content

Commit 18366cc

Browse files
committed
Minor refactoring
1. readBytesUntil => readStringUntil 2. Moved certain globals to local 3. Declaring variables closer to their respective uses, unless declaring at top provides easy configurability 4. Avoid publishing in case of conlost
1 parent 96f96d5 commit 18366cc

File tree

1 file changed

+11
-19
lines changed

1 file changed

+11
-19
lines changed

sketches/arduino_sample_sketch.ino

+11-19
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,13 @@
11
#include <SoftwareSerial.h>
22

3-
SoftwareSerial mySerial(8, 9); // RX, TX
3+
#define SERIAL_RX_PIN 8
4+
#define SERIAL_TX_PIN 9
45

56
#define EVENT_PIN 2
67
#define RESET_PIN 4
78

89
#define MY_AWS_IOT_ENDPOINT "<hash>-ats.iot.<region>.amazonaws.com"
910

10-
#define HOST_RESPONSE_BUFFER_SIZE 500
11-
12-
char buffer[HOST_RESPONSE_BUFFER_SIZE];
13-
1411
typedef enum event_t {
1512
EVENT_NONE = 0,
1613
EVENT_STARTUP = 2,
@@ -31,18 +28,12 @@ typedef enum {
3128
STATE_CONNECTED,
3229
} state_t;
3330

34-
static state_t state;
35-
static unsigned long got_connected;
36-
static unsigned long saved_timeout_value_ms;
37-
3831
String execute_command(String command, unsigned long timeout_ms)
3932
{
40-
saved_timeout_value_ms = Serial.getTimeout();
33+
unsigned long saved_timeout_value_ms = Serial.getTimeout();
4134
Serial.setTimeout(timeout_ms);
42-
memset(buffer, 0, HOST_RESPONSE_BUFFER_SIZE);
4335
Serial.println(command);
44-
Serial.readBytesUntil('\n', buffer, HOST_RESPONSE_BUFFER_SIZE);
45-
String s(buffer);
36+
String s = Serial.readStringUntil('\n');
4637
s.trim();
4738
Serial.setTimeout(saved_timeout_value_ms);
4839
return s;
@@ -99,7 +90,7 @@ state_t process_ssid(String response)
9990

10091
void setup()
10192
{
102-
state = STATE_INIT;
93+
SoftwareSerial mySerial(SERIAL_RX_PIN, SERIAL_TX_PIN);
10394
Serial.begin(115200);
10495
mySerial.begin(115200);
10596
pinMode(EVENT_PIN, INPUT);
@@ -110,14 +101,13 @@ void setup()
110101
while (!mySerial) {
111102
;
112103
}
113-
got_connected = 0;
114-
saved_timeout_value_ms = 0;
115104
}
116105

117106
void loop()
118107
{
119108
event_t event = EVENT_NONE;
120109
String response;
110+
static state_t state = STATE_INIT;
121111

122112
if (state != STATE_INIT)
123113
{
@@ -170,12 +160,14 @@ void loop()
170160
if (event == EVENT_CONLOST)
171161
{
172162
state = STATE_PROVISIONED;
163+
break;
173164
}
174-
if (millis() - got_connected >= 10000)
165+
static unsigned long last_send_time;
166+
if (millis() - last_send_time >= 10000)
175167
{
176168
response = execute_command("AT+SEND1 Hello World", 5000);
177-
got_connected = millis();
169+
last_send_time = millis();
178170
}
179171
break;
180172
}
181-
}
173+
}

0 commit comments

Comments
 (0)