-
Notifications
You must be signed in to change notification settings - Fork 0
/
Winch.ino
1650 lines (1593 loc) · 54.8 KB
/
Winch.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
//
// Define version information
#define WINCH_CONTROL_AUTHOR "N.Ammann"
//
// Define winch properties
#define ENGINE_MAINTENANCE_INTERVAL 25 // Interval for engine maintenance in hours
#define SPOOL_DIAMETER 0.225f // Spool diameter in m
#define ENCODER_RESOLUTION 0.087890625f // Resolution of the encoder in deg (360.0f / 4096 = 0.087890625
#define ROPE_LENGTH 300.0f // Total rope length in m
#define SERVO_MIN_PWM 1000u // Minimum PWM signal
#define SERVO_MAX_PWM 1800u // Maximum PWM signal
#define SAFETY_MARGIN 0.1f // Factor to increase safety margins
#define ANGULAR_INCREMENT_DEADBAND 0.1f // Angular increments below this value are ignored
#define EMERGENCY_STOPPING_DISTANCE 10.0f // Minimum distance the winch needs to come to a complete stop (zero throttle and break) in m.
#define EMERGENCY_STOPPING_TIME 2000 // Minimum time the winch needs to come to a complete stop (zero throttle and break) in ms.
#define STOPPING_DISTANCE 25.0f // TODO: This value has to be verified! Distance the winch needs to come to a complete stop (spool down then break) in m.
#define SPOOL_DOWN_TIME 1500 // Time in milliseconds to let the spool decelerate
#define MINIMAL_ACCELERATION 0.5f // TODO: This value has to be verified! Minimal acceleration of the rope to reach desired velocity in m/s^2
#define MAXIMAL_ACCELERATION 10.0f // Maximal acceleration of the rope to reach desired velocity in m/s^2
#define MINIMAL_VELOCITY 10.0f // Minimal configurable velocity in km/h
#define MAXIMAL_VELOCITY 45.0f // Maximal configurable velocity in km/h
#define SPOOL_UP_TIME 3800 // Time in milliseconds to let the spool spin up in idle (0.8s) / let the rope get tight (3s)
#define ENGINE_RUNNING_TIME_WINDOW 2 // Time horizon to check if engine is running in seconds
#define ENGINE_VIBRATION_THRESHOLD 1.25f // Squared norm of acceleration threshold to detect engine vibrations
#define SPOOL_UP_BEEP_TIME 500 // Time in milliseconds for the duration of the spool up beep
#define START_SIGNAL_DURATION 3 // Minimum time the button has to be pressed to start winch in seconds
#define EMERGENCY_STOP_SIGNAL_DURATION 0.1f // Minimum time the button has to be pressed to start breaking in seconds
#define CONF_SIGNAL_DURATION 0.1f // Minimum time the button has to be pressed to switch to configuration state in seconds
//
// Define persistent variables in EEPROM using EEPROM-Storage library!
#include <EEPROM-Storage.h>
EEPROMStorage<unsigned int> engineRunTimeSinceLastMaintenanceEEPROM(0, 0); // This variable stores engine run time since last maintenance in seconds. It is stored in EEPROM at positions 0 (4 + 1 bytes)
EEPROMStorage<unsigned int> engineRunTimeTotalEEPROM(5, 0); // This variable stores total engine run time in seconds. It is stored in EEPROM at positions 5 (4 + 1 bytes)
EEPROMStorage<unsigned int> totalRunsEEPROM(10, 0); // This variable stores the total number of runs. It is stored in EEPROM at positions 10 (4 + 1 bytes)
EEPROMStorage<unsigned int> throttleServoMinEEPROM(15, SERVO_MIN_PWM); // This variable stores the PWM value for the minimal angle. It is stored in EEPROM at positions 15 (4 + 1 bytes)
EEPROMStorage<unsigned int> throttleServoMaxEEPROM(20, SERVO_MAX_PWM); // This variable stores the PWM value for the maximal angle. It is stored in EEPROM at positions 20 (4 + 1 bytes)
EEPROMStorage<bool> throttleServoInverseEEPROM(25, false); // This variable indicates if the rotation direction is inversed. It is stored in EEPROM at positions 25 (1 + 1 bytes)
EEPROMStorage<unsigned int> breakServoMinEEPROM(27, SERVO_MIN_PWM); // This variable stores the PWM value for the minimal angle. It is stored in EEPROM at positions 27 (4 + 1 bytes)
EEPROMStorage<unsigned int> breakServoMaxEEPROM(32, SERVO_MAX_PWM); // This variable stores the PWM value for the maximal angle. It is stored in EEPROM at positions 32 (4 + 1 bytes)
EEPROMStorage<bool> breakServoInverseEEPROM(37, false); // This variable indicates if the rotation direction is inversed. It is stored in EEPROM at positions 37 (1 + 1 bytes)
EEPROMStorage<float> controllerKpEEPROM(39, 0.0f); // This variable stores the P gain of the PID controller. It is stored in EEPROM at position 49 (4 + 1 bytes)
EEPROMStorage<float> controllerKiEEPROM(44, 0.0f); // This variable stores the I gain of the PID controller. It is stored in EEPROM at position 54 (4 + 1 bytes)
EEPROMStorage<float> controllerKdEEPROM(49, 0.0f); // This variable stores the D gain of the PID controller. It is stored in EEPROM at position 59 (4 + 1 bytes)
EEPROMStorage<float> desiredVelocityEEPROM(54, 30.0f); // This variable stores the desired velocity im km/h. It is stored in EEPROM at position 64 (4 + 1 bytes)
EEPROMStorage<float> accelerationEEPROM(59, 2.0f); // This variable stores the acceleration towards the desired velocity im m/s^2. It is stored in EEPROM at position 69 (4 + 1 bytes)
//
// Define global variables to enable faster access to EEPROM variables
unsigned int throttleServoMin;
unsigned int throttleServoMax;
bool throttleServoInverse;
unsigned int breakServoMin;
unsigned int breakServoMax;
bool breakServoInverse;
//
// Definition of IO pins
const int throttleServoPin = 2;
const int breakServoPin = 3;
const int buzzerPin = 4;
const int buttonPin = 7;
const int potentiometerPin = A0;
//
// Definition of I2C addresses and include I2C functionality
#include <Wire.h>
const int i2cAddressACC = 0x1C;
const int i2cAddressLCD = 0x27;
const int i2cAddressMAG = 0x36;
//
// Definition of servo functionality
#include <Servo.h>
Servo throttleServo;
float __throttleServoValue;
Servo breakServo;
float __breakServoValue;
#define CALIBRATION_ANGLE 30.2f
//
// Definition of the LCD display driver
#include "LCD_Wrapper.hpp"
LCD_Wrapper lcd(i2cAddressLCD, 20, 4);
//
// Create custom characters
// Inverted ' '
#define INVERTED_SPACE_SYMBOL 0
byte invertedSpace[] = {
0x1F,
0x1F,
0x1F,
0x1F,
0x1F,
0x1F,
0x1F,
0x1F
};
// Inverted '<'
#define INVERTED_LEFT_SYMBOL 1
byte invertedLeft[] = {
0x1D,
0x1B,
0x17,
0x0F,
0x17,
0x1B,
0x1D,
0x1F
};
// Inverted '>'
#define INVERTED_RIGHT_SYMBOL 2
byte invertedRight[] = {
0x17,
0x1B,
0x1D,
0x1E,
0x1D,
0x1B,
0x17,
0x1F
};
// Inverted 'E'
#define INVERTED_E_SYMBOL 3
byte invertedE[] = {
0x00,
0x0F,
0x0F,
0x01,
0x0F,
0x0F,
0x00,
0x1F
};
// Inverted 'S'
#define INVERTED_S_SYMBOL 4
byte invertedS[] = {
0x10,
0x0F,
0x0F,
0x11,
0x1E,
0x1E,
0x01,
0x1F
};
// Inverted 'C'
#define INVERTED_C_SYMBOL 5
byte invertedC[] = {
0x11,
0x0E,
0x0F,
0x0F,
0x0F,
0x0E,
0x11,
0x1F
};
// Inverted 'O'
#define INVERTED_O_SYMBOL 6
byte invertedO[] = {
0x11,
0x0E,
0x0E,
0x0E,
0x0E,
0x0E,
0x11,
0x1F
};
// Inverted 'K'
#define INVERTED_K_SYMBOL 7
byte invertedK[] = {
0x0E,
0x0D,
0x0B,
0x07,
0x0B,
0x0D,
0x0E,
0x1F
};
//
// Definition of accelerometer driver
#include "SparkFun_MMA8452Q.h"
MMA8452Q acc;
//
// Definition of magnetic rotation encoder driver
#include "AS5600.h"
AMS_5600 encoder(i2cAddressMAG);
//
// Define control loop
#define CONTROL_LOOP_FREQ_HZ 50 // Frequency of the control loop in Hz
#define CONTROL_LOOP_INTERVAL (1000 / CONTROL_LOOP_FREQ_HZ)
#define LCD_UPDATE_RATE 2 // Frequency of the display update in Hz
long lastMillis;
//
// Define configuration items
enum ConfigurationItems
{
VELOCITY = 0,
ACCELERATION = 1,
P_GAIN = 2,
I_GAIN = 3,
D_GAIN = 4,
THROTTLE_SERVO_MIN = 5,
THROTTLE_SERVO_MAX = 6,
THROTTLE_SERVO_INVERSE = 7,
BREAK_SERVO_MIN = 8,
BREAK_SERVO_MAX = 9,
BREAK_SERVO_INVERSE = 10,
RUNS_TOTAL = 11,
RUN_TIME_TOTAL = 12,
RUN_TIME_MAINTENANCE = 13,
REGISTER_MAINTENANCE = 14,
RESET_ALL = 15
};
enum SelectedItem
{
LEFT = 0,
OK = 1,
ESC = 2,
RIGHT = 3
};
//
// Define math constants
#define SQ(x) ((x)*(x))
//
// Define state classes
class WinchState
{
public:
enum State
{
CONFIGURATION = -1,
STANDBY = 0,
SPOOL_UP_REJECTED = 1,
SPOOL_UP_WARNING = 2,
SPOOL_UP = 3,
SHREDDING = 4,
SPOOL_DOWN = 5
};
bool operator ==(const WinchState& other) const
{
return this->_state == other._state;
}
bool operator !=(const WinchState& other) const
{
return this->_state != other._state;
}
WinchState()
{
this->_state = WinchState::STANDBY;
this->_changed = millis();
}
WinchState& operator =(const WinchState::State& state)
{
this->_state = state;
this->_changed = millis();
return *this;
}
operator WinchState::State() const
{
return this->_state;
}
long lastChanged() const
{
return this->_changed;
}
private:
State _state;
long _changed;
};
class EngineState
{
public:
enum State
{
OFF = 0,
ON = 1
};
bool operator ==(const EngineState& other) const
{
return this->_state == other._state;
}
bool operator !=(const EngineState& other) const
{
return this->_state != other._state;
}
EngineState()
{
this->_state = EngineState::OFF;
this->_changed = millis();
}
EngineState& operator =(const EngineState::State& state)
{
this->_state = state;
this->_changed = millis();
return *this;
}
operator EngineState::State() const
{
return this->_state;
}
long lastChanged() const
{
return this->_changed;
}
private:
State _state;
long _changed;
};
//
// Define global variables
unsigned int buttonState;
unsigned long buttonHighCount;
bool waitForButtonRelease;
unsigned long loopCounter;
unsigned int engineVibrationCounter;
word lastEncoderReading;
float revolutionCounter;
WinchState winchState;
EngineState engineState;
ConfigurationItems activeConfiguration;
SelectedItem selectedItem;
bool selectingValue;
float commandedVelocity;
float desiredVelocity;
float acceleration;
//
// Define PID controller values
#define MINIMAL_P_GAIN 0.0f
#define MAXIMAL_P_GAIN 1.0f // TODO: This value has to be verified!
float controllerKp;
#define MINIMAL_I_GAIN 0.0f
#define MAXIMAL_I_GAIN 1.0f // TODO: This value has to be verified!
float controllerKi;
#define MINIMAL_D_GAIN 0.0f
#define MAXIMAL_D_GAIN 1.0f // TODO: This value has to be verified!
float controllerKd;
float currentError;
float lastError;
float integralError;
//
// Define feed forward controller
float calculateFeedForwardComponent(float commandedVelocity)
{
//
// Check if commanded velocity is in range
if (commandedVelocity < MINIMAL_VELOCITY) return 0.0f;
if (commandedVelocity > MAXIMAL_VELOCITY) return 1.0f;
//
// Calculate feed forward component based on polynom
return (commandedVelocity - MINIMAL_VELOCITY) / (MAXIMAL_VELOCITY - MINIMAL_VELOCITY);
}
//
// Utility functions
void idle(const unsigned int duration)
{
unsigned long currentMillis = millis();
while (millis() - currentMillis < duration);
}
void haltProgram()
{
while (true) {
tone(buzzerPin, 2000);
idle(500);
noTone(buzzerPin);
idle(500);
}
}
void printErrorMessage(const __FlashStringHelper* text)
{
Serial.print(F("Error: ")); Serial.println(text);
lcd.setCursor(0, 1);
lcd.print(F(" ERROR MESSAGE: "));
lcd.setCursor(0, 2);
lcd.print(F(" "));
lcd.setCursor(0, 3);
lcd.print(F(" "));
lcd.setCursor(0, 3);
lcd.print(text);
lcd.updateDisplay();
}
void printInfoMessage(const __FlashStringHelper* text)
{
lcd.setCursor(0, 1);
lcd.print(F(" INFO MESSAGE: "));
lcd.setCursor(0, 2);
lcd.print(F(" "));
lcd.setCursor(0, 3);
lcd.print(F(" "));
lcd.setCursor(0, 3);
lcd.print(text);
}
void printErrorMessageAndHaltProgram(const __FlashStringHelper* text)
{
//
// Print error message
printErrorMessage(text);
//
// Halt program
haltProgram();
}
unsigned int getThrottleServoMicroseconds()
{
return throttleServo.readMicroseconds();
}
void setThrottleServoMicroseconds(unsigned int us)
{
throttleServo.writeMicroseconds(us);
}
float getThrottleServo()
{
return __throttleServoValue;
}
void setThrottleServo(float value)
{
//
// Check if value is in range
if (value > 1.0f) {
value = 1.0f;
} else if (value < 0.0f) {
value = 0.0f;
}
//
// Store to global variable to read the value back
__throttleServoValue = value;
//
// Transform value to PWM signal
if (throttleServoInverse) {
throttleServo.writeMicroseconds(map(value, 0.0f, 1.0f, throttleServoMax, throttleServoMin));
} else {
throttleServo.writeMicroseconds(map(value, 0.0f, 1.0f, throttleServoMin, throttleServoMax));
}
}
unsigned int getBreakServoMicroseconds()
{
return breakServo.readMicroseconds();
}
void setBreakServoMicroseconds(unsigned int us)
{
breakServo.writeMicroseconds(us);
}
float getBreakServo()
{
return __breakServoValue;
}
void setBreakServo(float value)
{
//
// Check if value is in range
if (value > 1.0f) {
value = 1.0f;
} else if (value < 0.0f) {
value = 0.0f;
}
//
// Store to global variable to read the value back
__breakServoValue = value;
//
// Transform angle to PWM signal
if (breakServoInverse) {
breakServo.writeMicroseconds(map(value, 0.0f, 1.0f, breakServoMax, breakServoMin));
} else {
breakServo.writeMicroseconds(map(value, 0.0f, 1.0f, breakServoMin, breakServoMax));
}
}
inline bool getBool(const __FlashStringHelper* text)
{
//
// Initialize value
bool value = false;
//
// Print text
lcd.setCursor(0, 2);
lcd.print(text);
//
// Read value from potentiometer as long as the button is not pressed
while (digitalRead(buttonPin) == LOW) {
value = (map(analogRead(potentiometerPin), 0, 1023, 0, 10) > 5);
lcd.setCursor(0, 3);
lcd.print(F("Value: "));
lcd.setCursor(7, 3);
lcd.print(value ? F("True") : F("False"));
lcd.updateDisplay();
idle(100);
}
//
// Wait until button is released
while (digitalRead(buttonPin) == HIGH);
//
// Return value
return value;
}
inline int getNumber(const __FlashStringHelper* text, const int minimum, const int maximum, void (*f)(int))
{
//
// Initialize value
int value = 0;
//
// Print text
lcd.setCursor(0, 2);
lcd.print(text);
//
// Read value from potentiometer as long as the button is not pressed
while (digitalRead(buttonPin) == LOW) {
value = map(analogRead(potentiometerPin), 0, 1023, minimum, maximum);
if (f) f(value);
lcd.setCursor(0, 3);
lcd.print(F("Value: "));
lcd.setCursor(7, 3);
lcd.print(value);
lcd.updateDisplay();
idle(100);
}
//
// Wait until button is released
while (digitalRead(buttonPin) == HIGH);
//
// Return value
return value;
}
inline unsigned int getNumber(const __FlashStringHelper* text, const unsigned int minimum, const unsigned int maximum, void (*f)(unsigned int))
{
//
// Initialize value
unsigned int value = 0;
//
// Print text
lcd.setCursor(0, 2);
lcd.print(text);
//
// Read value from potentiometer as long as the button is not pressed
while (digitalRead(buttonPin) == LOW) {
value = map(analogRead(potentiometerPin), 0, 1023, minimum, maximum);
if (f) f(value);
lcd.setCursor(0, 3);
lcd.print(F("Value: "));
lcd.setCursor(7, 3);
lcd.print(value);
lcd.updateDisplay();
idle(100);
}
//
// Wait until button is released
while (digitalRead(buttonPin) == HIGH);
//
// Return value
return value;
}
inline float getNumber(const __FlashStringHelper* text, const float minimum, const float maximum, void (*f)(float))
{
//
// Initialize value
float value = 0;
//
// Print text
lcd.setCursor(0, 2);
lcd.print(text);
//
// Read value from potentiometer as long as the button is not pressed
while (digitalRead(buttonPin) == LOW) {
value = map(analogRead(potentiometerPin), 0, 1023, minimum, maximum);
if (f) f(value);
lcd.setCursor(0, 3);
lcd.print(F("Value: "));
lcd.setCursor(7, 3);
lcd.print(value);
lcd.updateDisplay();
idle(100);
}
//
// Wait until button is released
while (digitalRead(buttonPin) == HIGH);
//
// Return value
return value;
}
void haltWinch()
{
//
// Put throttle to zero
setThrottleServo(0.0f);
//
// Enable break
setBreakServo(1.0f);
}
void releaseWinch()
{
//
// Put throttle to zero
setThrottleServo(0.0f);
//
// Release break
setBreakServo(0.0f);
}
bool buttonPressedFor(unsigned int counter)
{
if (buttonState == HIGH && buttonHighCount > counter) {
waitForButtonRelease = true;
buttonHighCount = 0;
return true;
} else {
return false;
}
}
bool buttonPressedForAndReleased(unsigned int counter)
{
if (buttonState == LOW && buttonHighCount > counter) {
buttonHighCount = 0;
return true;
} else {
return false;
}
}
void clearEEPROM()
{
for (unsigned int i = 0; i < EEPROM.length(); ++i) {
EEPROM.update(i, 0xFF);
}
}
void updateButton()
{
if (digitalRead(buttonPin) == LOW) {
buttonState = LOW;
waitForButtonRelease = false;
} else {
if (buttonState == LOW || waitForButtonRelease) {
buttonHighCount = 0;
} else {
buttonHighCount++;
}
buttonState = HIGH;
}
}
void updateEngineState()
{
//
// Check if new data is available
if (acc.available()) {
//
// Get new data
acc.read();
Serial.print(acc.cx); Serial.print(';');
Serial.print(acc.cy); Serial.print(';');
Serial.print(acc.cz); Serial.print(';');
//
// Calculate squared norm of acceleration vector
float norm2 = SQ(acc.cx) + SQ(acc.cy) + SQ(acc.cz);
Serial.print(norm2); Serial.print(';');
//
// Check if squared norm is above defined threshold for specified time
if (norm2 >= ENGINE_VIBRATION_THRESHOLD) {
if (engineVibrationCounter < ENGINE_RUNNING_TIME_WINDOW * CONTROL_LOOP_FREQ_HZ) {
engineVibrationCounter++;
}
} else if (engineVibrationCounter > 0) {
engineVibrationCounter--;
}
//
// Check if engine state has to be changed.
// Change value of counter to introduce hysteresis.
if (engineState != EngineState::State::ON) {
if (engineVibrationCounter > ENGINE_RUNNING_TIME_WINDOW * CONTROL_LOOP_FREQ_HZ / 2) {
engineState = EngineState::State::ON;
engineVibrationCounter = ENGINE_RUNNING_TIME_WINDOW * CONTROL_LOOP_FREQ_HZ;
}
} else {
if (engineVibrationCounter < ENGINE_RUNNING_TIME_WINDOW * CONTROL_LOOP_FREQ_HZ / 2) {
engineRunTimeTotalEEPROM += (millis() - engineState.lastChanged()) / 1000;
engineRunTimeSinceLastMaintenanceEEPROM += (millis() - engineState.lastChanged()) / 1000;
engineState = EngineState::State::OFF;
engineVibrationCounter = 0;
}
}
} else {
//
// We lost the accelerometer -> HALT
haltWinch();
printErrorMessageAndHaltProgram(F(" NO ACC READING "));
}
Serial.print(engineState); Serial.print(';');
Serial.print(engineVibrationCounter); Serial.print(';');
}
void displayRopeStatus(const float& ropeVelocity, const float& ropeLength_m)
{
lcd.setCursor(0, 2);
lcd.print(F("Velocity: Rope:"));
lcd.setCursor(0, 3);
lcd.print(F(" km/h m"));
lcd.setCursor(0, 3);
if (ropeVelocity < 10) lcd.print(" ");
lcd.print(ropeVelocity, 1);
lcd.setCursor(12, 3);
if (-99.95f < ropeLength_m && ropeLength_m < 999.95f) lcd.print(" ");
if ( -9.95f < ropeLength_m && ropeLength_m < 99.95f) lcd.print(" ");
if ( 0.00f <= ropeLength_m && ropeLength_m < 9.95f) lcd.print(" ");
lcd.print(ropeLength_m, 1);
}
template< typename T >
float map(T x, T in_min, T in_max, float out_min, float out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void displayMenu(int idx = -1)
{
lcd.setCursor(0, 3);
if (idx == 0) {
lcd.write(INVERTED_SPACE_SYMBOL);
lcd.write(INVERTED_LEFT_SYMBOL);
lcd.write(INVERTED_LEFT_SYMBOL);
lcd.write(INVERTED_SPACE_SYMBOL);
} else {
lcd.print(F(" << "));
}
lcd.print(F("|"));
if (idx == 1) {
lcd.write(INVERTED_SPACE_SYMBOL);
lcd.write(INVERTED_O_SYMBOL);
lcd.write(INVERTED_K_SYMBOL);
lcd.write(INVERTED_SPACE_SYMBOL);
} else {
lcd.print(F(" OK "));
}
lcd.print(F("|"));
if (idx == 2) {
lcd.write(INVERTED_SPACE_SYMBOL);
lcd.write(INVERTED_E_SYMBOL);
lcd.write(INVERTED_S_SYMBOL);
lcd.write(INVERTED_C_SYMBOL);
lcd.write(INVERTED_SPACE_SYMBOL);
} else {
lcd.print(F(" ESC "));
}
lcd.print(F("|"));
if (idx == 3) {
lcd.write(INVERTED_SPACE_SYMBOL);
lcd.write(INVERTED_RIGHT_SYMBOL);
lcd.write(INVERTED_RIGHT_SYMBOL);
lcd.write(INVERTED_SPACE_SYMBOL);
} else {
lcd.print(F(" >> "));
}
}
//
// Define boot process
void setup() {
//
// Load calibrated variables from EEPROM to RAM
throttleServoMin = throttleServoMinEEPROM;
throttleServoMax = throttleServoMaxEEPROM;
throttleServoInverse = throttleServoInverseEEPROM;
breakServoMin = breakServoMinEEPROM;
breakServoMax = breakServoMaxEEPROM;
breakServoInverse = breakServoInverseEEPROM;
//
// Initialize IO pins
pinMode(buttonPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
//
// Initialize I2C bus communication
Wire.begin();
//
// Initialize serial output for debugging
Serial.begin(115200);
while (!Serial);
//
// Write welcome message to serial output
Serial.println(F("Winch Control"));
Serial.print(F("Created by: ")); Serial.println(F(WINCH_CONTROL_AUTHOR));
//
// Display some debug information
Serial.print(F("CPU Frequency: ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
Serial.print(F("Control Loop Frequency: ")); Serial.print(CONTROL_LOOP_FREQ_HZ); Serial.println(F(" Hz"));
Serial.print(F("Control Loop Rate: ")); Serial.print(CONTROL_LOOP_INTERVAL); Serial.println(F(" ms"));
Serial.print(F("Throttle Servo Min PWM: ")); Serial.print(throttleServoMinEEPROM); Serial.println(F(" µs"));
Serial.print(F("Throttle Servo Max PWM: ")); Serial.print(throttleServoMaxEEPROM); Serial.println(F(" µs"));
Serial.print(F("Throttle Servo Inverse: ")); Serial.print(throttleServoInverseEEPROM ? F("True") : F("False")); Serial.println(F(""));
Serial.print(F("Break Servo Min PWM: ")); Serial.print(breakServoMinEEPROM); Serial.println(F(" µs"));
Serial.print(F("Break Servo Max PWM: ")); Serial.print(breakServoMaxEEPROM); Serial.println(F(" µs"));
Serial.print(F("Break Servo Inverse: ")); Serial.print(breakServoInverseEEPROM ? F("True") : F("False")); Serial.println(F(""));
Serial.print(F("Controller Kp: ")); Serial.print(controllerKpEEPROM); Serial.println(F(""));
Serial.print(F("Controller Ki: ")); Serial.print(controllerKiEEPROM); Serial.println(F(""));
Serial.print(F("Controller Kd: ")); Serial.print(controllerKdEEPROM); Serial.println(F(""));
Serial.print(F("Desired Velocity: ")); Serial.print(desiredVelocityEEPROM); Serial.println(F(" km/h"));
Serial.print(F("Acceleration: ")); Serial.print(accelerationEEPROM); Serial.println(F(" m/s^2"));
Serial.print(F("Engine Run Time Total: ")); Serial.print(engineRunTimeTotalEEPROM); Serial.println(F(" s"));
Serial.print(F("Engine Run Time Since Maintenance: ")); Serial.print(engineRunTimeSinceLastMaintenanceEEPROM); Serial.println(F(" s"));
Serial.print(F("Total Runs: ")); Serial.print(totalRunsEEPROM); Serial.println(F(""));
//
// Search for LCD display
Wire.beginTransmission(i2cAddressLCD);
if (Wire.endTransmission() != 0) {
printErrorMessageAndHaltProgram(F(" LCD NOT FOUND! "));
}
//
// Initialize LCD display
lcd.init();
lcd.backlight();
//
// Add custom characters
lcd.createChar(INVERTED_SPACE_SYMBOL, invertedSpace);
lcd.createChar(INVERTED_LEFT_SYMBOL, invertedLeft);
lcd.createChar(INVERTED_RIGHT_SYMBOL, invertedRight);
lcd.createChar(INVERTED_E_SYMBOL, invertedE);
lcd.createChar(INVERTED_S_SYMBOL, invertedS);
lcd.createChar(INVERTED_C_SYMBOL, invertedC);
lcd.createChar(INVERTED_O_SYMBOL, invertedO);
lcd.createChar(INVERTED_K_SYMBOL, invertedK);
//
// Write welcome message to LCD
lcd.setCursor(0, 0);
lcd.print(F("Winch Control"));
lcd.setCursor(0, 1);
lcd.print(F("Created by:"));
lcd.setCursor(12, 1);
lcd.print(F(WINCH_CONTROL_AUTHOR));
lcd.setCursor(0, 3);
lcd.print(F(" Happy Shredding! "));
lcd.updateDisplay();
//
// Initialize accelerometer
if (!acc.begin(Wire, i2cAddressACC)) {
printErrorMessageAndHaltProgram(F(" ACC NOT FOUND! "));
}
//
// Search for magnetic rotational encoder
Wire.beginTransmission(i2cAddressMAG);
if (Wire.endTransmission() != 0) {
printErrorMessageAndHaltProgram(F(" ENCODER NOT FOUND! "));
}
//
// Initialize magnetic rotational encoder
if(encoder.detectMagnet() == 1) {
switch (encoder.getMagnetStrength()) {
case 1:
// printErrorMessageAndHaltProgram(F(" MAG TOO WEAK "));
break;
case 2:
break;
case 3:
// printErrorMessageAndHaltProgram(F(" MAG TOO STRONG "));
break;
}
lastEncoderReading = encoder.getRawAngle();
} else {
//
// No communication with encoder established!
printErrorMessageAndHaltProgram(F(" NO MAG DETECTED! "));
}
//
// Initialize variables
buttonState = LOW;
buttonHighCount = 0;
waitForButtonRelease = false;
loopCounter = 0;
engineVibrationCounter = 0;
revolutionCounter = 0.0f;
winchState = WinchState::State::STANDBY;
engineState = EngineState::State::OFF;
activeConfiguration = ConfigurationItems::VELOCITY;
selectedItem = SelectedItem::OK;
selectingValue = false;
commandedVelocity = 0.0f;
desiredVelocity = desiredVelocityEEPROM;
acceleration = accelerationEEPROM;
//
// Set PID values
// const float K_krit = 12.5f;
// const float T_krit = 2.0f;
// controllerKp = 0.60f * K_krit;
// controllerKi = 1.20f * K_krit / T_krit;
// controllerKd = 3.00f * K_krit * T_krit / 40.0f;
controllerKp = controllerKpEEPROM;
controllerKi = controllerKiEEPROM;
controllerKd = controllerKdEEPROM;
//
// Just wait a bit so that the welcome message is readable
idle(3000);
//
// Check if we have to inform about some important stuff
if (((ENGINE_MAINTENANCE_INTERVAL - 1) * 60) <= engineRunTimeSinceLastMaintenanceEEPROM / 60) {
printInfoMessage(F("MAINTENANCE REQUIRED"));
//
// Just wait a bit so that the info message is readable
idle(3000);
}
//
// Check if we enter the calibration
bool servosNeedCalibration = !throttleServoMinEEPROM.isInitialized() ||
!throttleServoMaxEEPROM.isInitialized() ||
!throttleServoInverseEEPROM.isInitialized() ||
!breakServoMinEEPROM.isInitialized() ||
!breakServoMaxEEPROM.isInitialized() ||
!breakServoInverseEEPROM.isInitialized();
if (servosNeedCalibration) {
//
// Display message
Serial.println(F("Entering calibration mode ..."));
lcd.setCursor(0, 1);
lcd.print(F("Calibration Mode: "));
//
// Wait until button is released
while (digitalRead(buttonPin) == HIGH);
//
// Check if we enter servo calibration
if (servosNeedCalibration) {
//
// Initialize servos with max thinkable values
throttleServo.attach(throttleServoPin, SERVO_MIN_PWM, SERVO_MAX_PWM);
breakServo.attach(breakServoPin, SERVO_MIN_PWM, SERVO_MAX_PWM);
//
// Calibrate minimal value of throttle servo
Serial.println(F("Calibrate minimal value of throttle servo ..."));
throttleServoMin = getNumber(F("Min. Throttle Servo:"), SERVO_MIN_PWM, SERVO_MAX_PWM, &setThrottleServoMicroseconds);
throttleServoMinEEPROM = throttleServoMin;
Serial.print(F("Set minimal value of throttle servo to ")); Serial.print(throttleServoMin); Serial.println(F(" us!"));
//
// Calibrate maximal value of throttle servo
Serial.println(F("Calibrate maximal value of throttle servo ..."));
throttleServoMax = getNumber(F("Max. Throttle Servo:"), throttleServoMin, SERVO_MAX_PWM, &setThrottleServoMicroseconds);
throttleServoMaxEEPROM = throttleServoMax;
Serial.print(F("Set maximal value of throttle servo to ")); Serial.print(throttleServoMax); Serial.println(F(" us!"));
//
// Check if throttle servo should be inverted
Serial.println(F("Set inversion of break servo ..."));
throttleServoInverse = getBool(F("Inv. Throttle Servo:"));
throttleServoInverseEEPROM = throttleServoInverse;
Serial.print(F("Inversion of throttle servo ")); Serial.print(throttleServoInverse ? F("enabled") : F("disabled")); Serial.println(F("!"));
//
// Calibrate minimal value of break servo
Serial.println(F("Calibrate minimal value of break servo ..."));
breakServoMin = getNumber(F("Min. Break Servo: "), SERVO_MIN_PWM, SERVO_MAX_PWM, &setBreakServoMicroseconds);
breakServoMinEEPROM = breakServoMin;
Serial.print(F("Set minimal value of break servo to ")); Serial.print(breakServoMin); Serial.println(F(" us!"));
//
// Calibrate maximal value of break servo
Serial.println(F("Calibrate maximal value of break servo ..."));
breakServoMax = getNumber(F("Max. Break Servo: "), breakServoMin, SERVO_MAX_PWM, &setBreakServoMicroseconds);
breakServoMaxEEPROM = breakServoMax;
Serial.print(F("Set maximal value of break servo to ")); Serial.print(breakServoMax); Serial.println(F(" us!"));
//
// Check if break servo should be inverted
Serial.println(F("Set inversion of break servo ..."));
breakServoInverse = getBool(F("Inv. Break Servo: "));
breakServoInverseEEPROM = breakServoInverse;
Serial.print(F("Inversion of break servo ")); Serial.print(breakServoInverse ? F("enabled") : F("disabled")); Serial.println(F("!"));
//
// Unload servos with calibration config and load servos again.
throttleServo.detach();
breakServo.detach();
}
//
// Initialize servos
throttleServo.attach(throttleServoPin, throttleServoMin, throttleServoMax);
breakServo.attach(breakServoPin, breakServoMin, breakServoMax);
throttleServo.writeMicroseconds(throttleServoInverse ? throttleServoMax : throttleServoMin);
breakServo.writeMicroseconds(breakServoInverse ? breakServoMax : breakServoMin);
} else {
//
// Initialize servos
throttleServo.attach(throttleServoPin, throttleServoMin, throttleServoMax);
breakServo.attach(breakServoPin, breakServoMin, breakServoMax);