forked from thomaslhotta/arduino-stepper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharduino-stepper.ino
337 lines (265 loc) · 7.9 KB
/
arduino-stepper.ino
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
#include <CustomStepper.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal
#include <WiFiManager.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#include <FS.h>
#include <DoubleResetDetector.h>
// Number of seconds after reset during which a
// subseqent reset will be considered a double reset.
#define DRD_TIMEOUT 3
// RTC Memory Address for the DoubleResetDetector to use
#define DRD_ADDRESS 0
DoubleResetDetector drd(DRD_TIMEOUT, DRD_ADDRESS);
#define SENSOR_PWR_PIN 4
#define SENSOR_IN_PIN 5
#define SWITCH_PIN = 5;
struct {
int check;
int pos;
} currentPosition;
// Config variables
char domain[100];
char path[200];
// Working variables
bool shouldSaveConfig = false;
bool zeroingMode = false;
int targetPosition = 0;
CustomStepper stepper( 14, 12, 13, 15 );
WiFiClientSecure client;
/**
* Commands to the indicator to move to the zero position
*/
void setToZero() {
Serial.println( "setting to 0" );
pinMode( SENSOR_PWR_PIN, OUTPUT );
pinMode( SENSOR_IN_PIN, INPUT );
Serial.print( "setting to 0" );
delay(1000);
digitalWrite( SENSOR_PWR_PIN, HIGH );
delay(1000);
zeroingMode = true;
stepper.setDirection( CW );
stepper.rotate();
}
/**
* Returns the current position of the indicator. If the stored position is invalid the return will be -1
*/
int getCurrentPosition() {
if ( ! ESP.rtcUserMemoryRead( 4, ( uint32_t* ) ¤tPosition, sizeof( currentPosition ) )
|| 359 != ( currentPosition.pos + currentPosition.check ) ) {
return -1;
}
return currentPosition.pos;
}
/**
* Saves the given position to RTC memory.
*/
void saveCurrentPosition( int position ) {
currentPosition.pos = position;
currentPosition.check = 359 - position;
Serial.print( "setting to " );
Serial.println( currentPosition.check );
ESP.rtcUserMemoryWrite( 4, ( uint32_t* ) ¤tPosition, sizeof( currentPosition ) );
}
/**
* Set the indicator to the given position
*/
void setPosition( int deg, int currentPosition ) {
// Check for out of range values
if ( deg < 0 || deg > 359 ) {
Serial.print( "Invalid position: " );
Serial.println( deg );
return;
}
Serial.println( "" );
Serial.print( "Set to: " );
Serial.println( deg );
int currentPos = getCurrentPosition();
Serial.print( "Current: " );
Serial.println( currentPos );
// Do nothing if no rotation is needed
if ( currentPos == deg ) {
Serial.println( "No rotation needed" );
return;
}
int rotate = 0;
if ( currentPos <= deg ) {
rotate = deg - currentPos;
} else {
rotate = 359 - ( currentPos - deg );
}
if ( rotate < 180 ) {
stepper.setDirection( CW );
} else {
stepper.setDirection( CCW );
rotate = 359 - rotate;
}
stepper.rotateDegrees( rotate );
Serial.print( "Rotating: " );
Serial.println( rotate );
}
/**
* Fetches the target position from the configured web server
*/
int getFromServer() {
Serial.println();
Serial.print( F( "connecting to " ) );
Serial.println( domain );
// WiFiClientSecure client;
if ( ! client.connect( domain, 443 ) ) {
Serial.println( F( "connection failed" ) );
return - 1;
}
// We now create a URI for the request
String url = String( "https://" );
url.concat( domain );
url.concat( path );
Serial.print( "Requesting URL: " );
Serial.println( url );
// This will send the request to the server
client.print( String( "GET " ) + url + " HTTP/1.1\r\n" +
"Host: " + domain + "\r\n" +
"Connection: close\r\n\r\n" );
delay( 5000 );
// Needed so available() actually works
client.readStringUntil( '\n' );
while ( client.available() ) {
String line = client.readStringUntil( '\n' );
if ( line == "\r" ) {
Serial.println( "headers received" );
break;
}
}
// Response format => {position: 359}
String l2 = client.readStringUntil( ':' );
// Skip first line of response;
String line = client.readStringUntil( '}' );
Serial.print( "Server said move to " );
Serial.println( line );
return line.toInt();
}
/**
* Loads the configuration from SPIFFS
*/
void loadConfig() {
if ( ! SPIFFS.begin() ) {
Serial.println( "failed to mount FS" );
return;
}
Serial.println( "mounted file system" );
if ( ! SPIFFS.exists( "/config.json" ) ) {
Serial.println( "config.json does not exist" );
return;
}
File configFile = SPIFFS.open( "/config.json", "r" );
if ( ! configFile ) {
Serial.println( "config.json could not be loaded" );
return;
}
Serial.println( "opened config file" );
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if ( ! json.success() ) {
Serial.println( "config.json is invalid" );
return;
}
Serial.println("\nparsed json");
strcpy( domain, json["domain"] );
strcpy( path, json["path"] );
}
/**
* Saves the configuration
*/
void saveConfig() {
Serial.println( "Saving configuration" );
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["domain"] = domain;
json["path"] = path;
File configFile = SPIFFS.open( "/config.json", "w" );
if ( ! configFile ) {
Serial.println( "Failed to open config file for writing" );
}
json.printTo(Serial);
json.printTo(configFile);
configFile.close();
}
/**
* Callback function so set shouldSaveConfig variable
*/
void saveConfigCallback () {
Serial.println( "Should save config" );
shouldSaveConfig = true;
}
void setup() {
Serial.begin( 115200 );
stepper.setRPM( 3 );
stepper.setDirection( CW );
loadConfig();
WiFiManagerParameter custom_domain( "domain", "Domain name e.g. www.kjero.com", domain, 100 );
WiFiManagerParameter custom_path( "path", "Path. e.g /wp-admin/admin-ajax.php?action=stepper&key=YOURKEY", path, 200);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
wifiManager.setSaveConfigCallback( saveConfigCallback );
wifiManager.setDebugOutput(true);
wifiManager.addParameter( &custom_domain );
wifiManager.addParameter( &custom_path );
if ( drd.detectDoubleReset() ) {
wifiManager.startConfigPortal( "Clock display", "kjero_clock" );
ESP.reset();
} else if ( ! wifiManager.autoConnect( "Clock display", "kjero_clock" ) ) {
Serial.println( "failed to connect and hit timeout" );
delay(5000);
ESP.deepSleep( 600 * 1000000 );
}
if ( shouldSaveConfig ) {
strcpy(domain, custom_domain.getValue());
strcpy(path, custom_path.getValue());
saveConfig();
}
//pinMode( switchPin, INPUT_PULLUP );
targetPosition = getFromServer();
int currentPosition = getCurrentPosition();
Serial.print( "Current position:" );
Serial.println( currentPosition );
if ( -1 == currentPosition ) {
setToZero();
} else {
setPosition( targetPosition, currentPosition );
}
}
void loop() {
// Perform stepper motor actions
stepper.run();
// Enable web server and zeroing in AP mode
if ( true == zeroingMode && 100 > analogRead( A0 ) ) {
zeroingMode = false;
stepper.setDirection( STOP );
digitalWrite( SENSOR_PWR_PIN, LOW );
Serial.println( "Zeroing complete" );
saveCurrentPosition(0);
setPosition( targetPosition, 0 );
}
// Enter sleep mode once everything is done
if ( stepper.isDone() ) {
saveCurrentPosition(targetPosition);
// Switch off motor once everything is done to reduce power consumption
digitalWrite( 14, LOW );
digitalWrite( 13, LOW );
digitalWrite( 12, LOW );
digitalWrite( 15, LOW );
Serial.println();
Serial.println( "Going to sleep" );
delay( 1000 );
ESP.deepSleep( 600 * 1000000, WAKE_RF_DEFAULT );
}
}