-
Notifications
You must be signed in to change notification settings - Fork 1
/
FS20Uno.ino
1847 lines (1633 loc) · 58.3 KB
/
FS20Uno.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
/* ===================================================================
* File: FS20Uno.ino
* Author: Norbert Richter <mail@norbert-richter.info>
* Project: Electric rooflight window and shutter controller
* with wallbuttons and FS20-SM8 control using Arduino Uno
* Desc: The control unit consists of
* * Arduino Uno
* * 4 I2C Portexpander MCP23017
* * 2 ELV FS20-SM8 8-channel receiver
* * 16 Relais to control 8 motors:
* * 8 Relais for motor on/off
* * 8 Relais for motot direction.
*
* Operation mode:
* ==============
* Features:
* * Can control up to 4 electrical roof windows with shutter
* * Control windows by using
* * two pushbuttons ("Open" and "Close")
* * two FS20-SM8 channel ("Open" and "Close" via FS20 sender)
* * command using serial interface
* (connected to a Serial2Ethernet interface like WIZNET or a
* RaspberryPi using ser2net it is also usable via network)
* * Optional rain sensor to close roof windows when it is raining
* * Optional restore window position after rain has gone.
*
* Functions:
* * 2 pushbutton (wall button)
* * Opening a motor by pushing the "Open" pushbutton for a short
* time.
* When using the "Open" pushbutton again when motor runs in "Open"
* direction will stop the motor.
* * Closing a motor by pushing the "Close" pushbutton for a short
* time.
* When using the "Close" pushbutton again when motor runs in
* "Close" direction will stop the motor.
* * Pushing both buttons together will stop the current running
* direction anyway.
* * If pushing a button longer than 10 sec, the pressed time until
* releasing the button will be used as new motor running time.
*
* * 2 FS20-SM8 channel
* * Opening a motor by enable the related FS20-SM8 "Open" channel.
* Stop this mode by enable again the related FS20-SM8 "Open"
* channel.
* * Closing a motor by enable the related FS20-SM8 "Close" channel.
* Stop this mode by enable again the related FS20-SM8 "Close"
* channel.
*
* * Serial interface with simple commands
*
*
* Two FS20-SM8 8 channel recevier are used as FS20 receiver, so we
* have 16 channels to control 8 motors in open and close direction.
*
* With this setup we control 4 electric roof windows with electric
* shutter having 24V direct current motors:
* - one motor open/close the window
* - one motor open/close the shutter (jalousie)
*
* Using the Arduino Uno we translate the user inputs from pushbuttons
* and FS20-SM8 channels to motor signals for
* - Off
* - Opening
* - Closing
*
* For further functionality (e. g. command to position the motor to a
* desired position), we keep the following attributes:
* * Motor type (window or jalousie)
* * Motor running time (from open <-> close position)
*
* I2C MCP23017 port enhancer connection:
* MPC1
* Port A (Output): Relais Motor 1-8 ON/OFF
* Port B (Output): Relais Motor 1-8 Direction
* MPC2
* Port A (Output): FS20-SM8 #1 Key 1-8 ("OPEN")
* Port B (Output): FS20-SM8 #2 Key 1-8 ("CLOSE")
* MPC3
* Port A (Input) : FS20-SM8 #1 Status 1-8 ("OPEN")
* Port B (Input) : FS20-SM8 #2 Status 1-8 ("CLOSE")
* FS20-SM8 outputs connect signal to GND (0=active)
* MPC4
* Port A (Input) : Pushbutton ("OPEN")
* Port B (Input) : Pushbutton ("CLOSE")
*
* Two additonal inputs are used as rains sensor and rain sensor enabled.
*
* Motor control:
* ----------------------------
* Each motor will be completyl controlled by Arduino Uno. There are
* no direct connections of FS20-SM8 channel outputs or pushbutton to
* motor relais control signal.
*
* Each motor used two additional porperties:
* * Motor type (window or jalousie)
* * Motor running time (from open <-> close position)
* Both properties are set to default values using the program defines
* DEFAULT_MOTORTYPE, MOTOR_WINDOW_MAXRUNTIME and MOTOR_JALOUSIE_MAXRUNTIME.
* They can be changed during operation with the commands "MOTORTYPE"
* and "MOTORTIME". Values are stored in EEPROM.
* Motors having property WINDOW are closed when rain sensor is enable
* and rain is active.
* Each motor will be automatically switch off after a maximum runtime
* including an additonal overtravel time. The motor runtime is used to
* properly calculate the current position between open and close.
* To be sure that a window will be realy closed, each motor can have
* and optional overtravel time.
* The runtime and overtime values can be set via program defaults, by
* using the serial command interface or (runtime only) by using the
* auto-learn function pressing the related pushbutton for longer than
* 10 seconds. Keep the pushbutton as long as the window or shutter
* moves, then release it.
*
* Motor protection:
* Due to the electromagnetic induction effect of the direct current
* motors, there are several protection implemented:
* * The motor voltage is switched on only after direction relais
* was switched into proper direction and attend relais operation
* time (OPERATE_TIME).
* * Also motor is switched off first if the motor is still running
* and we need to reverse the direction attend relais operation
* time (OPERATE_TIME). Before motor is switch on in reverse direction
* we also attend an additonal MOTOR_SWITCHOVER time to protect motor
* itself.
*
* Pushbutton:
* ----------------------------
* Pusbutton connects a pull-up input to GND (means 0=active).
* Pushbutton function:
* - Button "OPEN": Switch motor to "Open",
* pushing a second time switch motor off.
* - Button "CLOSE": Switch motor to "Close",
* pushing a second time switch motor off.
* - Push both buttons together also swich motor off.
* - Keep a pushbutton pressed longer than 10 sec, activates a auto-
* learn function to measure the real runtime for a motor needs to
* move a window or shutter.
* Pusbuttons having a higher priority than FS20-SM8 channel outputs
* so if a FS20-SM8 channel is active, pushbutton overwrite the state
* and possibly switchs FS20-SM8 channel off.
*
* FS20-SM8:
* ----------------------------
* FS20-SM8 channel outputs are also used to control the motors. Because
* we connect the FS20-SM8 channel key inputs also to Arduino, we are
* able to activly control the FS20-SM8 channel by soft-push the
* FS20-SM8 key. So we can switch FS20-SM8 channel, which are switch
* by key pressing or by FS20 control signal.
* FS20 control conditions:
* * two active FS20-SM8 channels, which are related to the same motor
* will be decoupled:
* If a FS20-SM8 output will be go active even the related other
* FS20-SM8 channel output is active, the other FS20-SM8 channel
* will be switch off - means the latest trigger wins.
* * only rising slope will activate the function.
* * only falling slope will deactive the function.
* * Pushbutton using will overwrite FS20-SM8 channel, so it will be
* disabled if necessary.
*
* Rainsensor
* ----------------------------
* Rain sensor can be used to automatically close all motors of type
* WINDOW. An optional RESUME function will reopen all windows which
* are not closed when rain begins to the previous position.
* The resume functionaliy only works properly, if the motor runtime
* are properly set to a real value.
*
* Rain sensor input:
* Can be connect to input "RAIN_INPUT", the active level polarity can
* be set using "RAIN_INPUT_ACTIVE".
*
* Rain sensor enable input:
* A second input connected to "RAIN_ENABLE" can be used to enable/dis-
* able Rain sensor input. This is usefull if you want to temporarly
* switch the rain sensor function off using a wall button.
* The active level polarity can be set using "RAIN_ENABLE_ACTIVE".
* If input "RAIN_ENABLE" is inactive, than rain sensor input signal
* will be ignored.
*
* Control-Kommando "RAIN"
* Both inputs for rain can be overruled by control command "RAIN":
* * RAIN WET|ON|DRY|OFF
* Simulate the rain input signal: WET|ON =Raining
* DRY|OFF=Inaktiv
* * RAIN ENABLE|DISABLE
* Simulate rain enable input: ENABLE =Rain function enabled
* DISABLE=Rain function disabled
* * RAIN AUTO
* Because using of one of the above simulation commands switch
* of the automatic mode, this command re-enables the physical input
*
* * RAIN RESUME <s>/FORGET
* RESUME <s> reopen all windows after rain has gone to the previous
* position after a delay of <s> seconds.
* The delay <s> can be used to prevent that the windows are closed
* and reopened in short times when it is not permanently raining.
* The resume functonaly can be disabled by using "RAIN FORGET". In
* this case the windows are close on rain but not reopened after
* rain has gone.
* ===================================================================*/
#include <Arduino.h>
#include <errno.h>
#include <EEPROM.h> // https://www.arduino.cc/en/Reference/EEPROM
#include <Wire.h> // https://www.arduino.cc/en/Reference/Wire
#include <MsTimer2.h> // http://playground.arduino.cc/Main/MsTimer2
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2
#include <Adafruit_SleepyDog.h> // https://github.com/adafruit/Adafruit_SleepyDog
// Eigene includes
#include "SerialCommand.h" // https://github.com/scogswell/ArduinoSerialCommand
#include "Xtea.h"
#include "FS20Uno.h"
#include "I2C.h"
#define PROGRAM F("FS20Uno") // program name
#define VERSION F("4.05") // program version
#include "REVISION.h" // Build (changed from git hook)
#define DATAVERSION 126 // can be used to invalidate EEPROM data
#define WATCHDOG_ENABLED // #undef to disable watchdog function
/* ===================================================================
* DEBUG SETTINGS
* ===================================================================*/
/* Uncomment next line to test the Arduino library millis() overflow
* millis() will then start with TEST_MILLIS_TIMER [ms]
* before first overflow (max 49 days 17:02:47.295),
*/
//#define TEST_MILLIS_TIMER 30000L // start with 30 sec before overflow
/* Debug outputs:
* You can not use all debug outputs together because default program
* size is to big. Use the debug code size value to estimate which
* debug may be enabled together.
* Note: Debugging disables all the build-in online help */
#undef DEBUG_PINS // 0,2 kB: enable debug output pins
#undef DEBUG_RUNTIME // 0.4 kB: enable runtime debugging
#undef DEBUG_SETUP // 0.1 kB: enable setup related outputs
#undef DEBUG_WATCHDOG // 0.2 kB: enable watchdog related outputs
#undef DEBUG_EEPROM // 2.0 kB: enable EEPROM related outputs
#undef DEBUG_SERIALCMD // 0.3 kB: enable Serial cmd interface related outputs
#undef DEBUG_PASSWD // 0.5 kB: enable password related outputs
#undef DEBUG_CMD_RESTORE // 0.1 kB: enable CMD RESTORE related outputs
#undef DEBUG_SM8STATUS // 1.1 kB: enable FS20-SM8-output related output
#undef DEBUG_PUSHBUTTON // 0.9 kB: enable pushbutton related output
#undef DEBUG_SM8OUTPUT // 0.5 kB: enable FS20-SM8-key related output
#undef DEBUG_MOTOR // 1.7 kB: enable motor control related output
#undef DEBUG_MOTOR_DETAILS // 0.5 kB: enable motor control details output
#undef DEBUG_RAIN // 1.0 kB: enable rain sensor related output
#undef DEBUG_ALIVE // 0.1 kB: enable program alive signal output
#if defined(DEBUG_PINS) || \
defined(DEBUG_RUNTIME) || \
defined(DEBUG_SETUP) || \
defined(DEBUG_WATCHDOG) || \
defined(DEBUG_EEPROM) || \
defined(DEBUG_SERIALCMD) || \
defined(DEBUG_PASSWD) || \
defined(DEBUG_CMD_RESTORE) || \
defined(DEBUG_SM8STATUS) || \
defined(DEBUG_PUSHBUTTON) || \
defined(DEBUG_SM8OUTPUT) || \
defined(DEBUG_MOTOR) || \
defined(DEBUG_MOTOR_DETAILS) || \
defined(DEBUG_RAIN) || \
defined(DEBUG_ALIVE)
#define DEBUG_OUTPUT
#undef WATCHDOG_ENABLED
#endif
#ifdef DEBUG_PINS
#define DBG_INT 12 // Debug PIN = D12
#define DBG_MPC 11 // Debug PIN = D11
#define DBG_TIMER 10 // Debug PIN = D10
#endif
/* Run time measurement */
#ifdef DEBUG_RUNTIME
#define DEBUG_RUNTIME_START(val) unsigned long val = micros();
#define DEBUG_RUNTIME_END(funcName,val) printRuntime(F(funcName), val);
#else
#define DEBUG_RUNTIME_START(val)
#define DEBUG_RUNTIME_END(funcName,val)
#endif
/* ===================================================================
* Global Vars
* ===================================================================*/
// Uptime
volatile unsigned int millisOverflow = 0;
unsigned long prevMillis = 0;
unsigned long savedOperationTime = 0;
// Interrup soft enable flags
volatile bool extISREnabled = false;
volatile bool timerISREnabled = false;
volatile bool isrTrigger = false;
// timer vars
TIMER ledTimer;
LEDPATTERN currentLEDPattern;
byte currentLEDBitCount;
TIMER runTimer;
#if (1000/TIMER_MS)<=UINT8_MAX
byte secTimerCount;
#elif (1000/TIMER_MS)<=UINT16_MAX
WORD secTimerCount;
#else
DWORD secTimerCount;
#endif
// MPC output data
/* Motor
* Lower Bits: Motor on/off
* Upper Bits: Motor direction */
volatile IOBITS valMotorRelais = IOBITS_ZERO; // wanted value
volatile IOBITS regMotorRelais = IOBITS_ZERO; // value put to MPC
/* SM8 Keys
* Lower Bits: Motor opening
* Upper Bits: Motor closing */
volatile IOBITS valSM8Button = ~IOBITS_ZERO;
/* Values read out from MCP23017 when MPC triggers an IRQ
* Lower Bits: Motor opening
* Upper Bits: Motor closing */
volatile IOBITS irqSM8Status = IOBITS_ZERO;
volatile IOBITS irqPushButton = IOBITS_ZERO;
/* Values used within program logic
* Lower Bits: Motor opening
* Upper Bits: Motor closing */
volatile IOBITS curSM8Status = IOBITS_ZERO;
IOBITS SM8StatusIgnore = IOBITS_ZERO;
volatile IOBITS curPushButton = IOBITS_ZERO;
/* Debounce counter for FS20-SM8 outputs and pushbuttons */
volatile char debSM8Status[IOBITS_CNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
volatile char debPushButton[IOBITS_CNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
/* Motor control values:
* 0: Motor off
* >0: Motor opening 1=immediately, >1=delay in ms before opening)
* <0: Motor closing -1=immediately, <1=abs(delay) in ms before closing)
* delay values are in ms/TIMER_MS
*/
volatile MOTOR_CTRL MotorCtrl[MAX_MOTORS] = {MOTOR_OFF,MOTOR_OFF,MOTOR_OFF,MOTOR_OFF,MOTOR_OFF,MOTOR_OFF,MOTOR_OFF,MOTOR_OFF};
// Bitmask for motors which are switch off during IRQ
volatile MOTORBITS sendStatusMOTOR_OFF;
/* Motor timeout counter: Counted down within timer IRQ and switches
* motor off if getting 0 */
volatile MOTOR_TIMER MotorTimeout[MAX_MOTORS] = {0,0,0,0,0,0,0,0};
/* Current motor positions (counter values) */
volatile MOTOR_TIMER MotorPosition[MAX_MOTORS] = {0,0,0,0,0,0,0,0};
/* Requested motor positions (counter values) or NO_POSITION if inactive */
volatile MOTOR_TIMER destMotorPosition[MAX_MOTORS] = {NO_POSITION,NO_POSITION,NO_POSITION,NO_POSITION,NO_POSITION,NO_POSITION,NO_POSITION,NO_POSITION};
/* Stored motor positions (percent values) when rain starts */
volatile byte resumeMotorPosition[MAX_MOTORS] = {NO_RESUME_POSITION,NO_RESUME_POSITION,NO_RESUME_POSITION,NO_RESUME_POSITION,NO_RESUME_POSITION,NO_RESUME_POSITION,NO_RESUME_POSITION,NO_RESUME_POSITION};
/* Bit mask which controls if motor resume position storing is locked
* This prevents motor resume position will be overwritten with wrong
* values if rain status is flapping within rain resume delay time.
* It will be set when motor position is stored and released every time
* motor is switched from on to off or resumeDelay is NO_RESUME_DELAY */
volatile MOTORBITS lockStoreResumePosition;
/* Delay to count down before resumes window position after rain */
volatile WORD resumeDelay = NO_RESUME_DELAY;
/* Timer for auto-learn function: Counts the time of pressed pushbutton */
TIMER PushButtonTimer[MAX_MOTORS] = {0,0,0,0,0,0,0,0};
/* SM8 key control "pushed"-time */
volatile SM8_TIMEOUT SM8Timeout[IOBITS_CNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
/* Rain sensor */
/* Soft rain detection (not permanently stored in EEPROM) */
bool softRainInput = false;
/* Rain sensor input and enable input */
Bounce debEnable = Bounce();
Bounce debInput = Bounce();
/* Rain flag */
bool isRaining = false;
/* EEPROM Variablen */
struct MYEEPROM eeprom;
// Command interface login status
bool prevUnlocked; // remember value for output new status
volatile bool cmdUnlocked; // global cmd interface unlock state
volatile WORD cmdLoginTimeout; // auto logout timer
/* Strings in PROGMEM */
const char fstrON[] PROGMEM = "ON";
const char fstrOFF[] PROGMEM = "OFF";
/* ===================================================================
* Program
* ===================================================================*/
#ifdef DEBUG_RUNTIME
void printRuntime(const __FlashStringHelper *funcName, unsigned long starttime)
{
unsigned long duration = micros() - starttime;
SerialPrintUptime();
SerialPrintf(F("RUNTIME - "));
Serial.print(funcName);
SerialPrintfln(F(" duration: %lu.%03lu ms"), duration / 1000L, duration % 1000L);
}
#endif
/* ===================================================================
* Function: setup
* Return:
* Arguments:
* Description: setup function runs once
* when you press reset or power the board
* ===================================================================*/
void setup()
{
Watchdog.disable();
#ifdef TEST_MILLIS_TIMER
cli(); //halt the interrupts
//timer0_millis = UINT32_MAX - TEST_MILLIS_TIMER; //change the value of the register
timer0_millis = (3600L-30L)*1000L;
sei(); //re-enable the interrupts
#endif
DEBUG_RUNTIME_START(msSetup);
// indicate setup started
pinMode(STATUS_LED, OUTPUT); // for onboard LED
digitalWrite(STATUS_LED, HIGH);
Serial.begin(SERIAL_BAUDRATE);
Serial.println();
// Init random generator
long r = millis();
#ifdef DEBUG_SETUP
SerialTimePrintfln(F("setup - r=%ld"), r);
#endif
int an = 0;
#ifdef RANDOM_SEED_ANALOG_READ1
an = analogRead(RANDOM_SEED_ANALOG_READ1);
r = an;
#ifdef DEBUG_SETUP
SerialTimePrintfln(F("setup - AN1: %d"), an);
#endif
#endif
#ifdef RANDOM_SEED_ANALOG_READ2
an = analogRead(RANDOM_SEED_ANALOG_READ2);
r <<= 10;
r |= an;
#ifdef DEBUG_SETUP
SerialTimePrintfln(F("setup - AN2: %d"), an);
#endif
#endif
#ifdef RANDOM_SEED_ANALOG_READ3
an = analogRead(RANDOM_SEED_ANALOG_READ3);
r <<= 10;
r |= an;
#ifdef DEBUG_SETUP
SerialTimePrintfln(F("setup - AN3: %d"), an);
#endif
#endif
#ifdef DEBUG_SETUP
SerialTimePrintfln(F("setup - randomSeed(%ld)"), r);
#endif
randomSeed(r);
// Read EEPROM program setting
eepromInitVars();
// Init program vars
initVars();
// Init command interface
setupSerialCommand();
if ( !eeprom.SendStatus ) {
printProgramInfo(true);
}
sendStatus(false,SYSTEM, F("%S %S.%S"), PROGRAM, VERSION, REVISION);
#ifdef DEBUG_OUTPUT
SerialTimePrintfln(F("setup - Debug output enabled"));
#endif
#ifdef DEBUG_PINS
SerialTimePrintfln(F("setup - Debug pins enabled"));
pinMode(DBG_INT, OUTPUT);
pinMode(DBG_MPC, OUTPUT);
pinMode(DBG_TIMER, OUTPUT);
#endif
// Input pins pulled-up
pinMode(RAIN_ENABLE, INPUT_PULLUP);
digitalWrite(RAIN_ENABLE, RAIN_ENABLE_ACTIVE==0 ? LOW:HIGH );
// After setting up the button, setup the Bounce instance
debEnable.attach(RAIN_ENABLE);
debEnable.interval(RAIN_DEBOUNCE_TIME); // interval in ms
pinMode(RAIN_INPUT, INPUT_PULLUP);
digitalWrite(RAIN_INPUT, RAIN_INPUT_ACTIVE==0 ? HIGH:LOW);
// After setting up the button, setup the Bounce instance
debInput.attach(RAIN_INPUT);
debInput.interval(RAIN_DEBOUNCE_TIME);
#ifdef DEBUG_PINS
digitalWrite(DBG_INT, LOW);
digitalWrite(DBG_MPC, LOW);
digitalWrite(DBG_TIMER, LOW);
#endif
Wire.begin();
// expander configuration register
expanderWriteBoth(MPC_MOTORRELAIS, IOCON, 0b00100100); // sequential mode, INT Open-drain output
expanderWriteBoth(MPC_SM8BUTTON, IOCON, 0b00100100); // sequential mode, INT Open-drain output
expanderWriteBoth(MPC_SM8STATUS, IOCON, 0b01100100); // mirror interrupts, sequential mode, INT Open-drain output
expanderWriteBoth(MPC_PUSHBUTTON, IOCON, 0b01100100); // mirror interrupts, sequential mode, INT Open-drain output
// enable pull-up on switches
expanderWriteBoth(MPC_MOTORRELAIS, GPPU, 0xFF); // pull-up resistor A/B
expanderWriteBoth(MPC_SM8BUTTON, GPPU, 0xFF); // pull-up resistor A/B
expanderWriteBoth(MPC_SM8STATUS, GPPU, 0xFF); // pull-up resistor A/B
expanderWriteBoth(MPC_PUSHBUTTON, GPPU, 0xFF); // pull-up resistor A/B
// port data
expanderWriteWord(MPC_MOTORRELAIS, GPIO, regMotorRelais);
expanderWriteWord(MPC_SM8BUTTON, GPIO, valSM8Button);
expanderWriteWord(MPC_SM8STATUS, GPIO, ~IOBITS_ZERO);
expanderWriteWord(MPC_PUSHBUTTON, GPIO, ~IOBITS_ZERO);
// port direction
expanderWriteBoth(MPC_MOTORRELAIS, IODIR, 0x00); // OUTPUT
expanderWriteBoth(MPC_SM8BUTTON, IODIR, 0x00); // OUTPUT
expanderWriteBoth(MPC_SM8STATUS, IODIR, 0xFF); // INPUT
expanderWriteBoth(MPC_PUSHBUTTON, IODIR, 0xFF); // INPUT
// invert polarity
expanderWriteBoth(MPC_SM8STATUS, IOPOL, 0xFF); // invert polarity of signal
expanderWriteBoth(MPC_PUSHBUTTON, IOPOL, 0xFF); // invert polarity of signal
// interrupt on change to previous one
expanderWriteBoth(MPC_PUSHBUTTON, INTCON, 0x00); // enable interrupts
// enable interrupts on input MPC
expanderWriteBoth(MPC_SM8STATUS, GPINTEN, 0xFF); // enable interrupts
expanderWriteBoth(MPC_PUSHBUTTON, GPINTEN, 0xFF); // enable interrupts
// read from interrupt capture ports to clear them
expanderRead(MPC_SM8STATUS, INTCAPA);
expanderRead(MPC_SM8STATUS, INTCAPB);
expanderRead(MPC_PUSHBUTTON, INTCAPA);
expanderRead(MPC_PUSHBUTTON, INTCAPB);
// MPC23017 pin 19 are connected together to an Ardunino IRQ input
pinMode(MPC_INT_INPUT, INPUT_PULLUP);// make int input
digitalWrite(MPC_INT_INPUT, HIGH); // enable pull-up as we have made
// the interrupt pins open drain
// Disable controller interrupts
noInterrupts();
// Disable interrupt processing too
extISREnabled = false;
timerISREnabled = false;
// External interrupt
attachInterrupt(digitalPinToInterrupt(MPC_INT_INPUT), extISR, FALLING);
// Timer2 interrupt
MsTimer2::set(TIMER_MS, timerISR);
MsTimer2::start();
// Enable controller interrupts
interrupts();
// Init watchdog
watchdogInit();
// Reset FS20-SM8
clrSM8Status();
// Clear interrupt flag register by reading data
curSM8Status = expanderReadWord(MPC_SM8STATUS, GPIO);
curPushButton = expanderReadWord(MPC_PUSHBUTTON, GPIO);
// clear interrupt capture register by reading
expanderReadWord(MPC_SM8STATUS, INTCAP);
expanderReadWord(MPC_PUSHBUTTON, INTCAP);
// clear again interrupt flag register by reading flag register
expanderReadWord(MPC_SM8STATUS, INFTF);
expanderReadWord(MPC_PUSHBUTTON, INFTF);
// Enable interrupt processing
extISREnabled = true;
timerISREnabled = true;
prevMillis = millis();
// Finished
digitalWrite(STATUS_LED, LOW);
#ifdef DEBUG_SETUP
SerialTimePrintfln(F("setup - done, starting main loop()"));
#endif
DEBUG_RUNTIME_END("setup()",msSetup);
// Manual settings of single EEPROM vars
//~ eeprom.OperatingHours = 0;
//~ eepromWriteVars();
sendStatus(false,SYSTEM, F("START"));
}
/* ===================================================================
* Function: initVars
* Return:
* Arguments:
* Description: Init program vars
* ===================================================================*/
void initVars()
{
byte i;
for(i=0; i<MAX_MOTORS; i++) {
MotorPosition[i] = eeprom.MotorPosition[i];
}
// Variablen initalisieren
currentLEDPattern = eeprom.LEDPatternNormal;
currentLEDBitCount = 0;
ledTimer = millis() + (TIMER)eeprom.LEDBitLenght;
runTimer = millis() + (TIMER)ALIVE_TIMER;
secTimerCount = 0;
sendStatusMOTOR_OFF = 0;
cmdUnlocked = false;
prevUnlocked = false;
cmdLoginTimeout = 0;
lockStoreResumePosition = 0;
}
/* ===================================================================
* Function: extISR
* Return:
* Arguments:
* Description: Interrupt service routine
* called when external pin D2 goes from 1 to 0
* ===================================================================*/
void extISR()
{
if ( extISREnabled )
{
#ifdef DEBUG_PINS
digitalWrite(DBG_INT, !digitalRead(DBG_INT));
#endif
isrTrigger = true;
}
}
/* ===================================================================
* Function: timerISR
* Return:
* Arguments:
* Description: Timer Interrupt service routine
* called every TIMER_MS ms
* ===================================================================*/
void timerISR()
{
if ( timerISREnabled )
{
byte i;
#ifdef DEBUG_PINS
digitalWrite(DBG_TIMER, !digitalRead(DBG_TIMER));
#endif
// Check millis() timer overflow
if ( millis() < prevMillis ) {
millisOverflow++;
prevMillis = millis();
}
// Delay for rain RESUME command
if ( resumeDelay!=NO_RESUME_DELAY && resumeDelay>0 ) {
resumeDelay--;
}
for (i = 0; i < IOBITS_CNT; i++) {
// Debounce FS20-SM8 outputs
if ( debSM8Status[i] > 0 ) {
debSM8Status[i]--;
}
else {
bitWrite(curSM8Status, i, bitRead(irqSM8Status, i));
}
// Debounce pushbuttons
if ( debPushButton[i] > 0 ) {
debPushButton[i]--;
}
else {
bitWrite(curPushButton, i, bitRead(irqPushButton, i));
}
/* SM8 key control timeout
* FS20-SM8 key control press signal must be carefully
* not longer than a short time, because otherwise the
* FS20-SM8 channel will go into programming mode (> 5 s) */
if ( SM8Timeout[i] > 0 ) {
if ( --SM8Timeout[i] == 0 ) {
// SM8 key timer timout, reset FS20-SM8 key output
bitSet(valSM8Button, i);
}
}
}
// Control MPC motor bits
// (MPC register will not be written within IRQ service rouutine)
for (i = 0; i < MAX_MOTORS; i++) {
// Measure runtime
if ( bitRead(regMotorRelais, i) ) {
// Motor is on, determine direction
if ( bitRead(regMotorRelais, i + MAX_MOTORS) ) {
// Motor runs in open direction
if ( MotorPosition[i] < (eeprom.MaxRuntime[i] / TIMER_MS) ) {
++MotorPosition[i];
}
}
else {
// Motor runs in close direction
if ( MotorPosition[i]>0 ) {
--MotorPosition[i];
}
}
// If a motor destination position is set, check it
if ( destMotorPosition[i] != NO_POSITION ) {
// Motor position achieved?
if ( MotorPosition[i] == destMotorPosition[i] ) {
// Motor OFF
if ( MotorCtrl[i] != MOTOR_OFF ) {
bitSet(sendStatusMOTOR_OFF, i);
}
MotorCtrl[i] = MOTOR_OFF;
// Clear destination position
destMotorPosition[i] = NO_POSITION;
// Unlock position storing
bitClear(lockStoreResumePosition, i);
}
}
}
// Check motor timeout
if ( MotorTimeout[i] > 0 ) {
--MotorTimeout[i];
if ( MotorTimeout[i] == 0 ) {
// Motor timeout, switch motor off
if ( MotorCtrl[i] != MOTOR_OFF ) {
bitSet(sendStatusMOTOR_OFF, i);
}
MotorCtrl[i] = MOTOR_OFF;
// Unlock position storing
bitClear(lockStoreResumePosition, i);
}
}
// Motor delay control
if ( MotorCtrl[i] > MOTOR_OPEN ) {
--MotorCtrl[i];
// Motor opening, motor off
bitSet(valMotorRelais, i + MAX_MOTORS);
bitClear(valMotorRelais, i);
}
else if ( MotorCtrl[i] < MOTOR_CLOSE ) {
++MotorCtrl[i];
// Motor closing, motor off
bitClear(valMotorRelais, i + MAX_MOTORS);
bitClear(valMotorRelais, i);
}
else {
// No more delay, motor should be set to a defined state
if ( MotorCtrl[i] == MOTOR_OPEN ) {
// Motor to opening, motor on
bitSet(valMotorRelais, i + MAX_MOTORS);
bitSet(valMotorRelais, i);
}
else if ( MotorCtrl[i] == MOTOR_CLOSE ) {
// Motor to closing, motor on
bitClear(valMotorRelais, i + MAX_MOTORS);
bitSet(valMotorRelais, i);
}
else if ( MotorCtrl[i] == MOTOR_OFF ) {
// Motor off, direction relais to close
bitClear(valMotorRelais, i);
bitClear(valMotorRelais, i + MAX_MOTORS);
}
}
}
// Timer in sec steps
if ( ++secTimerCount>=(1000/TIMER_MS) ) {
// executed every second
if ( cmdLoginTimeout>0 ) {
cmdLoginTimeout--;
if ( cmdLoginTimeout == 0 ) {
cmdUnlocked = false;
}
}
// Reset second counter
secTimerCount = 0;
}
#ifdef DEBUG_PINS
digitalWrite(DBG_TIMER, !digitalRead(DBG_TIMER));
#endif
}
}
/* ===================================================================
* Function: handleMPCInt
* Return:
* Arguments:
* Description: MPC IRQ handling outside IRQ routine, because we can
* not handle I2C interfacing within IRQ subroutine.
* Read out MPC Register into global variables
* ===================================================================*/
void handleMPCInt()
{
// Check if an MPC irq occured
if ( isrTrigger ) {
byte i;
#ifdef DEBUG_PINS
digitalWrite(DBG_INT, !digitalRead(DBG_INT));
#endif
isrTrigger = false;
if ( expanderReadWord(MPC_SM8STATUS, INFTF) )
{
#ifdef DEBUG_PINS
digitalWrite(DBG_MPC, HIGH);
#endif
irqSM8Status = expanderReadWord(MPC_SM8STATUS, GPIO);
for (i = 0; i < IOBITS_CNT; i++) {
if ( bitRead(curSM8Status,i) != bitRead(irqSM8Status,i) ) {
debSM8Status[i] = SM8_DEBOUNCE_TIME / TIMER_MS;
}
}
#ifdef DEBUG_PINS
digitalWrite(DBG_MPC, LOW);
#endif
}
if ( expanderReadWord(MPC_PUSHBUTTON, INFTF) )
{
static IOBITS tmpPushButton = IOBITS_ZERO;
#ifdef DEBUG_PINS
digitalWrite(DBG_MPC, HIGH);
#endif
irqPushButton = expanderReadWord(MPC_PUSHBUTTON, GPIO);
#ifdef DEBUG_PUSHBUTTON
SerialTimePrintfln(F("handleMPCInt - IRQ - irqPushButton: 0x%04x"), irqPushButton);
#endif
for (i = 0; i < IOBITS_CNT; i++) {
if ( bitRead(tmpPushButton,i) != bitRead(irqPushButton,i) ) {
#ifdef DEBUG_PUSHBUTTON
SerialTimePrintfln(F("handleMPCInt - IRQ - debounce key %d"), i);
#endif
debPushButton[i] = WPB_DEBOUNCE_TIME / TIMER_MS;
bitWrite(tmpPushButton, i, bitRead(irqPushButton,i));
}
}
#ifdef DEBUG_PINS
digitalWrite(DBG_MPC, LOW);
#endif
}
#ifdef DEBUG_PINS
digitalWrite(DBG_INT, !digitalRead(DBG_INT));
#endif
}
watchdogReset();
}
#if defined(DEBUG_MOTOR) || defined(DEBUG_MOTOR_DETAILS)
void debugPrintMotorStatus(bool from)
{
static MOTOR_CTRL prevMotorCtrl[MAX_MOTORS] = {MOTOR_OFF, MOTOR_OFF, MOTOR_OFF, MOTOR_OFF, MOTOR_OFF, MOTOR_OFF, MOTOR_OFF, MOTOR_OFF};
bool motorChanged;
byte i;
motorChanged = false;
for (i = 0; i < MAX_MOTORS && !motorChanged; i++) {
motorChanged = prevMotorCtrl[i]!=MotorCtrl[i];
}
if ( motorChanged ) {
byte i;
SerialTimePrintfln(F("debugPrintMotorStatus(%i) - ----------------------------------------"), from);
SerialTimePrintfln(F("debugPrintMotorStatus(%i) - M1 M2 M3 M4 M5 M6 M7 M8"), from);
SerialTimePrintf (F("debugPrintMotorStatus(%i) - "), from);
for (i = 0; i < MAX_MOTORS; i++) {
if (MotorCtrl[i] == 0) {
SerialPrintf(F(" off"));
}
else {
SerialPrintf(F("%5d"), MotorCtrl[i]);
}
prevMotorCtrl[i] = MotorCtrl[i];
}
printCRLF();
}
}
#endif
/* ===================================================================
* Function: clrSM8Status
* Return:
* Arguments:
* Description: FS20-SM8 channel reset
* Switches all channel in ON-state to OFF
* ===================================================================*/
void clrSM8Status(void)
{
// Read current value from input MPC
curSM8Status = expanderReadWord(MPC_SM8STATUS, GPIO);
curPushButton = expanderReadWord(MPC_PUSHBUTTON, GPIO);
for(byte channel=0; channel<IOBITS_CNT; channel++) {
if ( bitRead(curSM8Status, channel) ) {
bitClear(valSM8Button, channel);
}
}
expanderWriteWord(MPC_SM8BUTTON, GPIO, valSM8Button);
delay(FS20_SM8_IN_RESPONSE);
for(byte channel=0; channel<IOBITS_CNT; channel++) {
if ( bitRead(curSM8Status, channel) ) {
bitSet(valSM8Button, channel);
}
}
expanderWriteWord(MPC_SM8BUTTON, GPIO, valSM8Button);
watchdogReset();
}
/* ===================================================================
* Function: ctrlSM8Status
* Return:
* Arguments:
* Description: FS20-SM8 channel output handling
* ===================================================================*/
void ctrlSM8Status(void)
{
static IOBITS tmpSM8Status = IOBITS_ZERO;
/* FS20 SM8 Output */
static IOBITS SM8Status;
static IOBITS prevSM8Status = IOBITS_ZERO;
if ( (tmpSM8Status != curSM8Status) ) {
#ifdef DEBUG_SM8STATUS