-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathR2UppitySpinnerV3.ino
4192 lines (3881 loc) · 130 KB
/
R2UppitySpinnerV3.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
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
/*
* --------------------------------------------------------------------
* R2UppitySpinnerV3 (https://github.com/reeltwo/R2UppitySpinnerV3)
* --------------------------------------------------------------------
* Written by Mimir Reynisson (skelmir)
*
* R2UppitySpinnerV3 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* R2UppitySpinnerV3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with R2UppitySpinnerV3; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#ifdef SOC_LEDC_SUPPORT_HS_MODE
#define LEDC_CHANNELS (SOC_LEDC_CHANNEL_NUM<<1)
#else
#define LEDC_CHANNELS (SOC_LEDC_CHANNEL_NUM)
#endif
extern uint8_t channels_resolution[LEDC_CHANNELS];
///////////////////////////////////
#if __has_include("build_version.h")
#include "build_version.h"
#else
#define BUILD_VERSION "custom"
#endif
#if __has_include("reeltwo_build_version.h")
#include "reeltwo_build_version.h"
#endif
///////////////////////////////////
#define USE_DEBUG
// #define USE_SMQDEBUG
#define USE_DROID_REMOTE // Define for droid remote support
#define USE_WIFI // Define to WiFi Support
#define USE_WIFI_WEB // Define for configuration website
#define USE_WIFI_MARCDUINO // Define to enable Marcudino command handler on port 2000
#define USE_MDNS // Define for mDNS support
#define USE_OTA // Define for OTA support
// Define if using Uppity Spinner PCB with SD Card
//#define USE_SDCARD // Define SD card support
// #define DISABLE_ROTARY
///////////////////////////////////
// CONFIGURABLE OPTIONS
///////////////////////////////////
#ifdef USE_DROID_REMOTE
#define REMOTE_ENABLED true
#define SMQ_HOSTNAME "R2Uppity"
#define SMQ_SECRET "Astromech"
#endif
// Replace with your network credentials
#ifdef USE_WIFI
#define WIFI_ENABLED true
// Set these to your desired credentials.
#define WIFI_AP_NAME "R2Uppity"
#define WIFI_AP_PASSPHRASE "Astromech"
#define WIFI_ACCESS_POINT true /* true if access point: false if joining existing wifi */
#endif
#define MARC_SERIAL_ENABLED true
#define MARC_WIFI_ENABLED false
///////////////////////////////////
#define SERIAL_BAUD_RATE 9600
#define CONSOLE_BUFFER_SIZE 300
#define COMMAND_BUFFER_SIZE 256
#define ROTARY_THROTTLE_ACCELERATION_SCALE 100
#define ROTARY_THROTTLE_DECELERATION_SCALE 20
#define ROTARY_THROTTLE_LATENCY 25
#define ROTARY_FUDGE_POSITION 5
// Default random duration of 'M' movement mode
#define MOVEMODE_MIN_DURATION 30 // minimum 30 seconds
#define MOVEMODE_MAX_DURATION 30 // random range additional 30 seconds
#define MOVEMODE_MAX_INTERVAL 5 // default interval between random commands
///////////////////////////////////
// RISKIER CONFIGURATION OPTIONS
///////////////////////////////////
// IA-Parts lifter defaults
#define IAPARTS_LIFTER_MINIMUM_POWER 30 // 30 out of 100. Don't bother with lower values. Won't lift reliably
#define IAPARTS_LIFTER_SEEKBOTTTOM_POWER 30 // 30 out of 100. Lower than LIFTER_MINIMUM_POWER because we are going down
#define IAPARTS_ROTARY_MINIMUM_POWER 20 // 20 out of 100. Don't bother with lower values. Won't rotate reliably
#define IAPARTS_LIFTER_DISTANCE 845 // default value - lifter will calibrate
// Greg Hulette’s Periscope Lifter
#define GREG_LIFTER_MINIMUM_POWER 65 // 65 out of 100. Don't bother with lower values. Won't lift reliably
#define GREG_LIFTER_SEEKBOTTTOM_POWER 40 // 40 out of 100. Lower than LIFTER_MINIMUM_POWER because we are going down
#define GREG_ROTARY_MINIMUM_POWER 40 // 40 out of 100. Don't bother with lower values. Won't rotate reliably
#define GREG_LIFTER_DISTANCE 450 // default value 450 - lifter will calibrate
// lifter defaults
#define DEFAULT_LIFTER_MINIMUM_POWER IAPARTS_LIFTER_MINIMUM_POWER
#define DEFAULT_LIFTER_SEEKBOTTTOM_POWER IAPARTS_LIFTER_SEEKBOTTTOM_POWER
#define DEFAULT_ROTARY_MINIMUM_POWER IAPARTS_ROTARY_MINIMUM_POWER
#define DEFAULT_LIFTER_DISTANCE IAPARTS_LIFTER_DISTANCE
#define DEFAULT_ROTARY_MINIMUM_HEIGHT DEFAULT_LIFTER_DISTANCE/2
#define MOTOR_TIMEOUT 2000
#define OUTPUT_LIMIT_PRESCALE 3.1
#define DISTANCE_OUTPUT_SCALE 3
#define MAX_COMMANDS 100
#define COMMAND_SERIAL Serial2
///////////////////////////////////
// This option is for builders working on their own custom lifters.
// It will leave the lifter logic intact but act as if there is no rotary.
///////////////////////////////////
//#define DISABLE_ROTARY
///////////////////////////////////
#ifdef DISABLE_ROTARY
// DO NOT ENABLE THIS UNLESS YOU REMOVE THE ROTARY UNIT
#define DISABLE_SAFETY_MANEUVER
#endif
#include "pin-map.h"
//////////////////////////////
// LIGHT KIT TRI-STATE
//////////////////////////////
// A B C
// OPEN OPEN OPEN (Switch Position 0): Full Cycle (default): This routine will randomly select the LED
// color, pattern, and speed for a random period of time.
// OPEN OPEN GND (Switch Position 1): Off: This setting turns ALL lights OFF. I added this to allow a
// microcontroller to turn off the lights without having to kill
// the supply power.
// OPEN GND OPEN (Switch Position 2): Obi Wan: The Top LED’s flash Blue, the Side LED’s are Blue,
// and the Main White LED’s are Random.
// OPEN GND GND (Switch Position 3): Yoda: The Top LED’s and Side LED’s fade Green On and Off.
// GND OPEN OPEN (Switch Position 4): Sith: The Top LED’s and Side LED’s flash Red.
// GND OPEN GND (Switch Position 5): Search Light: All LED’s are White, the Center Bright LED is ON.
// GND GND OPEN (Switch Position 6): Dagobah: This is the most screen accurate mode.
// The Main White LED’s are ON, the side LED’s are White, the Lower
// Rectangular Red LED’s are All On, and the Rear LED’s are Blinking Red.
// GND GND GND (Switch Position 7): Sparkle: All White LED’s randomly Flash
///////////////////////////////////
#define PREFERENCE_REMOTE_ENABLED "remote"
#define PREFERENCE_REMOTE_HOSTNAME "rhost"
#define PREFERENCE_REMOTE_SECRET "rsecret"
#define PREFERENCE_REMOTE_PAIRED "rpaired"
#define PREFERENCE_REMOTE_LMK "rlmk"
#define PREFERENCE_WIFI_ENABLED "wifi"
#define PREFERENCE_WIFI_SSID "ssid"
#define PREFERENCE_WIFI_PASS "pass"
#define PREFERENCE_WIFI_AP "ap"
#define PREFERENCE_MARCSERIAL "mserial"
#define PREFERENCE_MARCWIFI_ENABLED "mwifi"
#define PREFERENCES_PARAM_LIFTER_MINIMUM_POWER "lftminpwr"
#define PREFERENCES_PARAM_LIFTER_SEEKBOT_POWER "lftseekbotpwr"
#define PREFERENCES_PARAM_ROTARY_MINIMUM_POWER "rotminpwr"
#define PREFERENCES_PARAM_LIFTER_DISTANCE "lftdist"
#define PREFERENCES_PARAM_ROTARY_MININUM_HEIGHT "minheight"
///////////////////////////////////
#ifdef USE_DROID_REMOTE
#include "ReelTwoSMQ32.h"
#else
#include "ReelTwo.h"
#endif
#include "core/SetupEvent.h"
#include "core/AnimatedEvent.h"
//#include "core/AnalogWrite.h"
#include "encoder/PPMReader.h"
#include "Wire.h"
#ifdef USE_WIFI
#include "wifi/WifiAccess.h"
#include <ESPmDNS.h>
#ifdef USE_WIFI_WEB
#include "wifi/WifiWebServer.h"
#endif
#ifdef USE_WIFI_MARCDUINO
#include "wifi/WifiMarcduinoReceiver.h"
#endif
#endif
#ifdef USE_OTA
#include <ArduinoOTA.h>
#endif
#include <Preferences.h>
#ifdef USE_SDCARD
#include "FS.h"
#include "SD.h"
#endif
#ifdef USE_DROID_REMOTE
#define USE_MENUS
#endif
Preferences preferences;
///////////////////////////////////
#include "core/PinManager.h"
#ifdef USE_I2C_GPIO_EXPANDER
#include "PCF8574.h"
#ifndef GPIO_EXPANDER_ADDRESS
#define GPIO_EXPANDER_ADDRESS 0x20
#endif
static volatile bool sDigitalReadAll = true;
static void IRAM_ATTR flagDigitalReadAll()
{
sDigitalReadAll = true;
}
class CustomPinManager : public PinManager
{
public:
typedef PCF8574::DigitalInput DigitalInput;
CustomPinManager(byte i2cAddress = GPIO_EXPANDER_ADDRESS) :
fGPIOExpander(i2cAddress, PIN_GPIO_INTERRUPT, flagDigitalReadAll)
{}
virtual bool digitalRead(uint8_t pin) override
{
if (pin >= GPIO_PIN_BASE)
{
return fGPIOExpander.digitalRead(pin-GPIO_PIN_BASE, sDigitalReadAll);
}
return PinManager::digitalRead(pin);
}
virtual void digitalWrite(uint8_t pin, uint8_t val) override
{
if (pin >= GPIO_PIN_BASE)
{
fGPIOExpander.digitalWrite(pin-GPIO_PIN_BASE, val);
}
else
{
PinManager::digitalWrite(pin, val);
}
}
virtual void pinMode(uint8_t pin, uint8_t mode) override
{
if (pin >= GPIO_PIN_BASE)
{
fGPIOExpander.pinMode(pin-GPIO_PIN_BASE, mode);
}
else
{
PinManager::pinMode(pin, mode);
}
}
virtual void begin() override
{
fGPIOExpander.begin();
}
DigitalInput digitalReadAll()
{
return fGPIOExpander.digitalReadAll();
}
protected:
PCF8574 fGPIOExpander;
};
CustomPinManager sPinManager;
#else
PinManager sPinManager;
#endif
///////////////////////////////////
#ifdef PIN_STATUSLED
#include "core/SingleStatusLED.h"
enum {
kNormalModeHome = 0,
kWifiModeHome = 1,
kNormalModeAway = 2,
kWifiModeAway = 3,
kNormalModeMoving = 4,
kWifiModeMoving = 5,
kSafetyMode = 6,
};
unsigned sCurrentMode = kNormalModeHome;
static constexpr uint8_t kStatusColors[][4][3] = {
{ { 0, 2, 0} , { 0, 2, 0} , { 0, 2, 0} , { 0, 2, 0} }, // normal mode home (all green)
{ { 0, 0, 2} , { 0, 0, 2} , { 0, 0, 2} , { 0, 0, 2} }, // wifi mode home (all blue)
{ { 2, 0, 0} , { 2, 0, 0} , { 2, 0, 0} , { 2, 0, 0} }, // normal mode away (all red)
{ { 0, 0, 2} , { 2, 0, 0} , { 0, 0, 2} , { 2, 0, 0} }, // wifi mode away (blue,red,blue,red)
{ { 0, 2, 0} , { 2, 2, 0} , { 0, 2, 0} , { 2, 2, 0} }, // normal mode moving (reen,yellow,green,yellow)
{ { 0, 0, 2} , { 2, 2, 0} , { 0, 0, 2} , { 2, 2, 0} }, // wifi mode moving (blue,yellow,blue,yellow)
{ { 2, 2, 0} , { 2, 2, 0} , { 2, 2, 0} , { 2, 2, 0} } // all yellow
};
typedef SingleStatusLED<PIN_STATUSLED> StatusLED;
StatusLED statusLED(kStatusColors, SizeOfArray(kStatusColors));
#endif
///////////////////////////////////
#include "drive/TargetSteering.h"
///////////////////////////////////
#include "core/EEPROMSettings.h"
///////////////////////////////////
struct LifterParameters
{
int fLifterMinPower;
int fLifterMinSeekBotPower;
int fRotaryMinPower;
int fLifterDistance;
int fRotaryMinHeight;
void load()
{
fLifterMinPower = preferences.getInt(PREFERENCES_PARAM_LIFTER_MINIMUM_POWER, DEFAULT_LIFTER_MINIMUM_POWER);
fLifterMinSeekBotPower = preferences.getInt(PREFERENCES_PARAM_LIFTER_SEEKBOT_POWER, DEFAULT_LIFTER_SEEKBOTTTOM_POWER);
fRotaryMinPower = preferences.getInt(PREFERENCES_PARAM_ROTARY_MINIMUM_POWER, DEFAULT_ROTARY_MINIMUM_POWER);
fLifterDistance = preferences.getInt(PREFERENCES_PARAM_LIFTER_DISTANCE, DEFAULT_LIFTER_DISTANCE);
fRotaryMinHeight = preferences.getInt(PREFERENCES_PARAM_ROTARY_MININUM_HEIGHT, DEFAULT_ROTARY_MINIMUM_HEIGHT);
}
void save()
{
preferences.putInt(PREFERENCES_PARAM_LIFTER_MINIMUM_POWER, fLifterMinPower);
preferences.putInt(PREFERENCES_PARAM_LIFTER_SEEKBOT_POWER, fLifterMinSeekBotPower);
preferences.putInt(PREFERENCES_PARAM_ROTARY_MINIMUM_POWER, fRotaryMinPower);
preferences.putInt(PREFERENCES_PARAM_LIFTER_DISTANCE, fLifterDistance);
preferences.putInt(PREFERENCES_PARAM_ROTARY_MININUM_HEIGHT, fRotaryMinHeight);
}
};
LifterParameters sLifterParameters;
///////////////////////////////////
#define LIFTER_MINIMUM_POWER sLifterParameters.fLifterMinPower
#define LIFTER_SEEKBOTTTOM_POWER sLifterParameters.fLifterMinSeekBotPower
#define ROTARY_MINIMUM_POWER sLifterParameters.fRotaryMinPower
#define LIFTER_DISTANCE sLifterParameters.fLifterDistance
#define ROTARY_MINIMUM_HEIGHT sLifterParameters.fRotaryMinHeight
///////////////////////////////////
#define ENCODER_STATUS_RATE 200 // ms (10Hz)
struct OutputLimit
{
bool valid;
unsigned outputLimit;
};
struct LifterSettings
{
OutputLimit fUpLimits[100/5+1];
OutputLimit fDownLimits[sizeof(fUpLimits)/sizeof(fUpLimits[0])];
unsigned fMinimumPower = 0;
unsigned fLifterDistance = 0;
union
{
struct
{
bool fLifterLimitSetting:1;
bool fRotaryLimitSetting:1;
bool fUpLimitsCalibrated:1;
bool fDownLimitsCalibrated:1;
bool fSafetyManeuver:1;
bool fDisableRotary:1;
};
uint8_t fFlags;
};
unsigned fBaudRate = SERIAL_BAUD_RATE;
unsigned fID = 0;
unsigned fReserved1 = 0;
unsigned fReserved2 = 0;
unsigned fReserved3 = 0;
unsigned getLifterDistance()
{
return fLifterDistance != 0 ? fLifterDistance : sLifterParameters.fLifterDistance;
}
static constexpr size_t limitCount()
{
return sizeof(fUpLimits)/sizeof(fUpLimits[0]);
}
#define PREFERENCES_PARAM_LIFTER_SEEKBOT_POWER "lftseekbotpwr"
#define PREFERENCES_PARAM_ROTARY_MINIMUM_POWER "rotminpwr"
};
EEPROMSettings<LifterSettings> sSettings;
///////////////////////////////////
static bool sCalibrating;
static bool sSafetyManeuver;
static bool sSafetyManeuverFailed;
static unsigned sRotaryCircleEncoderCount;
static unsigned sPos;
static unsigned sCopyPos;
static bool sProcessing;
static bool sNextCommand;
static uint32_t sWaitNextSerialCommand;
static char sBuffer[CONSOLE_BUFFER_SIZE];
static char sCopyBuffer[sizeof(sBuffer)+4];
static bool sCmdNextCommand;
static char sCmdBuffer[COMMAND_BUFFER_SIZE];
static bool sRCMode;
static bool sVerboseDebug;
static void runSerialCommand()
{
sWaitNextSerialCommand = 0;
sProcessing = (sPos != 0);
}
static void resetSerialCommand()
{
sWaitNextSerialCommand = 0;
sNextCommand = false;
sProcessing = (sCmdBuffer[0] == ':');
sPos = 0;
}
static void executeCommand(const char* cmd, ...)
{
va_list targ;
sPos = 0;
va_start(targ, cmd);
vsnprintf(sBuffer, sizeof(sBuffer), cmd, targ);
va_end(targ);
sPos = strlen(sBuffer);
runSerialCommand();
}
///////////////////////////////////
PPMReader sPPM(PIN_PPMIN_RC, 6);
#ifdef USE_SDCARD
static bool sSDCardMounted;
#endif
bool mountReadOnlyFileSystem()
{
#ifdef USE_SPIFFS
return (SPIFFS.begin(true));
#endif
return false;
}
bool mountWritableFileSystem()
{
#ifdef USE_FATFS
return (FFat.begin(true, "/fatfs"));
#endif
return false;
}
bool getSDCardMounted()
{
#ifdef USE_SDCARD
return sSDCardMounted;
#else
return false;
#endif
}
bool mountSDFileSystem()
{
#ifdef USE_SDCARD
if (SD.begin(PIN_SD_CS))
{
DEBUG_PRINTLN("Card Mount Success");
sSDCardMounted = true;
return true;
}
DEBUG_PRINTLN("Card Mount Failed");
#endif
return false;
}
void unmountSDFileSystem()
{
#ifdef USE_SDCARD
if (sSDCardMounted)
{
sSDCardMounted = false;
SD.end();
}
#endif
}
void unmountFileSystems()
{
unmountSDFileSystem();
#ifdef USE_FATFS
FFat.end();
#endif
#ifdef USE_SPIFFS
SPIFFS.end();
#endif
}
///////////////////////////////////
void reboot()
{
Serial.println(F("Restarting..."));
#ifdef USE_DROID_REMOTE
DisconnectRemote();
#endif
if (sRCMode)
sPPM.end();
unmountFileSystems();
preferences.end();
ESP.restart();
}
///////////////////////////////////
class PeriscopeLifter : public SetupEvent
{
public:
enum
{
kLightKit_FullCycle = 0,
kLightKit_Off = 1,
kLightKit_ObiWan = 2,
kLightKit_Yoda = 3,
kLightKit_Sith = 4,
kLightKit_SearchLight = 5,
kLightKit_Dagobah = 6,
kLightKit_Sparkle = 7
};
///////////////////////////////////
// Read limit switches
///////////////////////////////////
static bool lifterTopLimit()
{
bool limit = (sPinManager.digitalRead(PIN_LIFTER_TOPLIMIT) == sSettings.fLifterLimitSetting);
return limit;
}
static bool lifterBottomLimit()
{
bool limit = (sPinManager.digitalRead(PIN_LIFTER_BOTLIMIT) == sSettings.fLifterLimitSetting);
return limit;
}
static long getLifterPosition()
{
long pos;
cli();
pos = encoder_lifter_ticks;
sei();
return pos;
}
///////////////////////////////////
static bool rotaryHomeLimit()
{
#ifdef DISABLE_ROTARY
// No rotary unit. Always in home position
return true;
#else
bool limit = sSettings.fDisableRotary || (sPinManager.digitalRead(PIN_ROTARY_LIMIT) == sSettings.fRotaryLimitSetting);
return limit;
#endif
}
static long getRotaryPosition()
{
long pos;
cli();
pos = encoder_rotary_ticks;
sei();
return pos;
}
///////////////////////////////////
static bool lifterMotorFault()
{
return !digitalRead(PIN_LIFTER_DIAG);
}
static bool rotaryMotorFault()
{
return !digitalRead(PIN_ROTARY_DIAG);
}
static bool isIdle()
{
if (lifterBottomLimit())
{
if (!fMotorsEnabled ||
fMotorsEnabledTime + MOTOR_TIMEOUT < millis())
{
return true;
}
}
return false;
}
///////////////////////////////////
static bool motorsEnabled()
{
return fMotorsEnabled;
}
static void disableMotors()
{
sPinManager.digitalWrite(PIN_MOTOR_EN, LOW);
sPinManager.digitalWrite(PIN_MOTOR_ENB, HIGH);
fMotorsEnabled = false;
}
static void enableMotors()
{
sPinManager.digitalWrite(PIN_MOTOR_EN, HIGH);
sPinManager.digitalWrite(PIN_MOTOR_ENB, LOW);
fMotorsEnabled = true;
fMotorsEnabledTime = millis();
#ifdef PIN_STATUSLED
statusLED.setMode(sSafetyManeuver ? sCurrentMode + kNormalModeMoving : unsigned(kSafetyMode));
#endif
}
static inline void dualAnalogWrite(uint8_t m1, float v1, uint8_t m2, float v2)
{
const auto output1{static_cast<int32_t>(abs(v1) * 255)};
const auto output2{static_cast<int32_t>(abs(v2) * 255)};
// analogWrite(m1, output1, 255);
// analogWrite(m2, output2, 255);
::analogWrite(m1, output1);
::analogWrite(m2, output2);
// analogWrite(m1, v1);
// analogWrite(m2, v2);
}
///////////////////////////////////
// Move lifter motor up/down
///////////////////////////////////
static void lifterMotorMove(float throttle)
{
bool reverse = (throttle < 0);
throttle = min(max(abs(throttle), 0.0f), 1.0f);
if (throttle < 0.10)
throttle = 0;
if (fLifterThrottle != throttle)
{
enableMotors();
if (reverse)
{
dualAnalogWrite(PIN_LIFTER_PWM1, 0, PIN_LIFTER_PWM2, fabs(throttle));
fLifterThrottle = -throttle;
}
else
{
dualAnalogWrite(PIN_LIFTER_PWM1, fabs(throttle), PIN_LIFTER_PWM2, 0);
fLifterThrottle = throttle;
}
}
}
static void lifterMotorStop()
{
enableMotors();
dualAnalogWrite(PIN_LIFTER_PWM1, 0, PIN_LIFTER_PWM2, 0);
fLifterThrottle = 0;
}
///////////////////////////////////
static bool serialAbort()
{
if (sCalibrating && Serial.available())
{
DEBUG_PRINTLN("SERIAL ABORT");
while (Serial.available())
Serial.read();
sCalibrating = false;
return true;
}
return false;
}
static bool seekToPosition(float pos, float speed)
{
if (!ensureSafetyManeuver())
return false;
// ensure position is in the range of 0.0 [bottom] - 1.0 [top]
pos = min(max(abs(pos), 0.0f), 1.0f);
if (isRotarySpinning() || !rotaryHomeLimit())
{
// Cannot go below 50% if spinning or not at home position
pos = min(max(pos, 0.5f), 1.0f);
}
if (speed * 100 < sSettings.fMinimumPower)
return seekToPositionSlow(pos, speed/(sSettings.fMinimumPower/100.0));
long maxlen = sSettings.getLifterDistance();
long current = getLifterPosition();
long target_ticks = pos * maxlen;
long distance = abs(target_ticks - current);
TargetSteering steering(target_ticks);
steering.setSampleTime(1);
float minpower = (1.0f - ((float)distance / (float)maxlen)) + 0.1;
steering.setDistanceTunings(1.0, minpower, minpower);
float limit;
bool success = false;
if (target_ticks > getLifterPosition())
{
// seek up
if (!getUpOutputLimit(speed, limit))
return false;
steering.setDistanceOutputLimits(min(float(distance * DISTANCE_OUTPUT_SCALE), limit));
bool topLimit;
LifterStatus lifterStatus;
for (;;)
{
long encoder_ticks = getLifterPosition();
topLimit = lifterTopLimit();
if (topLimit || encoder_ticks == target_ticks || serialAbort())
break;
steering.setCurrentDistance(encoder_ticks);
lifterMotorMove(steering.getThrottle() * speed);
if (!lifterStatus.isMoving())
{
DEBUG_PRINTLN("ABORT");
break;
}
}
success = topLimit;
}
else
{
// seek down
if (!getDownOutputLimit(speed, limit))
return false;
steering.setDistanceOutputLimits(min(float(distance * DISTANCE_OUTPUT_SCALE), limit));
bool botLimit;
LifterStatus lifterStatus;
for (;;)
{
long encoder_ticks = getLifterPosition();
botLimit = lifterBottomLimit();
if (botLimit || encoder_ticks == target_ticks || serialAbort())
break;
steering.setCurrentDistance(encoder_ticks);
lifterMotorMove(steering.getThrottle() * speed);
if (!lifterStatus.isMoving())
{
DEBUG_PRINTLN("ABORT");
break;
}
}
success = botLimit;
}
lifterMotorStop();
return success;
}
///////////////////////////////////
// Spin rotary motor left/right
///////////////////////////////////
static bool rotaryAllowed()
{
#ifdef DISABLE_ROTARY
// Rotary motion not allowed
return false;
#else
return !sSafetyManeuverFailed && !sSettings.fDisableRotary && (getLifterPosition() > sLifterParameters.fRotaryMinHeight);
#endif
}
static void rotaryMotorSpeed(float speed)
{
fRotarySpeed = (rotaryAllowed()) ? speed : 0;
fRotaryEncoderLastStatus = millis();
rotaryMotorUpdate();
}
static void rotaryMotorUpdate()
{
#ifndef DISABLE_ROTARY
if (sSettings.fDisableRotary)
return;
uint32_t currentMillis = millis();
if (currentMillis - fRotaryThrottleUpdate > ROTARY_THROTTLE_LATENCY)
{
if (rotaryAllowed() && (fRotarySpeed != 0 || fRotaryThrottle != 0))
{
float throttle = 0;
long encoder_ticks = getRotaryPosition();
if (fRotarySpeed > fRotaryThrottle)
{
float scale = ROTARY_THROTTLE_ACCELERATION_SCALE;
if (fRotaryThrottle < 0)
scale = ROTARY_THROTTLE_DECELERATION_SCALE;
float val = max(abs(fRotarySpeed - fRotaryThrottle) / scale, 0.01f);
throttle = ((int)round(min(fRotaryThrottle + val, fRotarySpeed)*100))/100.0f;
if (sVerboseDebug)
{
DEBUG_PRINTLN(throttle);
}
rotaryMotorMove(throttle);
fRotaryThrottle = throttle;
}
else if (fRotarySpeed < fRotaryThrottle)
{
float scale = ROTARY_THROTTLE_ACCELERATION_SCALE;
if (fRotaryThrottle > 0)
scale = ROTARY_THROTTLE_DECELERATION_SCALE;
float val = abs(fRotarySpeed - fRotaryThrottle) / scale;
throttle = ((int)floor(max(fRotaryThrottle - val, fRotarySpeed)*100))/100.0f;
if (sVerboseDebug)
{
DEBUG_PRINTLN(throttle);
}
rotaryMotorMove(throttle);
fRotaryThrottle = throttle;
}
if (millis() - fRotaryEncoderLastStatus > ENCODER_STATUS_RATE*2)
{
fRotaryEncoderLastStatus = millis();
if (fRotaryEncoderLastTick == encoder_ticks)
{
DEBUG_PRINTLN("ROTARY NOT MOVING - ABORT");
rotaryMotorStop();
}
fRotaryEncoderLastTick = encoder_ticks;
}
fRotaryThrottleUpdate = currentMillis;
}
}
#endif
}
static void rotaryMotorMove(float throttle, bool skipSafety = false)
{
#ifndef DISABLE_ROTARY
if (sSettings.fDisableRotary)
return;
bool reverse = (throttle < 0);
throttle = min(max(abs(throttle), 0.0f), 1.0f);
if (throttle < 0.10)
throttle = 0;
// Ensure lifter is higher than minimum
if (rotaryAllowed() || skipSafety)
{
if (fRotaryThrottle != throttle)
{
fRotaryEncoderLastStatus = millis();
fRotaryEncoderLastTick = getRotaryPosition();
fRotaryMoving = (throttle != 0);
enableMotors();
if (reverse)
{
dualAnalogWrite(PIN_ROTARY_PWM1, 0, PIN_ROTARY_PWM2, fabs(throttle));
fRotaryThrottle = -throttle;
}
else
{
dualAnalogWrite(PIN_ROTARY_PWM1, fabs(throttle), PIN_ROTARY_PWM2, 0);
fRotaryThrottle = throttle;
}
}
}
else
{
DEBUG_PRINT("ROTARY NOT ALLOWED: ");
DEBUG_PRINTLN(getLifterPosition());
}
#endif
}
static bool withinArc(double p1, double p2, double p3)
{
return fmod(p2 - p1 + 2*360, 360) >= fmod(p3 - p1 + 2*360, 360);
}
static int normalize(int degrees)
{
degrees = fmod(degrees, 360);
if (degrees < 0)
degrees += 360;
return degrees;
}
static int shortestDistance(int origin, int target)
{
int result = 0.0;
int diff = fmod(fmod(abs(origin - target), 360), 360);
if (diff > 180)
{
//There is a shorter path in opposite direction
result = (360 - diff);
if (target > origin)
result *= -1;
}
else
{
result = diff;
if (origin > target)
result *= -1;
}
return result;
}
static bool moveScopeToTarget(int pos, int target, int fudge, float speed, float maxspeed, float &m)
{
#ifndef DISABLE_ROTARY
if (sSettings.fDisableRotary)
return true;
if (sVerboseDebug)
{
DEBUG_PRINT("MOVE raw="); DEBUG_PRINT(getRotaryPosition());
DEBUG_PRINT(" pos="); DEBUG_PRINT(pos);
DEBUG_PRINT(" target="); DEBUG_PRINT(target);
}
if (!withinArc(target - fudge, target + fudge, pos))
{
int dist = shortestDistance(pos, target);
if (sVerboseDebug)
{
DEBUG_PRINT(" dist="); DEBUG_PRINT(dist);
}
if (maxspeed > speed && abs(dist) > fudge*2)
speed += (maxspeed - speed) * float(abs(dist)) / 180;
if (sVerboseDebug)
{
DEBUG_PRINT(" speed1="); DEBUG_PRINT(speed);
}
if (speed < (ROTARY_MINIMUM_POWER/100.0))
speed = (ROTARY_MINIMUM_POWER/100.0);
if (sVerboseDebug)
{
DEBUG_PRINT(" speed2="); DEBUG_PRINT(speed);
}
float nm = (dist > 0) ? -speed : speed;
if (m != 0 && ((m < 0 && nm > 0) || (m > 0 && nm < 0)))
{
// Safety check: In case of problems with the rotary encoder. If our
// direction changes from the initial direction we will just stop.
DEBUG_PRINTLN("DIRECTION CHANGE");
DEBUG_PRINTLN(m);
DEBUG_PRINTLN(nm);
return true;
}
m = nm;
if (sVerboseDebug)