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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
'
' solar.bas  - Photovoltaik Datenlogger
'
' (c) 2009-2011 Kai Morich (http://www.kai-morich.de)
'
 
Dim Cvs_id As String * 60
Cvs_id = "$Id$"
 
$regfile = "m168def.dat"
$crystal = 12000000
$loadersize = 2048                                          ' loader start =$3800=14336
$baud = 19200
 
$hwstack = 64                                               ' 20
$swstack = 32                                               ' 1
$framesize = 64                                             ' 1 (+24 for bascom)
 
Const Xromdbg = 0
Const Withdbg = 0
#if Withdbg
$dbg
#endif
 
'-------------------------------------------------------------------------------
' pins
 
' lcd
Config Lcdpin = Pin , Db4 = Portc.3 , Db5 = Portc.2 , Db6 = Portc.1 , Db7 = Portb.4 , E = Portc.4 , Rs = Portc.5
Config Lcd = 16 * 2
Lcd_light Alias Portb.2                                     ' lcd backlight + stromzähler beleuchtung
Config Lcd_light = Output
 
' i2c
Config Sda = Portd.6                                        ' ext. 4k7 pullup
Config Scl = Portd.5                                        ' ext. 4k7 pullup
'  ds1307 - echtzeituhr - siehe clock_... funktionen
Ds1307_sqw Alias Pind.2                                     ' sekundentakt -> INT0
Set Ds1307_sqw                                              ' avr int. pullup
Const Ds1307_ = &HD0
Const Ds1307w = &HD0
Const Ds1307r = &HD1
'  24c512 - 64kb eeprom - siehe xrom_... funktionen
Const Eeprom_ = &HA0
Const Eepromw = &HA0
Const Eepromr = &HA1
 
Btn1 Alias Pind.3                                           ' anzeige-modus taster
Btn2 Alias Pind.4                                           ' anzeige-licht taster
Led1 Alias Portb.0                                          ' status
Twl_out Alias Portb.3                                       ' dämmerungs-schaltausgang (twilight)
Config Btn1 = Input
Config Btn2 = Input
Config Led1 = Output
Config Twl_out = Output
Set Btn1
Set Btn2
' btn... auch als key_... definiert
 
Cny70_pwr Alias Portb.1                                     ' saft für cny70-irdiode
Cny70_out Alias Portc.0                                     ' ausgang cny70-transistor
Cny70_led Alias Portd.7                                     ' kontroll-led für cny70 zustand
Config Cny70_pwr = Output
Config Cny70_led = Output
 
 
Goto Main
 
'-------------------------------------------------------------------------------
' einige variablen/konstanten vorab, da funktionsübergreifend verwendet
 
Const Pwr_cnt_kwh = 75                                      ' Stromzähler mit 75 Umdrehungen pro kWh
Const Pwr_watt_hsec = 4800000
' 1 rot      1 rot      1000 W     1 rot   1000*360000
' ----- = ----------- = ----    -> ----- = ----------- W = 4.800.000 W
'   h     360000 hsec    75         hsec       75
const pwr_min_hsec = 500                                     ' 9.600 Watt
const pwr_idle_5min = 3                                     ' 15-19 Minuten = 20-27 Watt
 
Dim Clock_sec As Long , Clock_hsec As Byte                  ' uptime. variablen müssen direkt hintereinanderliegen für 'pwr_isr'
 
Dim Eram_threshold As Eram Word At &H02
Dim Eram_hysteresis As Eram Word At &H04
Dim Eram_debounce As Eram Byte At &H06
' Die silberne Scheibe des Stromzählers erzeugt im Laufe einer Umdrehung deutlich schwankende Werte
' Für Feintuning gibt es den CSV-log der mit Excel als Grafik angezeigt werden kann
'
' Schwellwert (400) Das Analogsignal liegt bei mir zwischen 250-580.
' Hysterese   (125) Muß groß genug sein, um bei langsam drehender Scheibe (Dämmerung) keine falschen Impulse zu erzeugen
' Entprellung   (2) Muß kurz genug sein, um bei schnell drehender Scheibe keine Impulse zu verlieren (roter Strich nur 5-6 Takte lang)
 
' zeitgesteuerter Dämmerungsschalter mit ELV SI320-2
Dim Twl_bgn1 As Eram Byte At &H08                           ' Morgen Begin (in 10min)
Dim Twl_end1 As Eram Byte At &H09                           ' Morgen spätestes Ende (früher wenn Pwr_5mincnt>0)
Dim Twl_bgn2 As Eram Byte At &H0A                           ' Abend frühester Begin (erst wenn Pwr_5mincnt==0 für mindestens twl_min2 Intervalle)
Dim Twl_end2 As Eram Byte At &H0B                           ' Abend Ende
Dim Twl_min2 As Eram Byte At &H0C                           ' Abend
 
' Es werden die Original-Zählerimpulse gespeichert. Die Umrechnung in kWh erfolgt erst für die Anzeige
'  oft geänderte Werte im batteriegepufferten Uhren-Ram:
Const Ds1307_totalcnt_adr = &H08                            ' long: stromzählerstand
Const Ds1307_clock_dst_adr = &H0C                           ' byte: sommerzeit (daylight-saving-time)
'  seltener geänderte Werte im Eeprom:
Const Xrom_5min_adr = &H0000                                ' byte: 3 Monate = 96 Tage*288 = 27 KB
Const Xrom_day_adr = &H8000                                 ' word: 30 Jahre = 30 *12*32*2 = 22.5KB (mit 32bit time()-Funktion geht es eh nur bis 2037)
' Speicherkapazität:                                         Anlage Kai:7.92kWh
'  byte für 5min:     255 Impulse = 3,4kW/5min = 17000 W/min   max:~7000W   -> byte reicht für ~19kWh-Anlage
'  word für tag:    65535 Impulse = 873,8kW/h                  max:~55kWh   -> word reicht für ~125kWh-Anlage
'  long für gesamt:  2^31 Impulse = 28.633.115 kWh                          -> mehr als der Stromzähler
 
 
'-------------------------------------------------------------------------------
' Interrupts
'
'  INT0 - 1Hz - ds1307
'   - clock_sec
'  Timer0 - ca. 100Hz
'   - clock_hsec
'   - Tastenerkennung (_key_debounce)
'   - AD-Wandler starten (adc_hsec_isr)
'  ADCC - AD-Wandler fertig
'   - wenn Schwellwerterkennung ok, dann Impuls erzeugen (pwr_isr)
'  Urxc - Daten an serieller Schnittstelle
'   - das übliche
'
' clock_sec und clock_hsec sind nicht synchron, aber hsec wird eh nur zur Berechnung
' der akt.Leistung benutzt
 
' Nur wenige Dinge (z.B. clock_...) werden direkt in Interrupt-Routinen gesetzt
' Das meiste wird durch ..._next Flags in main ausgeführt
'
' Interruptroutinen sind in Assembler. Wahrscheinlich hätte auch Basic gereicht...
 
 
'-------------------------------------------------------------------------------
' misc
 
 
Incr_long:                                                  ' x,r24
$asm
   ld r24,x
   subi  r24,-1
   st x+,r24
   ld r24,x
   sbci  r24,-1
   st x+,r24
   ld r24,x
   sbci  r24,-1
   st x+,r24
   ld r24,x
   sbci  r24,-1
   st x+,r24
   ret
$end asm
 
'-------------------------------------------------------------------------------
' serial input
'  Befehle in stx/etx um sporadische bits auf der Leitung zu ignorieren.
'  sporadische bits durch Neutrinostrahlung oder doch nur Softwarefehler ?
Dim Serial_lines As Byte
Const Serial_len = 80
Dim Serial_line As String * Serial_len
Dim Serial_chars(serial_len) As Byte At Serial_line Overlay
Dim Serial_pos As Byte
Dim Serial_error As Byte
Dim _serial_char As Byte
Const _serial_char_stx = 2
Const _serial_char_etx = 3
Dim _serial_state As Byte
Const _serial_state_none = 0
Const _serial_state_stx = 1
Const _serial_state_etx = 2
Dim _serial_ccnt As Word
Dim _serial_lcnt As Word
 
Serial_init:
   On Urxc Serial_readchar
   Enable Urxc
   Serial_error = 0
   Return
 
Serial_readchar:
   _serial_char = Udr
   Select Case _serial_state
   Case _serial_state_etx:
      Serial_error = 1
   Case _serial_state_stx:
      If Serial_pos >= Serial_len Then
         Serial_error = 2
      Elseif _serial_char = _serial_char_etx Then
         _serial_state = _serial_state_etx
         If Serial_lines <> 0 Then
            Serial_error = 3
         Else
            Incr Serial_pos
            Serial_chars(serial_pos) = 0
            Incr Serial_lines
            Incr _serial_lcnt
         End If
      Else
         Incr Serial_pos
         Serial_chars(serial_pos) = _serial_char
      End If
   Case _serial_state_none:
      If _serial_char = _serial_char_stx Then
         _serial_state = _serial_state_stx
         Serial_pos = 0
      Else
         nop                                                ' ignore junk
      End If
   End Select
   Return
 
Serial_readline:
   If _serial_state <> _serial_state_etx Then
      Serial_error = 4
   End If
   Serial_pos = 1
   Return
 
Serial_end:
   If _serial_state <> _serial_state_etx Then
      Serial_error = 5
   End If
   Print Chr(_serial_char_stx);
   Return
 
Serial_done:
   If _serial_state <> _serial_state_etx Then
      Serial_error = 6
   End If
   Decr Serial_lines
   If Serial_error <> 0 Then
      Print Chr(_serial_char_stx) ; "serial error " ; Serial_error;
      Serial_error = 0
   End If
   Print Chr(_serial_char_etx);
   _serial_state = _serial_state_none
   Return
 
Serial_next:
   While Serial_chars(serial_pos) >= 33 : Incr Serial_pos : Wend
   While Serial_chars(serial_pos) = 32 : Incr Serial_pos : Wend
   Return
 
 
'-------------------------------------------------------------------------------
' lcd
Dim Lcd_val As Byte
 
const lcd_l = 0
'Const Lcd_g = 0
'Const Lcd_p = 1
 
Lcd_init:
   Set Lcd_light                                            ' aus
   Cls
 
   Deflcdchar lcd_l, 24,8,8,8,8,8,28,32                     ' mehr nach links
'   Deflcdchar Lcd_g , 32 , 32 , 14 , 17 , 17 , 15 , 1 , 14  ' g (sehr viel besser als {223})
'   Deflcdchar Lcd_p , 32 , 32 , 30 , 17 , 17 , 30 , 16 , 16 ' p (nur etwas besser als {240})
   Return
 
Lcd_num03:
   If Lcd_val < 100 Then : Lcd "0" : End If
Lcd_num02:
   If Lcd_val < 10 Then : Lcd "0" : End If
   Lcd Lcd_val
   Return
 
 
'-------------------------------------------------------------------------------
' pwr
Dim Pwr_next As Bit
 
Dim Pwr_totalcnt As Long , Pwr_totalkw As Long , Pwr_totalhw As Byte       ' Gesamtleistung
Dim Pwr_daycnt As Word , Pwr_daykw As Byte , Pwr_dayhw As Byte       ' Tagesleistung
Dim Pwr_5mincnt As Byte
Dim _pwr_act As Long
Dim Pwr_act As Word At _pwr_act Overlay                     ' aktuelle Leistung (W)
Dim Pwr_alert_5min As Byte                                  ' 5min Intervalle _ohne_ impuls
Dim Pwr_alert_hsec As Word                                  ' minimale Zeit zwischen 2 Impulsen
Dim Pwr_month_act As Long
Dim pwr_hsec As Word                                       ' Zeit zwischen 2 Impulsen in 1/100 sec
Dim _pwr_sec1 As Long , _pwr_hsec1 As Byte
Dim _pwr_sec2 As Long , _pwr_hsec2 As Byte
Dim _pwr_l1 As Long , _pwr_l2 As Long
Dim _pwr_b As Byte
 
Dim Pwr_totalcnt_(4) As Byte At Pwr_totalcnt Overlay
 
Pwr_init:
   pwr_hsec = 0
   Pwr_act = 0
   _pwr_sec1 = 0
   Pwr_alert_5min = 1
   Pwr_alert_hsec = 65535
   Return
 
Pwr_alert_reset:
   Pwr_alert_5min = 0
   Pwr_alert_hsec = 65535
   Return
 
Pwr_isr:
$asm
   lds   r24,{pwr_next}
   sbr   r24,2^bit.pwr_next
   sts   {pwr_next},r24
   Loadadr _pwr_sec1 , X
   Loadadr _pwr_sec2 , Y
   Call Pwr_isr2
   'ld r24,y+ : st x+,r24                                 ' pwr_sec1=pwr_sec2
   'ld r24,y+ : st x+,r24
   'ld r24,y+ : st x+,r24
   'ld r24,y+ : st x+,r24
   'ld r24,y+ : st x+,r24                                 ' pwr_hsec1=pwr_hsec2
   Loadadr Clock_sec , Y
Pwr_isr2:
   ld r24,y+
   st x+,r24                                    ' pwr_sec2=clock_sec
   ld r24,y+
   st x+,r24
   ld r24,y+
   st x+,r24
   ld r24,y+
   st x+,r24
   ld r24,y+
   st x+,r24                                    ' pwr_hsec2=clock_hsec
   ret
$end asm
 
Pwr_donext:
   Incr Pwr_totalcnt
   Incr Pwr_daycnt
   Incr Pwr_5mincnt
Pwr_calc:
   _pwr_l1 = Pwr_totalcnt * 10
   _pwr_l1 = _pwr_l1 / Pwr_cnt_kwh
   _pwr_l2 = _pwr_l1 Mod 10                                 ' mit long rechnen, sonst würde abgeschnitten
   _pwr_l1 = _pwr_l1 / 10
   Pwr_totalkw = _pwr_l1
   Pwr_totalhw = _pwr_l2
 
   _pwr_l1 = Pwr_daycnt * 10
   _pwr_l1 = _pwr_l1 / Pwr_cnt_kwh
   _pwr_l2 = _pwr_l1 Mod 10
   _pwr_l1 = _pwr_l1 / 10
   Pwr_daykw = _pwr_l1
   Pwr_dayhw = _pwr_l2
 
   If _pwr_sec1 = 0 Then
      if Pwr_5mincnt = 0 then return                        ' pwr_calc ohne pwr_donext
      pwr_hsec = 65535
   else
      _pwr_l1 = _pwr_sec2 - _pwr_sec1
      if _pwr_l1 >= 655 then                                   ' ~11 Minuten = 73 Watt
         pwr_hsec = 65535
      else
         _pwr_b = _pwr_hsec2 - _pwr_hsec1
         If _pwr_b >= 128 Then                                    ' unterlauf bei unsigned byte
         _pwr_b = _pwr_b + 100
            Decr _pwr_l1
         End If
         _pwr_l1 = _pwr_l1 * 100
         pwr_hsec = _pwr_l1 + _pwr_b
      end if
   end if
   'if pwr_hsec < pwr_min_hsec then return
   If pwr_hsec = 0 Then
      Pwr_act = 65535
   Else
      _pwr_act = Pwr_watt_hsec / pwr_hsec
   End If
   If pwr_hsec < Pwr_alert_hsec Then
      Pwr_alert_hsec = pwr_hsec
   End If
   Return
 
 
pwr_dosec:
   if pwr_hsec = 0 then
      return
   end if
   !CLI
   _pwr_l1 = Clock_sec - _pwr_sec2
   !sei
   if _pwr_l1 >= 3 then
      decr _pwr_l1                                             ' ohne hsec, stattdessen sec abrunden um (etwas) weniger als pwr_hsec zu schätzen
      if _pwr_l1 >= 655 then                                   ' ~11 Minuten = 73 Watt
         _pwr_l1 = 65535
      else
         _pwr_l1 = _pwr_l1 * 100
      end if
      if _pwr_l1 > pwr_hsec then
         pwr_hsec = _pwr_l1
         _pwr_act = Pwr_watt_hsec / pwr_hsec
      end if
   end if
   return
 
Pwr_do5min:
   If Pwr_5mincnt >= 1 Then
      Pwr_alert_5min = 0
   Elseif Pwr_alert_5min < 254 Then
      Incr Pwr_alert_5min
      If Pwr_alert_5min >= pwr_idle_5min Then
         _pwr_sec1 = 0
         pwr_hsec = 0
         Pwr_act = 0
      End If
   End If
   Return
 
 
'-------------------------------------------------------------------------------
' adc
Dim Adc_bit As Bit , Adc_next As Bit
Dim Adc_value As Word , Adc_threshold_up As Word , Adc_threshold_dn As Word
Dim Adc_debounce As Byte , Adc_cnt As Byte
Dim _adc_hsec As Byte                                       ' minitimer für 100Hz-key -> 20Hz ADC
 
 
Adc_init:
   Config Adc = Single , Prescaler = Auto , Reference = Avcc
   On Adcc Adc_ready_isr , Nosave
   Enable Adcc
   Adc_threshold_up = Eram_threshold + Eram_hysteresis
   Adc_threshold_dn = Eram_threshold - Eram_hysteresis
   Adc_debounce = Eram_debounce
   If Adc_debounce = 0 Then : Adc_debounce = 1 : End If
   Reset Cny70_pwr                                          ' licht an
   Start Adc
   Waitms 10
   Adc_value = Getadc(0)                                    ' set channel 0
   Adc_cnt = Adc_debounce
   If Adc_value >= Adc_threshold_up Then
      Adc_bit = 1
      Set Cny70_led
   End If
   Return
 
Adc_hsec_isr:                                               ' r16-19 verfügbar
$asm
' Bis 5 zählen um 100 Hz auf 20 Hz reduzieren
' Zum Stromsparen wird CNY70-Led erst ein Takt vor AD-Wandlung angeschaltet.
' Ein Anschalten unmittelbar vor der AD-Wandlung führt zu unbrauchbaren Analog-Werten.
   lds   r16,{_adc_hsec}
   inc   r16
   cpi   r16,4                                              ' ~20 Hz
   brlo  adc_hsec_isr3
   breq  adc_hsec_isr2
      lds r17,adcsr                                         ' 4 - adc sarten
      ori r17,2^6                                           ' wie Set Adcsr.6 nur mit r17 statt r24
      sts adcsr,r17
      clr   r16
   rjmp  adc_hsec_isr3
$end asm
Adc_hsec_isr2:
   Reset Cny70_pwr                                       ' 3 - licht an   (sbi portx,y)
Adc_hsec_isr3:
   !sts   {_adc_hsec},r16                                    ' 0-2 - nix
   Return
 
Adc_ready_isr:
$asm
   push  r16
   in    r16,sreg
   push  r16
   push  r17
   push  r18
   push  r19
   push  r24
   push  r25
   push  r26                                                ' x
   push  r27
   push  r28                                                ' y
   push  r29
   'in    r24,{adc_pwroff}
   'sbrs  r24,bit.adc_pwroff
   Set Cny70_pwr                                            ' licht aus
   lds   r24,{adc_next}                                     ' höchstwahrscheinlich ist {adc_bit}={adc_next}, aber ...
   sbr   r24,2^bit.adc_next
   sts   {adc_next},r24
   lds   r24,{adc_bit}
   bst   r24,bit.adc_bit                                    ' ins T-bit
   lds   r25,{adc_cnt}
   Loadadr Adc_value , X
   in    r16,adcl
   st    x+,r16
   in    r17,adch
   st    x+,r17
 
   ld    r18,x+
   ld    r19,x+
   cp    r16,r18
   cpc   r17,r19
   brlo  adc_isr2                                           ' if Adc_value > Adc_threshold_up
   brts  adc_isr2                                           ' and adc_bit=0
      sbr   r24,2^bit.adc_bit
      sts   {adc_bit},r24
      clr   r25
      Set Cny70_led                                         ' sbi portx,y
      rjmp adc_isr3
Adc_isr2:
   ld    r18,x+
   ld    r19,x+
   cp    r16,r18
   cpc   r17,r19
   brsh  adc_isr3                                           ' If Adc_value < Adc_threshold_dn
   brtc  adc_isr3                                           ' And Adc_bit = 1
      cbr   r24,2^bit.adc_bit
      sts   {adc_bit},r24
      clr   r25
      Reset Cny70_led
Adc_isr3:
   lds   r24,{adc_debounce}
   cp    r25,r24
   brge  adc_isr4
      inc   r25
      sts   {adc_cnt},r25
      cp    r25,r24
      brne  adc_isr4
         lds   r24,{adc_bit}
         bst   r24,bit.adc_bit                              ' ins T-bit
         brtc  adc_isr4
            ' save all bits before pwr_isr, because pwr_next is in same byte and overwritten
            CALL Pwr_isr                                   ' r16,x,y
Adc_isr4:
   pop   r29
   pop   r28
   pop   r27
   pop   r26
   pop   r25
   pop   r24
   pop   r19
   pop   r18
   pop   r17
   pop   r16
   Out Sreg , r16
   pop   r16
$end asm
   Return
 
'-------------------------------------------------------------------------------
' clock
Dim Clock_nexthsec As Byte                                  ' von key interrupt gesetzt
Dim Clock_nextsec As Bit                                    ' von ds1307 interrupt gesetzt
Dim Clock_next5min As Bit
Dim Clock_nexthour As Bit                                   ' ...
Dim Clock_nextday As Bit
 
Dim Clock_weekday As Byte
Dim Clock_dst As Byte
 
Dim _clock_b As Byte
 
Clock_weekday_str:
Data "" , "Mo" , "Di" , "Mi" , "Do" , "Fr" , "Sa" , "So"
 
Clock_init:
   Config Clock = User                                      ' this will dim the bytes automatic
   Config Date = Dmy , Separator = .
   Config Int0 = Falling
   On Int0 Clock_isr Nosave
   Enable Int0
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte 7
   I2cwbyte &B0001_0000                                     ' Sekundentakt an SQW pin
   I2cstop
   Gosub Clock_read_datetime
   Return
 
Clock_isr:
$asm
   push  r24
   in    r24,sreg                                           ' ori setzt flags
   push  r24
   push  r26                                                ' x
   push  r27
   lds   r24,{Clock_nextsec}
   ori   r24,2^bit.Clock_nextsec                            'Set Clock_nextsec
   sts   {Clock_nextsec},r24
   Loadadr Clock_sec , X
   Call Incr_long                                          ' r24,x
   clr   r24
   sts   {clock_hsec},r24
   pop   r27
   pop   r26
   pop   r24
   Out Sreg , R24
   pop   r24
$end asm
   Return
 
Clock_dosec:
   Incr _sec
   If _sec >= 60 Then
      _sec = 0
      Incr _min
      _clock_b = _min Mod 5
      If _clock_b = 0 Then
         Set Clock_next5min
      End If
      If _min >= 60 Then
         _min = 0
         Incr _hour
         Set Clock_nexthour
         If _hour >= 24 Then
            _hour = 0
            Set Clock_nextday
         End If
      End If
   End If
   Return
 
Clock_dohour:
   If _hour = 2 And Clock_weekday = 7 And _day > 24 Then    ' sommerzeit
      If Clock_dst = 0 And _month = 3 Then Gosub Clock_toggle_dst
      If Clock_dst <> 0 And _month = 10 Then Gosub Clock_toggle_dst
   End If
   Return
 
Clock_doday:
   _clock_b = _day
   ' die avr soft clock (_sec,_min,_hour) kann etwas schneller oder langsamer als der DS1307 laufen,
   ' bzw. wird in der Sekundenmitte initialisiert
   Gosub Clock_read_datetime
   ' zu schnell: clock wird von 00:00:00 auf 23:59:59 zurückgesetzt. clock_nextday wird in 1 sek. nochmal gesetzt
   ' zu langsam: clock wird von 00:00:00 auf 00:00:01 vorgesetzt. clock_nextday bleibt
   If _clock_b = _day Then
      Reset Clock_nextday
      Reset Clock_next5min
   End If
   Return
 
Clock_read_datetime:
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte 0
   I2cstart
   I2cwbyte Ds1307r
   I2crbyte _sec , Ack : : _sec = Makedec(_sec)
   I2crbyte _min , Ack   : _min = Makedec(_min)
   I2crbyte _hour , Ack : _hour = Makedec(_hour)
   I2crbyte Clock_weekday , Ack
   I2crbyte _day , Ack : : _day = Makedec(_day)
   I2crbyte _month , Ack : _month = Makedec(_month)
   I2crbyte _year , Nack : _year = Makedec(_year)
   I2cstop
   '
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte Ds1307_clock_dst_adr
   I2cstart
   I2cwbyte Ds1307r
   I2crbyte Clock_dst , Nack
   I2cstop
   Return
 
Getdatetime:                                                ' called by ...=$date,$time
   Return                                                   ' _sec,... are already set
 
Setdate:                                                    ' called by $date=...
   Clock_weekday = Dayofweek()
   Incr Clock_weekday
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte 3
   I2cwbyte Clock_weekday
   _clock_b = Makebcd(_day) : I2cwbyte _clock_b
   _clock_b = Makebcd(_month) : I2cwbyte _clock_b
   _clock_b = Makebcd(_year) : I2cwbyte _clock_b
   I2cstop
   Return
 
Settime:                                                    ' called by$time=...
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte 0
   _clock_b = Makebcd(_sec) : I2cwbyte _clock_b
   _clock_b = Makebcd(_min) : I2cwbyte _clock_b
   _clock_b = Makebcd(_hour) : I2cwbyte _clock_b
   I2cstop
   Return
 
Clock_toggle_dst:
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte 2
   I2cstart
   I2cwbyte Ds1307r
   I2crbyte _clock_b , Nack
   If Clock_dst = 0 Then
      Clock_dst = 1
      Incr _clock_b
      Incr _hour
   Else
      Clock_dst = 0
      Decr _clock_b
      Decr _hour
   End If
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte 2
   I2cwbyte _clock_b
   I2cstop
   '
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte Ds1307_clock_dst_adr
   I2cwbyte Clock_dst
   I2cstop
   Return
 
Clock_read_totalcnt:
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte Ds1307_totalcnt_adr
   I2cstart
   I2cwbyte Ds1307r
   I2crbyte Pwr_totalcnt_(1) , Ack
   I2crbyte Pwr_totalcnt_(2) , Ack
   I2crbyte Pwr_totalcnt_(3) , Ack
   I2crbyte Pwr_totalcnt_(4) , Nack
   I2cstop
   Return
 
Clock_write_totalcnt:
   I2cstart
   I2cwbyte Ds1307w
   I2cwbyte Ds1307_totalcnt_adr
   I2cwbyte Pwr_totalcnt_(1)
   I2cwbyte Pwr_totalcnt_(2)
   I2cwbyte Pwr_totalcnt_(3)
   I2cwbyte Pwr_totalcnt_(4)
   I2cstop
   Return
 
 
'-------------------------------------------------------------------------------
' keytimer
 
'Zuordnung der Tasten zu den Pins - diese müssen alle am selben Port hängen!
'Btn1 Alias Pind.3
'Btn2 Alias Pind.4
Key_port Alias Pind
Const Key_1 = 2 ^ 3
Const Key_2 = 2 ^ 4
 
Const Key_mask = Key_1 + Key_2                              'Maske zum Filtern der Eingänge
Const Key_highactive = Key_2                                'Maske zum Filtern der high-aktiven Eingänge
Const Key_repeatable = Key_1 + Key_2                        'Maske zum Filtern der Autorepeat Eingänge
 
Dim Key_press As Byte                                       'Gedrückte Tasten
'Dim Key_repeat As Byte                                      'Repeatende Tasten
 
Dim _key_state As Byte                                      '0/1 invertierter Status der Tasten (1=gedrückt)
Dim _key_rep As Byte
Dim _key_ct0 As Byte , _key_ct1 As Byte                     '2 Bit Zähler für Entprellung
Const _key_mask_compl = &HFF - Key_mask                     'Pinb_mask compliment
Const _key_repeat_start = 127                               'Anzahl-1 der Timer-ISR bis Autorepeat beginnt (ca. 500-1000ms)
Const _key_repeat_next = 15                                 'Anzahl-1 der Timer-ISR für Autorepeat Wiederholrate (ca. 125ms)
Const _key_timer0_prescale = 1024
Const _key_timer0_counter = 116                             ' 12000000 / 1024 / 117 = ~100Hz = 10ms
 
Key_init:
'   Ddrd = Ddrd And _key_mask_compl                          'DDRB: 0=INPUT 1=OUTPUT
'   Portd = Portd Or Key_mask                                '1=activate internal pull-up resistors for inputs
   Config Timer0 = Timer , Prescale = _key_timer0_prescale
   Ocr0a = _key_timer0_counter
   Set Tccr0a.wgm01                                         ' Clear Timer on Compare (CTC) Mode
   On Oc0a _timer0_isr , Nosave
   Enable Oc0a
   'debounce initial values
   _key_ct0 = 255                                           'Programmstart bei gedrückten Tasten abfangen
   _key_ct1 = 255
   Return
 
_timer0_isr:
$asm
   push  r16
   in    r16,sreg
   push  r16                                                'save R16 and SREG in stack
   push  r17                                                'now save all used registers
   push  r18
   PUSH  r19
   Call _key_debounce
 
   lds   r16,{Clock_nexthsec}
   inc   r16
   sts   {Clock_nexthsec},r16
   lds   r16,{clock_hsec}
   inc   r16
   sts   {clock_hsec},r16
   Call   adc_hsec_isr
 
   POP   r19                                                'restore registers
   pop   r18
   pop   r17
   pop   r16                                                'get content of SREG
   out  sreg,r16                                           'restore sreg
   pop   r16
$end Asm
   Return                                                   'and exit isr with RETI
 
'---------------------------------------------------------------
'Subroutine: _key_debounce
'            gleichzeitige Erkennnung von max. 8 gedrückten Tasten mit Entprellung und Autorepeat
'            jede Taste wird für einen Statuswechsel 3x abgetastet
'verwendete Register:  R16, R17, R18, R19
'Variablen:  Key_state    Status der Tasten 0/1
'            Key_rep      Wiederholungszähler für Autorepeat
'            Key_ct0 / Key_ct1  2-Bit-Zähler für Entprellung
'Result:     Key_press:   Bit des Pins wechselt zu 1 bei Erkennung einer gedrückten Taste
'                         Status von Key_press in Main nach Auslesen zurücksetzen!
'Thanks to Peter Dannegger
'---------------------------------------------------------------
_key_debounce:                                              'ca. 108 Byte
$asm
   ldi r17, key_highactive
   in  R18, key_port
   com R18                                                  'pin low is active
   Eor R18 , r17
   ANDI R18, key_mask                                       'filter pins with Pinb_mask
   LDS R19, {_Key_state}
   eor R18, R19                                             'detect level change at pin input
 
   LDS R16, {_Key_ct0}                                      'the 8 channels 2-Bit-Counter
   LDS R17, {_Key_ct1}
   and R16, R18                                             'reset the 2-bit-counter in R17:R16
   and R17, R18
   com R16                                                  'decrement R17:R16
   eor R17, R16
   STS {_Key_ct0} , R16                                     'save counter
   STS {_Key_ct1} , R17
 
   and R18, R16                                             'IF counter = &B11 set_digit input debounced
   and R18, R17
   eor R19, R18                                             '0<->1 toggle  state
   STS {_Key_state} , R19
 
   LDS R16, {key_press}
   and R18, R19
   or R16, R18                                              '0->1 key press detected
 
   LDS R17, {_Key_rep}
   andi r19, key_repeatable
   tst R19                                                  'Key_state: irgendeine Taste gedrückt?
   breq _Key_isr_rep
   dec R17
   brpl _Key_isr_finish                                     'IF Key_rep<0 set_digit Wartezeit abgelaufen
   mov R16, R19                                             'autorepeat key_press = key_state
   ldi R17, _key_repeat_next                                'set autorepeat repeat timer
   rjmp _Key_isr_finish
 
_key_isr_rep:
   ldi R17, _key_repeat_start                               'reset autorepeat start timer
 
_key_isr_finish:
   STS {_Key_rep} , R17                                     'save the autorepeat timer
'   STS {Key_repeat} , R18                                  'save the autorepeat key
   STS {key_press} , R16                                    'save debounced key
$end Asm
   Return
 
 
'-------------------------------------------------------------------------------
' externes eeprom
 
Dim Xrom_day As Byte
Dim Xrom_month As Byte
Dim Xrom_year As Byte
Dim Xrom_hour As Byte
Dim Xrom_min As Byte
 
Dim Xrom_monthcnt As Long
Dim Xrom_daycnt As Word
Dim Xrom_5mincnt As Byte
Dim _xrom_bytes(288) As Byte
Dim _xrom_bytes_2(144) As Byte At _xrom_bytes(145) Overlay
Dim _xrom_words(144) As Word At _xrom_bytes Overlay
Dim Xrom_5mincnts(288) As Byte At _xrom_bytes Overlay
Dim Xrom_daycnts(32) As Word At _xrom_bytes Overlay
 
Dim Xrom_dayvalid As Bit
Dim Xrom_5minvalid As Bit
Dim Xrom_monthdays As Byte
 
Dim _xrom_adr As Word
Dim _xrom_adr_(2) As Byte At _xrom_adr Overlay
Dim _xrom_daycnt_(2) As Byte At Xrom_daycnt Overlay
Dim _xrom_tmp As Byte
 
 
_xrom_calc_5min:
   Reset Xrom_5minvalid
   If Xrom_year > _year Then Return
   _xrom_tmp = _year - 1
   If Xrom_year < _xrom_tmp Then Return
   If Xrom_day < 1 Then Return
   If Xrom_day >= 32 Then Return
   _xrom_tmp = Xrom_month - _month
   If Xrom_year = _year Then                                ' diese Jahr
      _xrom_tmp = _xrom_tmp + 3
   Else                                                     ' letztes Jahr
      _xrom_tmp = _xrom_tmp - 9
   End If
   If _xrom_tmp >= 4 Then Return                            ' > 3 und <0
   If _xrom_tmp = 3 And Xrom_day > _day Then Return
   '  _Xrom_tmp in (2,1): pass
   If _xrom_tmp = 0 And Xrom_day <= _day Then Return
   Set Xrom_5minvalid
 
   _xrom_adr = Xrom_month Mod 3
   _xrom_adr = _xrom_adr * 32
   _xrom_adr = _xrom_adr + Xrom_day
   _xrom_adr = _xrom_adr - 1
   _xrom_adr = _xrom_adr * 24
   _xrom_adr = _xrom_adr + Xrom_hour
   _xrom_adr = _xrom_adr * 12
   _xrom_tmp = Xrom_min / 5
   _xrom_adr = _xrom_adr + _xrom_tmp
   _xrom_adr = _xrom_adr + Xrom_5min_adr
   Return
 
_xrom_calc_day:
   Reset Xrom_dayvalid
   If Xrom_year < 9 Then Return
   If Xrom_year >= 40 Then Return
   If Xrom_month < 1 Then Return
   If Xrom_month >= 13 Then Return
   If Xrom_day < 1 Then Return
   If Xrom_day >= 32 Then Return
   Set Xrom_dayvalid
   _xrom_adr = Xrom_year - 9
   _xrom_adr = _xrom_adr * 12
   _xrom_adr = _xrom_adr + Xrom_month
   _xrom_adr = _xrom_adr - 1
   _xrom_adr = _xrom_adr * 32
   _xrom_adr = _xrom_adr + Xrom_day
   _xrom_adr = _xrom_adr - 1
   _xrom_adr = _xrom_adr * 2
   _xrom_adr = _xrom_adr + Xrom_day_adr
   Return
 
_xrom_calc_monthdays:
   Select Case Xrom_month
   Case 2 : _xrom_tmp = Xrom_year Mod 4
            If _xrom_tmp = 0 _
            Then Xrom_monthdays = 29 _
            Else Xrom_monthdays = 28
   Case 4 : Xrom_monthdays = 30
   Case 6 : Xrom_monthdays = 30
   Case 9 : Xrom_monthdays = 30
   Case 11 : Xrom_monthdays = 30
   Case Else : Xrom_monthdays = 31
   End Select
   Return
 
Xrom_now:
   Xrom_year = _year
   Xrom_month = _month
   Xrom_day = _day
   Xrom_hour = _hour
   Xrom_min = _min
   Return
 
Xrom_i2c_header:
   I2cstart
   I2cwbyte Eepromw
   If Err = 1 Then                                          ' acknowledge polling
      I2cstop
      Goto Xrom_i2c_header
   End If
   I2cwbyte _xrom_adr_(2)
   I2cwbyte _xrom_adr_(1)
   Return
 
 
Xrom_read_5min:
   Gosub _xrom_calc_5min
#if Xromdbg
   Print "rm" ;
#endif
   If Xrom_5minvalid = 0 Then Return
   Gosub Xrom_i2c_header
   I2cstart
   I2cwbyte Eepromr
   I2crbyte Xrom_5mincnt , Nack
   I2cstop
#if Xromdbg
   Print _xrom_adr ; " " ; Xrom_5mincnt
#endif
   Return
 
Xrom_write_5min:
   Gosub _xrom_calc_5min
#if Xromdbg
   Print "wm" ;
#endif
   If Xrom_5minvalid = 0 Then Return
#if Xromdbg
   Print " " ; _xrom_adr ; " " ; Xrom_5mincnt
#endif
   Gosub Xrom_i2c_header
   I2cwbyte Xrom_5mincnt
   I2cstop
   Return
 
Xrom_read_day:
   Gosub _xrom_calc_day
#if Xromdbg
   Print "rd";
#endif
   If Xrom_dayvalid = 0 Then Return
   Gosub Xrom_i2c_header
   I2cstart
   I2cwbyte Eepromr
   I2crbyte _xrom_daycnt_(1) , Ack
   I2crbyte _xrom_daycnt_(2) , Nack
   I2cstop
#if Xromdbg
   Print " " ; _xrom_adr ; " " ; Xrom_daycnt;
#endif
   Xrom_hour = 0
   Xrom_min = 0
   Gosub _xrom_calc_5min
   If Xrom_5minvalid = 0 Then Return
   Gosub Xrom_i2c_header
   I2cstart
   I2cwbyte Eepromr
   For _xrom_tmp = 1 To 144
      I2crbyte _xrom_bytes(_xrom_tmp) , Ack
   Next
   I2crbyte _xrom_tmp , Nack
   I2cstop
   _xrom_adr = _xrom_adr + 144
   Gosub Xrom_i2c_header
   I2cstart
   I2cwbyte Eepromr
   For _xrom_tmp = 1 To 144
      I2crbyte _xrom_bytes_2(_xrom_tmp) , Ack
   Next
   I2crbyte _xrom_tmp , Nack
   I2cstop
#if Xromdbg
   Print " " ; _xrom_adr ; " ..."
#endif
   Return
 
Xrom_clear_day:
   Xrom_hour = 0
   Xrom_min = 0
#if Xromdbg
   Print "cd";
#endif
   Gosub _xrom_calc_5min
   If Xrom_dayvalid = 0 Then Return
   For _xrom_daycnt_(1) = 1 To 9                            ' 9*32 vermeidet Schreiben über Page-Grenzen
#if Xromdbg
      Print " " ; _xrom_adr;
#endif
Xrom_clear_day_retry:
      Gosub Xrom_i2c_header
      For _xrom_tmp = 1 To 32
         I2cwbyte 0
      Next
      I2cstop
      _xrom_adr = _xrom_adr + 32
   Next
   Xrom_daycnt = 0
#if Xromdbg
   Print
#endif
   ' fallthru
 
Xrom_write_day:
   Gosub _xrom_calc_day
#if Xromdbg
   Print "wd" ;
#endif
   If Xrom_dayvalid = 0 Then Return
#if Xromdbg
   Print " " ; _xrom_adr ; " " ; Xrom_daycnt
#endif
   Gosub Xrom_i2c_header
   I2cwbyte _xrom_daycnt_(1)
   I2cwbyte _xrom_daycnt_(2)
   I2cstop
   Return
 
 
Xrom_read_month:
   Xrom_day = 1
   Gosub _xrom_calc_day
   Gosub _xrom_calc_monthdays
   If Xrom_dayvalid = 0 Then Return
   Gosub Xrom_i2c_header
   I2cstart
   I2cwbyte Eepromr
   For _xrom_tmp = 1 To 64
      I2crbyte _xrom_bytes(_xrom_tmp) , Ack
   Next
   I2crbyte _xrom_tmp , Nack
   I2cstop
   Return
 
 
Xrom_read_monthcnt:
   Gosub Xrom_read_month
   Xrom_monthcnt = 0
   If Xrom_dayvalid = 0 Then Return
   For _xrom_tmp = 1 To Xrom_monthdays
      Xrom_monthcnt = Xrom_monthcnt + Xrom_daycnts(_xrom_tmp)
   Next
   Return
 
'-------------------------------------------------------------------------------
' dämmeruns+zeitschalter
Dim _twl_time As Byte , _twl_cnt2 As Byte , _twl_i As Byte
 
Twl_init:
   _twl_cnt2 = 0
   Reset Twl_out
   Return
 
Twl_do5min:
   _twl_time = _hour * 10
   _twl_i = _min / 10
   _twl_time = _twl_time + _twl_i
   If _twl_time >= Twl_end2 Then
      Reset Twl_out
   Elseif _twl_time >= Twl_bgn2 Then
      If Pwr_5mincnt = 0 Then Incr _twl_cnt2 Else _twl_cnt2 = 0
      If _twl_cnt2 >= Twl_min2 Then Set Twl_out
   Elseif _twl_time >= Twl_end1 Then
      _twl_cnt2 = 0
      Reset Twl_out
   Elseif _twl_time > Twl_bgn1 Then
      If Pwr_5mincnt >= 1 Then Reset Twl_out
   Elseif _twl_time = Twl_bgn1 Then
      If Pwr_5mincnt = 0 Then Set Twl_out
   End If
Return
 
 
'-------------------------------------------------------------------------------
' main
 
Dim I As Byte , J As Byte
Dim W As Word , V As Word , U As Word
Dim W_(2) As Byte At W Overlay
Dim L As Long , L2 As Long
Dim B As Byte
 
Dim Light_cnt As Byte
Const Light_len = 30                                        ' backlight duration
 
Dim Csv_count As Long
 
Dim Lcd_next As Bit
Dim Lcd_mode As Byte
Const Lcd_modes = 3
Dim Lcd_buf As String * 10
Dim Lcd_chars(10) As Byte At Lcd_buf Overlay
Dim Lcd_bit As Bit , Pwr_bit As Bit                         ' delayed copy of adc_bit
 
Main:
   Gosub Pwr_init
   Gosub Adc_init
   Gosub Clock_init
   Gosub Lcd_init
   Gosub Key_init
   Gosub Serial_init
   Gosub Twl_init
 
   Gosub Xrom_now
   Gosub Xrom_read_5min
   Pwr_5mincnt = Xrom_5mincnt
   Gosub Xrom_read_day
   Pwr_daycnt = Xrom_daycnt
   Gosub Clock_read_totalcnt
   Gosub Pwr_calc
 
   Config Watchdog = 2048
   Start Watchdog
   Enable Interrupts
   Light_cnt = Light_len
   Reset Lcd_light
   Do
      'Idle                                                  ' nicht benutzen! wuerde adc starten
      Reset Watchdog
      ' schnelle flags müssen atomar gelesen+zurückgeset werden
      ' sonst wird weiter unten im handler ein flag zurückgesetzt, was oben evtl. noch nicht behandelt wurde
 
      If Adc_bit = 1 Then Lcd_bit = 1
      If Pwr_next = 1 Then
         Pwr_next = 0
         Toggle Pwr_bit
         Gosub Pwr_donext
      End If
 
      If Clock_nextsec = 1 Then
         Toggle Led1
 
         Clock_nextsec = 0
         Gosub Xrom_now                                     ' alte zeit merken, da ...
         Gosub Clock_dosec                                  ' ... dies Clock_next5min setzt
         gosub pwr_dosec
         Set Lcd_next
         If Light_cnt >= 1 Then
            Decr Light_cnt
            If Light_cnt = 0 Then
               Set Lcd_light
               'Lcd_mode = 0
            End If
         End If
      End If
 
      If Clock_nextday = 1 Then
         Gosub Clock_doday                                  ' löscht evtl. clock_nextday+clock_next5min
      End If
 
      If Clock_next5min = 1 Then
         Clock_next5min = 0
         Gosub Pwr_do5min
         Gosub Twl_do5min
         If Pwr_5mincnt >= 1 Then
            Xrom_daycnt = Pwr_daycnt
            Xrom_5mincnt = Pwr_5mincnt
            Pwr_5mincnt = 0
            Gosub Clock_write_totalcnt
            Gosub Xrom_write_5min
            Gosub Xrom_write_day
         End If
      End If
 
      If Clock_nextday = 1 Then
         Clock_nextday = 0
         Pwr_daycnt = 0
         Gosub Pwr_calc
         Gosub Xrom_now                                     ' new day
         Gosub Xrom_clear_day
      End If
      If Clock_nexthour = 1 Then
         Clock_nexthour = 0
         Gosub Clock_dohour                                 ' automatische sommerzeit-umstellung
      End If
 
      If Key_press = Key_1 Then
         Incr Lcd_mode
         If Lcd_mode >= Lcd_modes Then Lcd_mode = 0
         Light_cnt = Light_len
         Reset Lcd_light
      End If
      If Key_press = Key_2 Then
         Light_cnt = Light_len
         Reset Lcd_light
      End If
      Key_press = 0
 
      If Serial_lines >= 1 Then
         Gosub Serial_readline
         Gosub Doserial
      End If
 
      If Adc_next = 1 Then
         Adc_next = 0
         If Csv_count <> 0 Then
            L = Clock_sec
            I = Clock_hsec
            If I > 99 Then I = 99                           ' don't confuse excel with xxx.100
            Print Chr(_serial_char_stx) ; L ; ".";
            If I < 10 Then Print "0";
            Print I ; ";" ; Adc_value ; ";" ; Adc_bit ; ";" ; Pwr_bit ; Chr(_serial_char_etx);
            Decr Csv_count
            If Csv_count = 0 Then
               Print Chr(_serial_char_stx) ; ";;;;ende" ; Chr(_serial_char_etx);
               Print Chr(_serial_char_stx) ; Chr(_serial_char_etx);
            End If
         End If
      End If
 
      ' das langsamste zuletzt
      If Lcd_next = 1 Then
         Lcd_next = 0
         Locate 1 , 1
         Select Case Lcd_mode
         Case 1:                                            ' debug menu 1
            Lcd Date$ ; " ad=" ; Adc_value ; "    "
            Locate 2 , 1
            Lcd Time$ ; " ct=" ; Pwr_daycnt ; "    "
         Case 2:                                            ' debug menu 2
            Do
               L = Clock_sec
               L2 = Clock_sec
            Loop Until L = L2
            Cls
            Locate 1 , 1
            Lcd "e" ; Serial_error ; " " ;
            Lcd Hex(serial_chars(1))
            Lcd Hex(serial_chars(2))
            Lcd Hex(serial_chars(3))
            Lcd Hex(serial_chars(4))
            Lcd Hex(serial_chars(5))
            Lcd Hex(serial_chars(6))
            Lcd Hex(serial_chars(7))
            Locate 2 , 1
            Lcd "c" ; _serial_ccnt ; " l" ; _serial_lcnt ; " s" ; _serial_state ; " p" ; Serial_pos ; " "
         Case Else                                          ' normalanzeige
            B = _sec Mod 4
            If B >= 2 Then
               Lcd_buf = Str(pwr_totalkw)
               Lcd "Tota" ; chr(lcd_l); Format(lcd_buf , "     0") ; "." ; Pwr_totalhw ; "kWh"
               Locate 2 , 1
               Lcd_buf = Date$
               Lcd Lcd_buf ; "  "
               Lcd_buf = Time$
               Lcd_chars(6) = 0
               Lcd Lcd_buf ; " "
            Else
               Lcd_buf = Str(pwr_daykw)
               Lcd "Heute" ; Format(lcd_buf , "     0") ; "." ; Pwr_dayhw ; "kWh"
               Locate 2 , 1
               Lcd_buf = Str(pwr_act)
               Lcd "Aktuel" ; chr(lcd_l); Format(lcd_buf , "      0") ; "W"
               If Lcd_bit = 1 Then
                  Lcd "*"                                   ' mindestens 1 sec anzeigen, auch wenn kuerzer
                  Lcd_bit = 0
               Else
                  Lcd " "
               End If
            End If
         End Select
      End If
   Loop
 
 
Doserial:
   Gosub Serial_next
   Select Case Serial_chars(1)
   Case "v":                                                ' version
      Gosub Serial_end
      Print Cvs_id;
   Case "s":                                                ' status
      Gosub Serial_end
      Do
         L = Clock_sec
         L2 = Clock_sec
      Loop Until L = L2                                     ' lock free uptime
      Print Date$ ; " " ; Time$ ; " " ; Clock_dst ; " " ; L ; " ";
      Print Pwr_totalcnt ; " " ; Pwr_daycnt ; " " ; Pwr_act ; " " ; pwr_hsec ; " ";
      Print Pwr_alert_hsec ; " " ; Pwr_alert_5min;
   Case "S":                                                ' status löschen
      Gosub Serial_end
      Gosub Pwr_alert_reset
   Case "t":                                                ' zeit
      Gosub Serial_end
      Print Time$ ;
      If Clock_dst = 1 Then Print " (Sommerzeit)" ;
   Case "u":                                                ' datum
      Gosub Serial_end
      Print Date$ ; " " ; Clock_weekday ; " (" ; Lookupstr(clock_weekday , Clock_weekday_str) ; ")" ;
   Case "T":                                                ' zeit setzen
      Time$ = Mid(serial_line , Serial_pos)
      Gosub Serial_end
   Case "U":                                                ' datum setzen
      Date$ = Mid(serial_line , Serial_pos , 8)
      Gosub Serial_end
   Case "Y":                                                ' manuelle sommerzeit-umschaltung. sollte nicht nötig sein, da automatisch in 'Clock_dohour'
      Gosub Serial_end
      Gosub Clock_toggle_dst
   Case "h":                                                ' digitalisierungs-schwellwerte lesen
      Gosub Serial_end
      W = Eram_threshold
      V = Eram_hysteresis
      I = Eram_debounce
      Print W ; " " ; V ; " " ; I ;
   Case "H":                                                ' digitalisierungs-schwellwerte setzen
      W = Val(serial_chars(serial_pos))
      Gosub Serial_next
      V = Val(serial_chars(serial_pos))
      Gosub Serial_next
      I = Val(serial_chars(serial_pos))
      Gosub Serial_end
      Eram_threshold = W
      Eram_hysteresis = V
      Eram_debounce = I
      Adc_threshold_up = W + V
      Adc_threshold_dn = W - V
      Adc_debounce = I
 
   Case "d":                                                ' tag: 5-minutenwerte lesen
      Xrom_year = Val(serial_chars(serial_pos))
      Gosub Serial_next
      Xrom_month = Val(serial_chars(serial_pos))
      Gosub Serial_next
      Xrom_day = Val(serial_chars(serial_pos))
      Gosub Serial_end
      If Xrom_year = 0 Then
         Xrom_year = _year
         Xrom_month = _month
         Xrom_day = _day
      End If
      Gosub Xrom_read_day
      If Xrom_dayvalid = 0 Then Goto Baddaytime
      Print Xrom_daycnt;
      If Xrom_5minvalid = 1 Then
         For W = 1 To 288
            Print " " ; Xrom_5mincnts(w) ;
         Next
      End If
   Case "D":                                                ' tag: tageswert (und gesamtwert) setzen
      Xrom_year = Val(serial_chars(serial_pos))
      Gosub Serial_next
      Xrom_month = Val(serial_chars(serial_pos))
      Gosub Serial_next
      Xrom_day = Val(serial_chars(serial_pos))
      Gosub Serial_next
      W = Val(serial_chars(serial_pos))
      Gosub Serial_end
      Gosub _xrom_calc_day
      If Xrom_dayvalid = 0 Then Goto Baddaytime
 
      If Xrom_year = _year And Xrom_month = _month And Xrom_day = _day Then
         V = Pwr_daycnt
         Pwr_daycnt = W
      Else
         Gosub Xrom_read_day
         V = Xrom_daycnt
      End If
      Pwr_totalcnt = Pwr_totalcnt - V
      Pwr_totalcnt = Pwr_totalcnt + W
      Gosub Clock_write_totalcnt
      Xrom_daycnt = W
      Gosub Xrom_write_day
      Gosub Pwr_calc
   Case "m":                                                ' monat: tageswerte lesen
      Xrom_year = Val(serial_chars(serial_pos))
      Gosub Serial_next
      Xrom_month = Val(serial_chars(serial_pos))
      Gosub Serial_end
      If Xrom_year = 0 Then
         Xrom_year = _year
         Xrom_month = _month
      End If
      Gosub Xrom_read_month
      If Xrom_dayvalid = 0 Then Goto Baddaytime
      Print "-";
      For I = 1 To Xrom_monthdays
         Print " " ; Xrom_daycnts(i) ;
      Next
'(
   Case "x":                                                ' read xrom
      W = Val(serial_chars(serial_pos))
      Gosub Serial_next
      V = Val(serial_chars(serial_pos))
      Gosub Serial_end
Case_x_retry:
      I2cstart
      I2cwbyte Eepromw
      If Err = 1 Then
         I2cstop
         Goto Case_x_retry
      End If
      K = High(w) : I2cwbyte K
      K = Low(w) : I2cwbyte K
      I2cstart
      I2cwbyte Eepromr
      While V >= 1
         Decr V
         I2crbyte I , Ack
         Print I ; ";";
      Wend
      I2crbyte I , Nack
      I2cstop
   Case "X":                                                ' write xrom
      W = Val(serial_chars(serial_pos))
      Gosub Serial_next
      V = Val(serial_chars(serial_pos))
      Gosub Serial_next
      I = Val(serial_chars(serial_pos))
      Gosub Serial_end
      Print W ; "+" ; V ; "=" ; I ; " ";
      While V >= 1
         If V >= 128 Then
            J = 128
            V = V - 128
         Else
            J = V
            V = 0
         End If
         Print W ; "+" ; J ; " ";
Case_xx_retry:
         I2cstart
         I2cwbyte Eepromw
         If Err = 1 Then
            I2cstop
            Goto Case_xx_retry
         End If
         K = High(w) : I2cwbyte K
         K = Low(w) : I2cwbyte K
         W = W + J
         While J >= 1
            I2cwbyte I
            Decr J
         Wend
         I2cstop
      Wend
')
   Case "l"                                                 ' csv-log info
      Gosub Serial_end
      Print Csv_count;
   Case "L"                                                 ' csv-log ausgabe starten/stoppen
      Csv_count = Val(serial_chars(serial_pos))
      Gosub Serial_end
      If Csv_count <> 0 Then
         W = Eram_threshold
         V = Eram_hysteresis
         I = Eram_debounce
         Print "clock;analog;digital;counter;start=" ; Date$ ; " " ; Time$ ; " rows=" ; Csv_count ; " threshold=" ; W ; " hysteresis=" ; V ; " debounce=" ; I
      End If
   Case "w"                                                 ' dämmerungsschalter lesen
      Gosub Serial_end
      I = Twl_bgn1
      J = Twl_end1
      Print I ; " " ; J ; " " ;
      I = Twl_bgn2
      J = Twl_end2
      Print I ; " " ; J ; " " ;
      I = Twl_min2
      Print I ; " " ; _twl_cnt2 ; " " ; Twl_out ;
   Case "W"                                                 ' dämmerungsschalter setzen
      I = Val(serial_chars(serial_pos))
      If I >= 2 Then
         Twl_bgn1 = I
         Gosub Serial_next
         I = Val(serial_chars(serial_pos))
         Twl_end1 = I
         Gosub Serial_next
         I = Val(serial_chars(serial_pos))
         Twl_bgn2 = I
         Gosub Serial_next
         I = Val(serial_chars(serial_pos))
         Twl_end2 = I
         Gosub Serial_next
         I = Val(serial_chars(serial_pos))
         Twl_min2 = I
      Else
         Twl_out = I
      End If
      Gosub Serial_end
   Case "p":                                                ' diverse power info
      Gosub Serial_end
      Print Pwr_totalcnt ; "=" ; Pwr_totalkw ; "." ; Pwr_totalhw;
      Print " " ; Pwr_daycnt ; "=" ; Pwr_daykw ; "." ; Pwr_dayhw;
      Print " " ; Pwr_5mincnt ; " " ; Pwr_act;
   Case "P":                                                ' zählerstand setzen
      Gosub Serial_end
      Pwr_totalcnt = Val(serial_chars(serial_pos))
      Gosub Clock_write_totalcnt
      Gosub Pwr_calc
#if Withdbg = 1
   Case "g":
      Dbg
#endif
   Case "!":
      Goto Restart
   Case Else:
      Gosub Serial_end
      Print "bad arg at " ; Serial_pos ; ": " ; Serial_line ;
   End Select
   Gosub Serial_done
   Return
Baddaytime:
   Print "bad day/time: " ; Serial_line ;
   Gosub Serial_done
   Return
 
 
Restart:
   Disable Interrupts
   Gosub Xrom_now
   Xrom_5mincnt = Pwr_5mincnt
   Xrom_daycnt = Pwr_daycnt
   Gosub Clock_write_totalcnt
   Gosub Xrom_write_5min
   Gosub Xrom_write_day
   Wait 5                                                   ' hard reset durch watchdog
   'Goto &H1C00                                             ' soft reset. führte zu problemen. speicher nicht initialisiert oder interrupts noch aktiviert ?
 
'