-
Notifications
You must be signed in to change notification settings - Fork 53
/
megadesk.cpp
1427 lines (1262 loc) · 35.5 KB
/
megadesk.cpp
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
// want to override minimum/maximum heights?
#define MINMAX
// option to include immediate user-feedback pips
#define FEEDBACK
// experimental smaller linInit
#define SMALL_INIT
// enable reset via button-press and/or bad linInit
#define ENABLERESET
// Serial control/telemetry
//#define SERIALCOMMS
// Transmit/receive *ascii* commands (instead of raw bytes) over serial for human interfacing/control.
#define HUMANSERIAL
// Echo back the interpreted command before acting on it.
#define SERIALECHO
// Report errors over serial - for debugging
// timeouts, bad motor reads, user errors
#define SERIALERRORS
// Report the variant (idle) type on move/stop - for debugging hung states
//#define SERIAL_IDLE
// debug requested targetHeight - for debugging
//#define DEBUGHEIGHT
// raw data. turn off HUMANSERIAL,SERIALECHO & use hexlify..
// Debug of packets sent during init over serial.
//#define DEBUGSTARTUP
// easter egg
#define EASTER
#include <EEPROM.h>
#include "lin.h"
#include "megadesk.h"
#include <avr/wdt.h>
// constants related to presses/eeprom slots
// (on attiny841: 512byte eeprom means slots 0-255)
// EEPROM magic signature to detect if eeprom is valid
#define EEPROM_SIG_SLOT 0
#define MAGIC_SIG 0x120d // bytes: 13, 18 in little endian order
#define MIN_SLOT 2 // 1 is possible but cant save without serial
#ifdef ENABLERESET
#define FORCE_RESET 15 // force reset
#endif
#define MIN_HEIGHT_SLOT 11
#define MAX_HEIGHT_SLOT 12
#define RECALIBRATE 14 // nothing is stored there
#define RESERVED_VARIANT 16 // reserved - deliberately empty
#define FEEDBACK_SLOT 17 // short tones on every button-press. buzz on no-ops
#define BOTHBUTTON_SLOT 18 // store whether bothbuttons is enabled
#define DOWN_SLOT_START 32 // 0x20 offset for down button slots
#ifdef SERIALCOMMS
uint16_t oldHeight = 0; // previously reported height
#endif
#define HYSTERESIS 137 // ignore movement requests < this distance
#define MOVE_OFFSET 159 // amount to move when moving manually
#ifdef AVR2
#define PIN_UP PIN_PA5
#define PIN_DOWN PIN_PA6
#define PIN_BEEP PIN_PA7
#define PIN_LIN_SERIAL PIN_PA1
HardwareSerial &userSerial = Serial;
HardwareSerial &linSerial = Serial1;
#else
#define PIN_UP PIN_PB0
#define PIN_DOWN PIN_PB1
#define PIN_BEEP PIN_PA7
#define PIN_LIN_SERIAL PIN_PA1
HardwareSerial &userSerial = Serial1;
HardwareSerial &linSerial = Serial;
#endif
// click durations
#define CLICK_TIMEOUT 400UL // Timeout in MS. for long-hold and release idle.
#define CLICK_LONG 10000UL // very-long holdtime in MS.
// beeps
#define PIP_DURATION 20
#define SHORT_PAUSE 50
#define BEEP_DURATION 150
#define LONG_PAUSE 500
#define ONE_SEC_PAUSE 1000
#define PAUSE BEEP_DURATION
#define PITCH_ADJUST (48000000 / F_CPU) // digitalWrite takes ~6us at 8MHz
// notes to beep
#define SILENCE 20
#define NOTE_A4 440
#define NOTE_C6 1046
#define NOTE_CSHARP6 1109
#define NOTE_D6 1175
#define NOTE_DSHARP6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_G6 1568
#define NOTE_A6 1760
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CSHARP7 2217
#define NOTE_D7 2344
#define NOTE_DSHARP7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_G7 3136
#define NOTE_A7 3520
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_LOW NOTE_C6
#define NOTE_ACK NOTE_G6
#define NOTE_HIGH NOTE_C7
// LIN commands/status
#define LIN_CMD_IDLE 252
#define LIN_CMD_RAISE 134
#define LIN_CMD_LOWER 133
#define LIN_CMD_FINE 135
#define LIN_CMD_FINISH 132
#define LIN_CMD_PREMOVE 196
#define LIN_CMD_RECALIBRATE 189
#define LIN_CMD_RECALIBRATE_END 188
#define LIN_MOTOR_BUSY 2
#define LIN_MOTOR_BUSY_FINE 3
// These are the 3 known idle states
#define LIN_MOTOR_IDLE1 0
#define LIN_MOTOR_IDLE2 37
#define LIN_MOTOR_IDLE3 96
// Changing these might be a really bad idea. They are sourced from
// decoding the OEM controller limits.
#define DANGER_MAX_HEIGHT (6777 - HYSTERESIS)
#define DANGER_MIN_HEIGHT (162 + HYSTERESIS)
// any button pressed?
#define PRESSED(b) (b != Button::NONE)
// is a memory button?
#define MEMORY_BUTTON(b) ((b == Button::UP) || ( bothbuttons && (b == Button::DOWN)))
// is bothbuttons enabled and the down button was used?
#define USED_DOWN ((bothbuttons) && (lastbutton == Button::DOWN))
// Tracking multipress/longpress of buttons
Button previous = Button::NONE; // previous state of buttons
Button lastbutton = Button::NONE; // last button to be pressed
uint8_t pushCount = 0; // tracks number of button pushes
uint8_t bothbuttons; // both button mode
bool savePosition = false; // flag to save currentHeight to pushCount slot
bool memoryEvent = false; // flag to load/save a pushCount slot
Command manualMove; // press and hold up/down?
// feedback pips
#ifdef FEEDBACK
bool feedback;
uint16_t scale[] = { NOTE_C6, NOTE_D6, NOTE_E6, NOTE_F6, NOTE_G6, NOTE_A6, NOTE_B6, NOTE_C7, };
#endif
// timestamps
unsigned long lastPushTime = 0;
unsigned long refTime = 0;
//////////////////
Lin lin(linSerial, PIN_LIN_SERIAL);
uint16_t currentHeight = 0;
uint16_t targetHeight = 0;
uint16_t maxHeight = DANGER_MAX_HEIGHT;
uint16_t minHeight = DANGER_MIN_HEIGHT;
bool memoryMoving = false;
Command user_cmd = Command::NONE; // for requesting motors up/down
State state = State::OFF; // desk-protocol state
// set/clear motor up command
#define MOTOR_UP user_cmd = Command::UP
#define MOTOR_DOWN user_cmd = Command::DOWN
#define MOTOR_OFF user_cmd = Command::NONE
#ifdef EASTER
#define EIGHTH 131
const uint16_t tones[] = {
NOTE_C6, EIGHTH*2, NOTE_C7, EIGHTH*8,
NOTE_B6, EIGHTH, NOTE_C7, EIGHTH,
NOTE_B6, EIGHTH, NOTE_G6, EIGHTH,
NOTE_A6, EIGHTH*8,
NOTE_F6, EIGHTH, SILENCE, EIGHTH,
NOTE_F6, EIGHTH*2,
NOTE_F6, EIGHTH, NOTE_E6, EIGHTH,
NOTE_D6, EIGHTH, NOTE_E6, EIGHTH,
NOTE_C6, EIGHTH, SILENCE, EIGHTH, };
#endif
// clean the slate for button presses
void startFresh()
{
previous = Button::NONE;
lastPushTime = 0;
pushCount = 0;
savePosition = false;
memoryEvent = false;
}
#ifdef ENABLERESET
// use a constructor to disable the watchdog well before setup() is called
softReset::softReset()
{
#ifndef AVR2
MCUSR = 0;
#endif
wdt_disable();
}
softReset soft;
// watchdog software-reset method.
inline void softReset::Reset() {
wdt_enable( WDTO_30MS );
// avoid wdt_reset() with this loop
for(;;) {}
}
#endif
void setup()
{
bool up_press = false;
pinMode(PIN_UP, INPUT_PULLUP);
pinMode(PIN_DOWN, INPUT_PULLUP);
pinMode(PIN_BEEP, OUTPUT);
delay(SHORT_PAUSE);
// hold up button on boot to toggle both/single Button Mode
if (!digitalRead(PIN_UP))
up_press = true;
// hold down button during reset to factory reset
if (!digitalRead(PIN_DOWN))
{
initAndReadEEPROM(true);
beep(NOTE_C7, 2);
delay(LONG_PAUSE);
while (true)
{
if (!digitalRead(PIN_DOWN))
{
// descending tones
beep(NOTE_E7);
beep(NOTE_D7);
beep(NOTE_C7);
delay(LONG_PAUSE);
}
if (!digitalRead(PIN_UP))
{
// ascending tones
beep(NOTE_C7);
beep(NOTE_D7);
beep(NOTE_E7);
delay(LONG_PAUSE);
}
delay(SHORT_PAUSE);
}
}
#ifdef SERIALCOMMS
userSerial.begin(115200);
#endif
// init + arpeggio
beep(NOTE_C6);
initAndReadEEPROM(false);
beep(NOTE_E6);
lin.begin(19200);
beep(NOTE_G6);
#ifdef DEBUGSTARTUP
// output bit period and recv-timeout times.
writeSerial(1000000/19200, (34+90)*1000000/19200, 0xaa);
#endif
linInit();
// final note played once for single button mode, twice for bothbutton mode
if (up_press)
toggleBothMode();
else
beep(NOTE_C7, bothbuttons+1);
}
// track button presses - short and long
void readButtons()
{
Button buttons;
unsigned long currentMillis = millis();
if (!digitalRead(PIN_UP)) {
if (!digitalRead(PIN_DOWN)) {
buttons = Button::BOTH;
manualMove = Command::NONE;
} else {
buttons = Button::UP;
}
} else if (!digitalRead(PIN_DOWN)) {
buttons = Button::DOWN;
} else {
buttons = Button::NONE;
}
if ( PRESSED(buttons) )
{ // a button is pressed
if (previous != buttons)
{ // new push
// clear pushCount if pushing a different button from last
if (buttons != lastbutton)
startFresh();
// If already moving and any button is pressed - stop (smoothly)
if ( memoryMoving ) {
if (targetHeight > currentHeight )
targetHeight = currentHeight + MOVE_OFFSET; // smoother stop
else
targetHeight = currentHeight - HYSTERESIS;
#if (defined SERIALCOMMS && defined DEBUGHEIGHT)
writeSerial(response_halt, targetHeight); // report target
#endif
}
lastPushTime = currentMillis;
lastbutton = buttons;
#ifdef FEEDBACK
if (feedback)
playTone(scale[pushCount % (sizeof(scale)/sizeof(scale[0]))],
PIP_DURATION); // musical feedback
#endif
}
else
{ // button held
unsigned long pushLength = currentMillis - lastPushTime;
// long push?
if (pushLength > CLICK_TIMEOUT) {
// first long push? then move!
if (pushCount == 0) {
if (buttons == Button::UP) manualMove = Command::UP;
if (buttons == Button::DOWN) manualMove = Command::DOWN;
#ifdef EASTER
if ((buttons == Button::BOTH) && (pushLength > CLICK_LONG)) {
// 10s hold. unused trigger, play the easter-egg
for (uint16_t i=0; i < sizeof(tones)/sizeof(tones[0]); i+=2) {
playTone(tones[i], tones[i+1]);
}
}
#endif
}
else if ( MEMORY_BUTTON(buttons) && (!savePosition) )
{
// longpress after previous pushes - save this position
beep(NOTE_ACK, pushCount + 1); // first provide feedback to release...
savePosition = true;
}
}
}
}
else
{ // nothing currently pressed
if ( PRESSED(previous) )
{ // just released
// moving?
if (manualMove != Command::NONE)
{
// we were under manual control before, stop now
manualMove = Command::NONE;
} else {
// not moving manually
pushCount++; // short press increase the count
}
}
else
{ // released and idle
// check timeout on release - indicating last press
if ((lastPushTime != 0) && (currentMillis - lastPushTime > CLICK_TIMEOUT))
{
// last press
if ((pushCount >= MIN_SLOT) && MEMORY_BUTTON(lastbutton))
memoryEvent = true; // either store or recall a setting
else { // single push or not a memory button.
startFresh();
// could still be a trigger for something. For now just...
#ifdef FEEDBACK
// play short dull buzz, indicating this is a no-op.
if (feedback) playTone(NOTE_A4, PIP_DURATION);
#endif
}
}
}
}
previous = buttons;
}
#ifdef SERIALCOMMS
#ifdef HUMANSERIAL
int digits=0;
// interpret bytes as ascii digits, report when any non-digit is recieved
// preserve any partially decoded digits.
int readdigits()
{
int r;
while ((r = userSerial.read()) > 0) {
if ((r < 0x30) || (r > 0x39)) {
// non-digit we're done, return what we have
return digits;
}
// it's a digit, add with base10 shift
digits = 10*digits + (r-0x30);
// keep reading...
}
return -1;
}
// human/ascii commands over serial.
// accepts commands like: <T2000,255\n <=3000,. <C0.0. <+200,0. <L.2. <C.. <R,0 <R.34
// can safely accept 16 chars at a time before there's buffer overflow and loss.
// (the 2 numeric fields are terminated by any non-numeric character)
void recvData()
{
const int numChars = 2;
const int numFields = 4; // read/store all 4 fields for simplicity, use only the last 3.
// static variables allows segmented/char-at-a-time decodes
static uint16_t receivedBytes[numFields];
static uint8_t ndx = 0;
int r; // read char/digit
// read 2 chars
while ((ndx < numChars) && ((r = userSerial.read()) != -1))
{
if ((ndx == 0) && (r != rxMarker))
{
// first char is not Rx, keep reading...
continue;
}
receivedBytes[ndx] = r;
++ndx;
}
// read ascii digits
while ((ndx >= numChars) && ((r = readdigits()) != -1)) {
receivedBytes[ndx] = r;
digits = 0; // clear
if (++ndx == numFields) {
// thats all 4 fields. parse/process them now and break-out.
parseData(receivedBytes[1],
receivedBytes[2],
receivedBytes[3]);
ndx = 0;
return;
}
}
}
#else
// modified from https://forum.arduino.cc/index.php?topic=396450.0
// read/process 5 raw bytes at a time or exit if no serial data available.
void recvData()
{
const int numBytes = 5; // read/store all 5 bytes for simplicity, use only the last 4.
// static variables allows segmented/char-at-a-time decodes
static byte receivedBytes[numBytes];
static uint8_t ndx = 0;
int r; // read char
while ((r = userSerial.read()) != -1)
{
if ((ndx == 0) && (r != rxMarker))
{
// first char is not rxMarker, keep reading...
continue;
}
receivedBytes[ndx] = r;
if (++ndx == numBytes)
{ // thats 5 now bytes, parse/process them now and break-out.
parseData(receivedBytes[1],
makeWord(receivedBytes[2], receivedBytes[3]),
receivedBytes[4]);
ndx = 0;
return;
}
}
}
#endif
void writeSerial(byte operation, uint16_t position, uint8_t push_addr, byte marker)
{
// note. serial.write only ever writes bytes. ints/longs get truncated!
userSerial.write(marker);
userSerial.write(operation);
#ifdef HUMANSERIAL
userSerial.print(position); // Tx human-readable output option
userSerial.print(',');
userSerial.print(push_addr);
userSerial.print('\n');
#else
userSerial.write(position >> 8); // high byte
userSerial.write(position & 0xff); // low byte
userSerial.write(push_addr);
#endif
}
void parseData(byte command, uint16_t position, uint8_t push_addr)
{
#ifdef SERIALECHO
writeSerial(command, position, push_addr, rxMarker); // echo command back for debugging
#endif
/*
data start (first byte)
char meaning
-----------------
< start Rx Marker
command (second byte)
cmd meaning
-----------------
+ increase
- decrease
= absolute
C Ask for current location
S Save location to (UpButton) EEPROM
s Save location to Downbutton EEPROM
L Load (Upbutton) location from EEPROM and move
l load Downbutton location from EEPROM and move
W Write arbitrary data to EEPROM
R Read arbitrary data from EEPROM
T play tone
position (third/fourth bytes or 1st digit field. max 65535)
cmd meaning
-----------------
+- relative to current position
=SsW absolute position
T tone frequency
CRLl (ignore)
push_addr (fifth byte or 2nd digit field. max 255)
cmd meaning
-----------------
SLlWwR EEPROM pushCount/slot
T tone duration/4 ms. (250 == 1s)
+-=C (ignore)
Transmitted operations
char meaning
-----------------
> Tx start Marker
E error response
X calibration started
*/
if (command == command_increase)
{
targetHeight = currentHeight + position;
memoryMoving = true;
}
else if (command == command_decrease)
{
targetHeight = currentHeight - position;
memoryMoving = true;
}
else if (command == command_absolute)
{
targetHeight = position;
memoryMoving = true;
}
else if (command == command_current)
{
writeSerial(command_absolute, currentHeight);
}
else if ((command == command_save) || (command == command_save_down))
{
// note. saving against down-button requires adding 32 to push_addr
// or by using command 's'
if (command == command_save_down)
push_addr += DOWN_SLOT_START;
// if position not set, then use currentHeight
if (position == 0)
{
position = currentHeight;
}
// save position to memory location
saveMemory(push_addr, position);
#ifdef MINMAX
// note. L command at same slot will *toggle* min/max heights.
// S command writes it unconditionally. W writes without updating min/maxHeight.
// Nowhere is there a check if limits are outside DANGER_MIN/MAX_HEIGHT...
//if changing memory location for min/max height, update correct variable
if (push_addr == MIN_HEIGHT_SLOT)
{
minHeight = position;
}
else if (push_addr == MAX_HEIGHT_SLOT)
{
maxHeight = position;
}
#endif
}
else if (command == command_load)
{
// check if loading down-button slot
if ((bothbuttons) && (push_addr > DOWN_SLOT_START)) {
push_addr -= DOWN_SLOT_START;
lastbutton = Button::DOWN;
} else
lastbutton = Button::UP;
pushCount = push_addr;
memoryEvent = true;
}
else if ((bothbuttons) && (command == command_load_down))
{
lastbutton = Button::DOWN;
pushCount = push_addr;
memoryEvent = true;
}
else if ((command == command_write) || (command == command_read))
{
if (command == command_write)
eepromPut16(push_addr, position);
writeSerial(command, eepromGet16(push_addr), push_addr);
}
else if (command == command_tone)
{
playTone(position, push_addr*4); // 255*4 ~ 1020ms max
}
#ifdef SERIALERRORS
else
{
// not a recognized command. writeSerial isn't very expressive for this error.
// two options:
//writeSerial(response_error, 0); // respond with a empty error
// or
// respond with the recieved message but with txMarker replaced with 'E'
writeSerial(command, position, push_addr, response_error);
}
#endif
}
#endif
void loop()
{
readButtons();
#ifdef ENABLERESET
if (memoryEvent && (pushCount == FORCE_RESET))
softReset::Reset();
#endif
// Wait before next cycle. 150ms on factory controller, 50ms seems fine.
delayUntil(50);
#ifdef SERIALCOMMS
uint8_t drift = linBurst(); // drift is difference between leg encoders
#else
linBurst();
#endif
// If we are in recalibrate mode or have a bad currentHeight, don't act on input.
if (state >= State::STARTING_RECAL || currentHeight <= 5)
{
return;
}
#ifdef SERIALCOMMS
#ifdef DEBUGHEIGHT
if (oldHeight != currentHeight){
#else
if (memoryMoving == false && oldHeight != currentHeight){
#endif
// report new location
if (oldHeight < currentHeight){
writeSerial(command_increase, currentHeight-oldHeight);
}
else {
writeSerial(command_decrease, oldHeight-currentHeight);
}
writeSerial(command_absolute, currentHeight, drift);
oldHeight = currentHeight;
}
recvData();
#endif
if (memoryEvent)
{
if (pushCount == RECALIBRATE)
{
// do calibration
#ifdef SERIALCOMMS
writeSerial(response_calibration, 0, pushCount);
#endif
state = State::STARTING_RECAL;
}
#ifdef MINMAX
else if (pushCount == MIN_HEIGHT_SLOT)
{
toggleMinHeight();
}
else if (pushCount == MAX_HEIGHT_SLOT)
{
if (USED_DOWN) // 12 presses on either button sets corresponding max/min limits
toggleMinHeight();
else
toggleMaxHeight();
}
#endif
else if (pushCount == BOTHBUTTON_SLOT)
{
toggleBothMode();
}
#ifdef FEEDBACK
else if (pushCount == FEEDBACK_SLOT)
{
toggleFeedback();
}
#endif
else if (savePosition)
{
if (USED_DOWN)
pushCount += DOWN_SLOT_START;
saveMemory(pushCount, currentHeight);
}
else
{
// load position
beep(NOTE_LOW, pushCount);
if (USED_DOWN)
pushCount += DOWN_SLOT_START;
targetHeight = loadMemory(pushCount);
memoryMoving = true;
}
startFresh(); // clears memoryEvent, pushCount, lastPushTime
}
else if (manualMove == Command::UP)
{
memoryMoving = false;
// max() allows escape from recalibration (below DANGER_MIN_HEIGHT)
targetHeight = max(currentHeight + MOVE_OFFSET, DANGER_MIN_HEIGHT);
}
else if (manualMove == Command::DOWN)
{
memoryMoving = false;
// min() allows descend if beyond DANGER_MAX_HEIGHT
targetHeight = min(currentHeight - MOVE_OFFSET, DANGER_MAX_HEIGHT);
}
// avoid moving toward an out-of-bounds position
if ((targetHeight < DANGER_MIN_HEIGHT) || (targetHeight > DANGER_MAX_HEIGHT)) {
#if (defined SERIALCOMMS && defined SERIALERRORS)
writeSerial(response_error, targetHeight); // Indicate an error and the bad targetHeight
#endif
targetHeight = currentHeight; // abandon target
}
// Turn on motors?
if (targetHeight > currentHeight + HYSTERESIS && currentHeight < maxHeight) {
#if (defined SERIALCOMMS && defined DEBUGHEIGHT)
writeSerial(response_up, targetHeight);
#endif
MOTOR_UP;
}
else if (targetHeight < currentHeight - HYSTERESIS && currentHeight > minHeight) {
#if (defined SERIALCOMMS && defined DEBUGHEIGHT)
writeSerial(response_down, targetHeight);
#endif
MOTOR_DOWN;
}
else
{
// some possibilities:
// close enough (maybe still coasting),
// or overshot,
// or out of range!
// so stop
MOTOR_OFF;
}
}
// check if motor is idle
bool isIdle(byte value) {
return (value == LIN_MOTOR_IDLE1 || value == LIN_MOTOR_IDLE2 || value == LIN_MOTOR_IDLE3);
}
uint8_t linBurst()
{
static byte empty[3] = {0, 0, 0};
static byte cmd[3];
byte node_a[3];
byte node_b[3];
static State lastState = State::OFF;
byte lin_cmd = LIN_CMD_IDLE;
// Send PID 17
lin.send(17, empty, 3);
delayUntil(5);
// Recv from PID 09
uint8_t chars = lin.recv(9, node_b, sizeof(node_b));
uint16_t enc_b = node_b[0] | (node_b[1] << 8);
if (chars != sizeof(node_b)+1) {
#ifdef SERIALERRORS
#ifdef SERIALCOMMS
writeSerial(response_error, enc_b, chars, badPID9Marker);
#endif
/*
#ifdef FEEDBACK
if (feedback) playTone(NOTE_A4, PIP_DURATION);
#endif
*/
#endif
return 0;
}
delayUntil(5);
// Recv from PID 08
chars = lin.recv(8, node_a, sizeof(node_a));
uint16_t enc_a = node_a[0] | (node_a[1] << 8);
if (chars != sizeof(node_a)+1) {
#ifdef SERIALERRORS
#ifdef SERIALCOMMS
writeSerial(response_error, enc_a, chars, badPID8Marker);
#endif
/*
#ifdef FEEDBACK
if (feedback) playTone(NOTE_A4, PIP_DURATION);
#endif
*/
#endif
return 0;
}
// Send PID 16, 6 times
for (byte i = 0; i < 6; i++)
{
delayUntil(5);
lin.send(16, 0, 0);
}
uint16_t enc_target = enc_a; //(enc_a+enc_b)/2;
uint16_t enc_min = min(enc_a, enc_b);
uint16_t enc_max = max(enc_a, enc_b);
currentHeight = enc_target;
// monitor drift between motor positions. report if above 20.
if ( enc_max - enc_min > 20) {
#ifdef SERIALERRORS
#ifdef SERIALCOMMS
writeSerial(response_error, enc_min, enc_max-enc_min, DriftMarker);
#endif
#ifdef FEEDBACK
// more serious problem? longer tone...
if (feedback) playTone(NOTE_A4, SHORT_PAUSE);
#endif
#endif
// what kind of corrective action can be taken?
// change state to STOPPING1?
// note. this is seen during recalibration!
}
delayUntil(5);
// Send PID 1
lin.send(1, 0, 0);
// depending on current state, set params for upcoming lin command and update state
switch (state)
{
case State::OFF:
if (user_cmd != Command::NONE)
{
if (isIdle(node_a[2]) && isIdle(node_b[2]))
{
state = State::STARTING;
}
#if (defined SERIALCOMMS && defined SERIAL_IDLE)
writeSerial(response_off, node_a[2], node_b[2], idleMarker); // Indicate the idle variant type
#endif
} else { // Command::NONE
memoryMoving = false; // Definitely not moving, serial can report now.
}
break;
case State::STARTING:
lin_cmd = LIN_CMD_PREMOVE;
switch (user_cmd)
{
case Command::NONE:
state = State::OFF; // maybe lin_cmd = LIN_CMD_IDLE;
break;
case Command::UP:
state = State::UP;
break;
case Command::DOWN:
state = State::DOWN;
break;
}
break;
case State::UP:
enc_target = enc_min;
lin_cmd = LIN_CMD_RAISE;
lastState = State::UP;
if (user_cmd != Command::UP || enc_max >= maxHeight)
{
state = State::STOPPING1;
}
break;
case State::DOWN:
enc_target = enc_max;
lin_cmd = LIN_CMD_LOWER;
lastState = State::DOWN;
if (user_cmd != Command::DOWN || enc_min <= minHeight)
{
state = State::STOPPING1;
}
break;
case State::STOPPING1:
case State::STOPPING2:
case State::STOPPING3:
enc_target = targetHeight; // more accurate stops
lin_cmd = LIN_CMD_FINE;
if (state == State::STOPPING1)
state = State::STOPPING2;
else if (state == State::STOPPING2)
state = State::STOPPING3;
else // State::STOPPING3
state = State::STOPPING4;
break;
case State::STOPPING4:
if (lastState == State::UP)
enc_target = enc_min;
else
enc_target = enc_max;
lin_cmd = LIN_CMD_FINISH;
// only check one, as that's good enough...
if (isIdle(node_a[2]))
{
state = State::OFF;
}
#if (defined SERIALCOMMS && defined SERIAL_IDLE)
writeSerial(response_stop, node_a[2], node_b[2], idleMarker); // Indicate the idle variant type
#endif
break;
// recal stuff here
case State::STARTING_RECAL:
lin_cmd = LIN_CMD_PREMOVE;
state = State::RECAL;
break;
case State::RECAL:
// We want to send 0/0/189
enc_target = 0;
lin_cmd = LIN_CMD_RECALIBRATE;
if (enc_max <= 99 && node_a[2] == 1 && node_b[2] == 1) // Are both motors reporting 99/0/1? We should be bottomed out at this point.
state = State::END_RECAL;
break;
case State::END_RECAL:
// We want to send 99/0/188
enc_target = 99;
lin_cmd = LIN_CMD_RECALIBRATE_END;
state = State::OFF;
targetHeight = enc_max; // prevents immediately resuming previous height
break;
}
// lastly send lin command to PID 18
cmd[0] = enc_target & 0xFF;
cmd[1] = enc_target >> 8;
cmd[2] = lin_cmd;
delayUntil(5);
lin.send(18, cmd, sizeof(cmd));
return (enc_max - enc_min);
}