-
Notifications
You must be signed in to change notification settings - Fork 1
/
AutoTuner.ino
1791 lines (1597 loc) · 62.6 KB
/
AutoTuner.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
//////////////////////////////////////////////////////////////////
// Copyright ©2014 Graeme Jury ZL2APV
// Released under the lgpl License - Please alter and share.
// Controller for the EB104.ru Auto Antenna Tuner
/////////////////////////////////////////////////////////////////
/*
+-----+
+------------| USB |------------+
| +-----+ |
Heartbeat B5 | [ ]D13/SCK MISO/D12[ ] | B4
| [ ]3.3V MOSI/D11[ ]~| B3
| [ ]V.ref ___ SS/D10[ ]~| B2
C0 | [ ]A0 / N \ D9[ ]~| B1
C1 | [ ]A1 / A \ D8[ ] | B0 Clock
C2 | [ ]A2 \ N / D7[ ] | D7 Latch
C3 | [ ]A3 \_0_/ D6[ ]~| D6 Data
C4 | [ ]A4/SDA D5[ ]~| D5 Freq Counter Input
C5 | [ ]A5/SCL D4[ ] | D4 Output Enable
| [ ]A6 INT1/D3[ ]~| D3 N/C
| [ ]A7 INT0/D2[ ] | D2 N/C
| [ ]5V GND[ ] |
C6 | [ ]RST RST[ ] | C6
| [ ]GND 5V MOSI GND TX1[ ] | D0
| [ ]Vin [ ] [ ] [ ] RX1[ ] | D1
| [ ] [ ] [ ] |
| MISO SCK RST |
| NANO-V3 |
+-------------------------------+
http://busyducks.com/ascii-art-arduinos
*/
#include <stdlib.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#include "defines.h"
// set the LCD address to 0x27 for a 20 chars 4 line display
// Set the pins on the I2C chip used for LCD connections:
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
// Bar part block characters definitions. Use lcd.write(6) for an empty bar
byte p1[8] = {
0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00
}; // 1 part of bar block
byte p2[8] = {
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00
};
byte p3[8] = {
0x00, 0x00, 0x1C, 0x1C, 0x1C, 0x1C, 0x00, 0x00
};
byte p4[8] = {
0x00, 0x00, 0x1E, 0x1E, 0x1E, 0x1E, 0x00, 0x00
}; // 4 parts of bar block
byte p5[8] = {
0x00, 0x00, 0x1F, 0x1F, 0x1F, 0x1F, 0x00, 0x00
}; // full bar block
byte p6[8] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
}; // blank bar block
// Global variables always start with an underscore
int _Button_array_max_value[num_of_analog_buttons];
int _Button_array_min_value[num_of_analog_buttons];
String rx_str = "";
boolean not_number = false;
unsigned int eepromTermAddr = 0;
struct status {
float fwd;
float rev;
float retLoss;
boolean tx_on;
boolean ampGain;
unsigned int freq;
byte C_relays;
byte L_relays;
boolean outputZ;
unsigned int totC;
unsigned int totL;
} _status;
struct MyValues {
unsigned int freq;
byte L;
byte C;
byte Z;
} val;
// Inductor definitions L1 L2 L3 L4 L5 L6 L7 L8
const unsigned int _inductors[] = { 6, 17, 35, 73, 136, 275, 568, 1099 }; // inductor values in nH
const unsigned int _strayL = 0;
// Capacitor definitions C1 C2 C3 C4 C5 C6 C7 C8
const unsigned int _capacitors[] = { 6, 11, 22, 44, 88, 168, 300, 660 }; // capacitor values in pF
const unsigned int _strayC = 0;
enum {INDUCTANCE, CAPACITANCE};
enum {POWERUP, TUNE, TUNING, TUNED};
byte _cmd = POWERUP; // Holds the command to be processed
const float tuneSWR = 18; //If retLoss < this value, forces a coarse tune. (Small value forces a tune)
boolean preset; // TODO remove this debug info on final version
//----------------------------------------------------------------------------------------------------------
void setup()
{
// First thing up, set C & L Relays to all off.
pinMode(Clock, OUTPUT); // make the 74HC164's clock pin an output
pinMode(Latch, OUTPUT); // make the 74HC164's latch pin an output
pinMode(Data , OUTPUT); // make the 74HC164 U4's data pin an output
pinMode(coRelay, OUTPUT);
digitalWrite(Clock, LOW);
_status.C_relays = 0;
_status.L_relays = 0;
_status.outputZ = loZ; // Caps switched to input side of L network
setRelays(); // Switch off all the relays & set c/o relay to input.
// Pin 13 of SR (output enable) is held high with a 10k pullup so random outputs won't operate the relays
// during power up. It needs to be held low after Arduino is booted and relay values initialised.
pinMode(outputEnable, OUTPUT); // Switch off HiZ mode for shift register
digitalWrite(outputEnable, LOW);
pinMode(swrGain, OUTPUT);
pinMode(LEDpin, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
digitalWrite(swrGain, LOW); // Turns off fet shunting swr Start with highest gain for amps.voltages
_status.ampGain = hi;
digitalWrite(BUTTON_PIN, HIGH); // pull-up activated
digitalWrite(analog_buttons_pin, HIGH); // pull-up activated
// digitalWrite(LEDpin, LOW);
lcd.begin(lcdNumRows, lcdNumCols);
// -- do some delay: some times I've got broken visualization
delay(100); // TODO Is this really necessary?
lcd.createChar(1, p1);
lcd.createChar(2, p2);
lcd.createChar(3, p3);
lcd.createChar(4, p4);
lcd.createChar(5, p5);
lcd.createChar(6, p6);
lcdPrintSplash();
//Initialize serial and wait for port to open:
Serial.begin(baudRate);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
initialize_analog_button_array();
// EEPROM[EEPROM.length()-1] = 0; //Uncomment this to force a reload of EEPROM values
// eeprom_initialise(); // and this line too
Serial.println(F("Arduino antenna tuner ver 2.0.0"));
Serial.println(F("Copyright (C) 2015, Graeme Jury ZL2APV"));
Serial.println();
EEPROM.get(eepromTermAddr, val.freq); // Initialise the terminator address for the eeprom
while (val.freq) {
eepromTermAddr += sizeof(MyValues);
EEPROM.get(eepromTermAddr, val.freq);
}
eeprom_Print();
}
//----------------------------------------------------------------------------------------------------------
void loop()
{
byte buttonNumber;
static unsigned long heartbeat = millis();
pollSerial();
getSWR();
// Serial.print(F("_cmd = ")); Serial.println(_cmd);
_cmd = processCommand(_cmd);
buttonNumber = getAnalogButton();
if (buttonNumber != 0) { // 0x00 is returned with no button press
_cmd = TUNED; // Stop any automatic tuning process with any button press
if (buttonNumber <= num_of_analog_buttons) {
// A short press trailing edge detected
processShortPressTE(buttonNumber);
}
else if (buttonNumber <= (num_of_analog_buttons + num_of_analog_buttons)) {
// A long press leading edge detected
buttonNumber = buttonNumber - num_of_analog_buttons;
processLongPressLE(buttonNumber);
#ifdef DEBUG_BUTTON_INFO
Serial.print(F("Loop: A long press leading edge detected on button "));
Serial.println(buttonNumber);
#endif
}
else {
// A long press trailing edge detected
buttonNumber = buttonNumber - (num_of_analog_buttons + num_of_analog_buttons);
processLongPressTE(buttonNumber);
}
}
// This button press will auto step the selected Capacitor or Inductor relays
// handle button
byte button_pressed = handle_button();
if (button_pressed) {
if (_cmd == TUNING) {
_cmd = POWERUP; // Any press halts a tune in progress
}
else {
switch (button_pressed) {
case 1:
{ // Leading edge of a button press which we ignore as we process trailing edges only.
break;
}
case 2:
{ // Short press, Initiate Autotune when RF present
#ifdef DEBUG_BUTTONS
Serial.println(F("Short press, Initiate Autotune when RF present"));
#endif
_cmd = TUNE;
break;
}
case 3:
{ // Medium press, Initiate Autotune when RF present
#ifdef DEBUG_BUTTONS
Serial.println(F("Medium press, Initiate Autotune when RF present"));
#endif
_cmd = TUNE;
break;
}
case 4:
{ // Long press, Not allocated yet
#ifdef DEBUG_BUTTONS
Serial.println(F("Long press, Bypass tuner"));
#endif
_status.C_relays = 0;
_status.L_relays = 0;
_status.outputZ = loZ; // Caps switched to input side of L network
setRelays(); // Switch off all the relays & set c/o relay to input.
_cmd = POWERUP;
lcdPrintSplash();
}
}
}
}
// Do heartbeat of 1 sec on and 1 sec off as non blocking routine
if (millis() > heartbeat) {
if (digitalRead(LEDpin)) {
digitalWrite(LEDpin, LOW); // turn the LED off
}
else digitalWrite(LEDpin, HIGH); // turn the LED on by making the voltage HIGH
heartbeat = (millis() + 1000);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Subroutines start here
////////////////////////////////////////////////////////////////////////////////////////////////////////////
byte processCommand(byte cmd)
{
float SWRtmp;
byte C_RelaysTmp; // Holds map of operated relays with C/O on input
byte L_RelaysTmp; // 0 = released and 1 = operated
boolean bestZ;
switch (cmd) {
case POWERUP:
{ // No tuning has been performed yet
if (_status.tx_on) { // We have enough Tx power so display the bargraph
lcdPrintBargraph(true);
} else { // We are receiving so display splash screen
lcdPrintSplash();
}
break;
}
case TUNE:
{ // Wait for sufficient RF fwd pwr then start tuning
// Serial.print(F("Got to TUNE, cmd = "));
// Serial.println(cmd);
if (_status.tx_on) {
lcdPrintBargraph(false);
cmd = TUNING;
} else {
lcd.home();
lcd.print(" Tune Pending ");
}
break;
}
case TUNING:
{ // Tuning is under way so process until finished
preset = true; // TODO remove this debug info on final version
tryPresets();
preset = false; // TODO remove this debug info on final version
#ifdef DEBUG_COARSE_TUNE_STATUS
Serial.print(F("@processCmd() .. _status.retLoss = "));
Serial.println(_status.retLoss, 5);
#endif
if (_status.retLoss < tuneSWR) {
#ifdef DEBUG_COARSE_TUNE_STATUS
Serial.println(F("Got here as no suitable preset found"));
#endif
_status.outputZ = loZ;
// function doRelayCoarseSteps() returns true if tune aborted with cmd button press
if (doRelayCoarseSteps()) {
_status.C_relays = 0; // set relays back to power on settings.
_status.L_relays = 0;
_status.outputZ = loZ;
setRelays();
cmd = POWERUP;
break;
}
//Save SWR and relay states and see if better with C/O relay on output
C_RelaysTmp = _status.C_relays;
L_RelaysTmp = _status.L_relays;
bestZ = _status.outputZ;
SWRtmp = _status.retLoss;
#ifdef DEBUG_COARSE_TUNE_STATUS1
Serial.println(F("LoZ coarse tune results"));
printStatus(printHeader);
printStatus(printBody);
#endif
if (_status.retLoss < 20) { // Only try again if swr needs improving (VSWR = 1.22:1)
_status.outputZ = hiZ;
doRelayCoarseSteps(); //Run it again and see if better with C/O relay operated
#ifdef DEBUG_COARSE_TUNE_STATUS1
Serial.println(F("HiZ coarse tune results"));
printStatus(printHeader);
printStatus(printBody);
#endif
if (SWRtmp > _status.retLoss) { // Capacitors on Input side gave best result so
_status.C_relays = C_RelaysTmp; // set relays back to where they were on input.
_status.L_relays = L_RelaysTmp;
_status.outputZ = bestZ;
setRelays();
getSWR();
}
}
}
#ifdef DEBUG_COARSE_TUNE_STATUS1
Serial.println(F("Final coarse tune results"));
printStatus(printHeader);
printStatus(printBody);
#endif
doRelayFineSteps();
cmd = TUNED;
lcdPrintStatus();
}
case TUNED:
{ // Update LCD display
if (_status.tx_on) {
lcdPrintBargraph(true);
} else {
lcdPrintStatus();
}
break;;
}
default:
cmd = TUNED;
}
return cmd;
}
//----------------------------------------------------------------------------------------------------------
void doRelayFineSteps()
{
byte Crelays;
byte Lrelays;
getSWR(); // Get swr and relay status up to date.
#ifdef DEBUG_RELAY_FINE_STEPS
int cnt = 1;
Serial.println(F("@doRelayFineSteps: Values on entry"));
printStatus(printHeader);
printStatus(printBody);
#endif
do {
Lrelays = _status.L_relays;
fineStep(INDUCTANCE); // Starts with best from stepping L relays.
#ifdef DEBUG_RELAY_FINE_STEPS
// printStatus(printBody);
#endif
Crelays = _status.C_relays;
fineStep(CAPACITANCE); // Try for an improvement from stepping C relays
#ifdef DEBUG_RELAY_FINE_STEPS
printStatus(printBody);
cnt++;
#endif
}
while ((_status.L_relays != Lrelays) && (_status.C_relays != Crelays)); // If any relays alter, go again
#ifdef DEBUG_RELAY_FINE_STEPS
Serial.print(F("doRelayFineSteps(): Been through loop "));
Serial.print(cnt);
Serial.println(F(" times."));
#endif
#ifdef DEBUG_RELAY_FINE_STEPS
Serial.println(F("-----------------------------------------------------------------------------------"));
Serial.println(F("Exiting doRelayFineSteps(): values on exit ..."));
printStatus(printHeader);
printStatus(printBody);
#endif
}
//--------------------------------------------------------------------------------------------------------/
void fineStep(bool LC) // Enter with swr and relay status up to date
{
// On entry, we look at the return Loss from the current relay settings and the returnLoss from the
// 4 relay steps each side to see if there is a trend and in which direction. The return loss from the
// 9 relays is read into an array which is examined to see if we need to step up or step down. A check
// is made to ensure that stepping the relays won't overflow 255 or underflow 0 then the array is
// traversed up or down consecutive relays until the best SWR is centred at values[4]. The associated
// relays are set in _status array. Parameter reactance determines whether we are stepping
// _status.C_relays or _status.L_relays.
float values[ARRAY_SIZE]; // Array to hold SWR values as L and C relays are traversed
uint8_t *pReactance; // A pointer to either _status.C_relays or _status.L_relays
float startRetLoss;
float bestRetLoss = 0;
uint8_t bestRelays = 0; // Record the relays holding the best rawSWR to date
uint8_t arrayStartRelay = 0;
// int startRelay = 0; // Declared as int as we may over or underflow 255 during testing relay positions.
int x;
/*
// TEST DATA HERE, ERASE ON FINAL VERSION !!!!!
_status.L_relays = 251;
_status.C_relays = 10;
for (x = 0; x < ARRAY_SIZE; x++) {
values[x] = x + 10;
}
values[4] = 50; // Set to correspond with _status.L_relays after array loaded
values[4] = 55; // Optional simulated better return loss, otherwise = to above
// END OF TEST DATA !!!!!
*/
// 1. Housekeeping
// ---------------
if (LC == INDUCTANCE) { // Choose whether we are working on the inductance or capacitance relays
pReactance = &_status.L_relays;
} else {
pReactance = &_status.C_relays;
}
// 2. Test that we won't overflow the relay boundries and adjust
// -------------------------------------------------------------
// There are 256 steps (0 - 255) for the L and C relays. We check here that we won't go above 255 or
// below 0 as we check the return loss for the L or C relay set grouped around our starting point.
// Set the arrayStartRelay value which will point to the first value in the array which may result
// in its being set over or under 255 for this initial setting.
// EXIT: *pReactance points to the relays of best return loss as per function entry value.
// arrayStartRelay points to the relays corresponding to the first element of the array.
// NOTE: an unsigned int will overflow from 255 to 0 or from 0 to 255.
arrayStartRelay = *pReactance - ARRAY_SIZE / 2;
#ifdef DEBUG_FINE_STEP
Serial.println();
Serial.print("arrayStartRelay value 1 = "); Serial.println(arrayStartRelay);
#endif
if (*pReactance <= ARRAY_SIZE / 2) {
arrayStartRelay = 0;
#ifdef DEBUG_FINE_STEP
Serial.print("arrayStartRelay value 2 = "); Serial.println(arrayStartRelay);
#endif
}
if (*pReactance >= 255 - ARRAY_SIZE / 2) {
arrayStartRelay = 255 - ARRAY_SIZE + 1;
#ifdef DEBUG_FINE_STEP
Serial.print("arrayStartRelay value 3 = "); Serial.println(arrayStartRelay);
#endif
}
#ifdef DEBUG_FINE_STEP
Serial.print("After step 2, *pReactance = "); Serial.println(*pReactance);
#endif
// 3. Load the array with return loss values from the relays surrounding the entry relays
// --------------------------------------------------------------------------------------
// Start loading the array with SWR values knowing that we won't overflow either the L or C relays
// Note that if we are at a relay boundry we may not have the entry relay at the array centre.
*pReactance = arrayStartRelay; // Set the L or C Relays values to the left side of the array
#ifdef DEBUG_FINE_STEP
Serial.print("After step 3 setting to LHS of array, *pReactance = "); Serial.println(*pReactance);
#endif
// Now read the set of return loss into the array.
for (x = 0; x < ARRAY_SIZE; x++) {
setRelays();
getSWR();
values[x] = _status.retLoss;
*pReactance = (*pReactance + 1);
}
*pReactance = (*pReactance - 1); // Remove the extra step created before the loop terminated.
// we finish with the *pReactance aligned with the RHS value of the array.
#ifdef DEBUG_FINE_STEP
Serial.print("After step 3 array loaded, *pReactance = "); Serial.println(*pReactance);
#endif
//4. Shift the array left or right to set the best return loss value to the centre of the array
// --------------------------------------------------------------------------------------------
startRetLoss = _status.retLoss;
bestRelays = *pReactance; // Save our best relay settings to date which is our entry value so far.
#ifdef DEBUG_FINE_STEP
Serial.println(); // Print the header for the table of relay stepping
if (LC == INDUCTANCE) {
Serial.println(F("\t\t\t Inductance"));
} else {
Serial.println(F("\t\t\t Capacitance"));
}
Serial.print("\t");
for (x = arrayStartRelay; x < arrayStartRelay + ARRAY_SIZE; x++) {
Serial.print(x); Serial.print("\t");
}
Serial.println();
#endif
#ifdef DEBUG_FINE_STEP
for (x = 0; x < ARRAY_SIZE; x++) {
Serial.print("\t");
Serial.print(values[x], 3);
}
#endif
findbestRetLoss(arrayStartRelay, pReactance, values);
Serial.print(F("\t*pReactance = ")); Serial.print(*pReactance);
Serial.print(F(", arrayStartRelay = ")); Serial.println(arrayStartRelay);
bestRelays = *pReactance;
// Testing for the location of best return loss relative to the centre of the array to see if we need
// to shift right or left. if cnt < valuesCentre, we need to search down but not if lowRelay at 0 or we will underflow
// If cnt = valuesCentre we have found the SWR dip
// If cnt > valuesCentre, we need to search up but not if lowRelay at 255-valuesSize or more else
// we will overflow.
if (bestRelays == (arrayStartRelay + ARRAY_SIZE / 2)) { // We are already at the array centre
Serial.println(F("At array centre"));
} else {
if (bestRelays < (arrayStartRelay + ARRAY_SIZE / 2)) { // We want to traverse right
Serial.println(F("Moving array window left"));
while ((arrayStartRelay > 0) && (bestRelays - arrayStartRelay < (ARRAY_SIZE / 2))) {
// Serial.print(F("bestRelays - arrayStartRelay = ")); Serial.println(bestRelays - arrayStartRelay);
for (x = ARRAY_SIZE - 1; x > 0; x--) {
values[x] = values[x - 1];
}
arrayStartRelay -= 1;
*pReactance = arrayStartRelay;
setRelays();
getSWR();
values[0] = _status.retLoss;
findbestRetLoss(arrayStartRelay, pReactance, values);
bestRelays = *pReactance;
#ifdef DEBUG_FINE_STEP
for (x = 0; x < ARRAY_SIZE; x++) {
Serial.print("\t");
Serial.print(values[x], 3);
}
Serial.print(F("\tarrayStartRelay-1+ARRAY_SIZE = ")); Serial.println(arrayStartRelay - 1 + ARRAY_SIZE);
#endif
}
} else {
Serial.println(F("Moving array window right"));
Serial.print(F("arrayStartRelay = ")); Serial.println(arrayStartRelay);
Serial.print(F("255 - ARRAY_SIZE = ")); Serial.println(255 - ARRAY_SIZE);
Serial.print(F("bestRelays - arrayStartRelay = ")); Serial.println(bestRelays - arrayStartRelay);
while ((arrayStartRelay <= 255 - ARRAY_SIZE) && (bestRelays - arrayStartRelay > (ARRAY_SIZE / 2))) {
for (x = 0; x < ARRAY_SIZE; x++) {
values[x] = values[x + 1];
}
arrayStartRelay += 1;
*pReactance = arrayStartRelay + ARRAY_SIZE;
setRelays();
getSWR();
values[ARRAY_SIZE - 1] = _status.retLoss;
findbestRetLoss(arrayStartRelay, pReactance, values);
bestRelays = *pReactance;
#ifdef DEBUG_FINE_STEP
for (x = 0; x < ARRAY_SIZE; x++) {
Serial.print("\t");
Serial.print(values[x], 3);
}
Serial.print(F("\tarray end = ")); Serial.println(arrayStartRelay - 1 + ARRAY_SIZE);
#endif
}
}
}
*pReactance = bestRelays;
setRelays(); // now operate them.
getSWR(); // and get final rawSWR value
#ifdef DEBUG_FINE_STEP
Serial.print(F("Exiting fineStep(), *pReactance = ")); Serial.println(*pReactance);
Serial.print(F("values[ARRAY_SIZE/2] = ")); Serial.println(values[ARRAY_SIZE / 2]);
Serial.print(F("bestRelays = ")); Serial.println(bestRelays);
// Serial.print(F("startRelay = ")); Serial.println(startRelay);
Serial.print(F("arrayStartRelay = ")); Serial.println(arrayStartRelay);
#endif
}
//--------------------------------------------------------------------------------------------------------/
void findbestRetLoss(uint8_t arrayStartRelay, uint8_t* pReactance, float values[])
{
// We need to scan the array to find the highest return loss and load the _status struct with
// the rawSWR value and the C and L relay values which produced it.
float bestRetLoss = 0;
uint8_t bestRelays = 0;
for (uint8_t x = 0; x < ARRAY_SIZE; x++) {
if (values[x] > bestRetLoss) {
bestRetLoss = values[x];
bestRelays = arrayStartRelay + x;
}
}
*pReactance = bestRelays; // ToDo see if we can get rid of bestRelays
}
//--------------------------------------------------------------------------------------------------------/
void eeprom_Load(unsigned int freq)
{
// Loads the passed frequency into the eeprom table of presets
// If freq = 0 then the table is cleared and reset to address 0 as start/end of table
// If frequency is higher than any other in the table it will be appended
// If frequency is lower than any table entry it will be pre-pended
// Otherwise the frequency will be inserted so as to keep the table in ascending frequency.
int eeAddress = 0;
int eeAddrHi = 0;
boolean endFlag = false;
if (freq == 0) {
eepromTermAddr = 0;
EEPROM.put(eepromTermAddr, 0);
Serial.println(F("Relay table has been zeroed"));
} else {
EEPROM.get(eeAddress, val.freq);
if (val.freq == 0) {
// endFlag = true; // If 1st addr = 0 (terminator) then we have a non loaded eeprom
EEPROM.put(eeAddress, freq);
eepromTermAddr += sizeof(MyValues);
EEPROM.put(eepromTermAddr, 0);
Serial.print(F("eeAddress = ")); Serial.print(eeAddress);
Serial.print(F(", eepromTermAddr = ")); Serial.println(eeAddress);
}
while ((val.freq) || (endFlag)) {
// We only get here if val.freq is a non zero number or we want to append the frequency
if (val.freq == freq) {
// The frequency we are entering matches a frequency already in the presets
// so simply overwrite it.
val.L = _status.L_relays;
val.C = _status.C_relays;
val.Z = _status.outputZ;
EEPROM.put(eeAddress, val);
Serial.print(F("freq ")); Serial.print(val.freq); Serial.print(F(" written to presets at address "));
Serial.println(eeAddress);
break;
} else {
Serial.print(F("val.freq = ")); Serial.print(val.freq);
Serial.print(F("; freq = ")); Serial.print(freq);
Serial.print(F("; eeAddress = ")); Serial.println(eeAddress);
// -------------------------------------------------------
if ((val.freq > freq) || (endFlag)) { // Don't process for frequencies less than the entry frequency
// val.freq must be greater than freq or we have reached the end to get here.
// We are going to insert the tune values in the address before this one
// (which is held in eeAddrHi). All the values above will need to be
// shifted up one to allow the tune data to be inserted.
Serial.println();
eeAddrHi = eeAddress;
eeAddress = eepromTermAddr;;
eepromTermAddr += sizeof(MyValues);//Move address to one struct item beyond
EEPROM.put(eepromTermAddr, 0);
Serial.print(F("Entering while loop, eeAddrHi = ")); Serial.print(eeAddrHi);
Serial.print(F("; eeAddress = ")); Serial.print(eeAddress);
Serial.print(F("; eepromTermAddr = ")); Serial.println(eepromTermAddr);
while ((eeAddress >= eeAddrHi) || (eeAddress == 0)) {
EEPROM.get(eeAddress, val.freq);
Serial.print(F("Start address = ")); Serial.print(eeAddress); Serial.print(F(" val.freq = ")); Serial.print(val.freq);
eeAddress += sizeof(unsigned int); // Step off freq to L
EEPROM.get(eeAddress, val.L);
eeAddress += sizeof(byte); // Step off L to C
EEPROM.get(eeAddress, val.C);
eeAddress += sizeof(byte); // Step off C to Z
EEPROM.get(eeAddress, val.Z);
eeAddress += sizeof(byte);
EEPROM.put(eeAddress, val);
Serial.print(F(" Finish address = ")); Serial.println(eeAddress);
eeAddress -= (sizeof(MyValues) * 2);
}
val.freq = freq;
val.L = _status.L_relays;
val.C = _status.C_relays;
val.Z = _status.outputZ;
eeAddress = eeAddrHi;
EEPROM.put(eeAddress, val);
Serial.print(F("insert freq ")); Serial.print(val.freq); Serial.print(F(" written to presets at address "));
Serial.println(eeAddress);
eeAddress = (eepromTermAddr - sizeof(MyValues));
break;
}
// -------------------------------------------------------
eeAddress += sizeof(MyValues);//Move address to the next struct item
// Serial.print(F("eeAddress = ")); Serial.println(eeAddress);
EEPROM.get(eeAddress, val.freq); //Get next frequency or 0000 if at end
if (val.freq == 0) endFlag = true;
// Serial.print(F("Exiting else, val.freq = ")); Serial.println(val.freq);
}
}
EEPROM.put(eepromTermAddr, 0);
Serial.print(F("eeprom_Load() exit freq ")); Serial.print(val.freq);
Serial.print(F(", eepromTermAddr = ")); Serial.println(eepromTermAddr);
eeprom_Print();
}
}
//--------------------------------------------------------------------------------------------------------/
void eeprom_Print()
{
int eeAddress = 0;
Serial.println(F("-------------------"));
Serial.println(F("Freq, L_relays, C_Relays, outputZ, Address"));
EEPROM.get(eeAddress, val.freq);
while (val.freq) {
eeAddress += sizeof(unsigned int); // Step off freq to L
EEPROM.get(eeAddress, val.L);
eeAddress += sizeof(byte); // Step off L to C
EEPROM.get(eeAddress, val.C);
eeAddress += sizeof(byte); // Step off C to Z
EEPROM.get(eeAddress, val.Z);
eeAddress += sizeof(byte);
Serial.print(val.freq);
Serial.print(F("\t")); Serial.print(val.L);
Serial.print(F("\t ")); Serial.print(val.C);
Serial.print(F("\t ")); Serial.print(val.Z);
Serial.print(F("\t ")); Serial.println(eeAddress - sizeof(MyValues));
EEPROM.get(eeAddress, val.freq); //Get next frequency or 0000 if at end
}
Serial.print(val.freq);
Serial.print(F(" eepromTermAddr = ")); Serial.println(eepromTermAddr);
Serial.println(F("-------------------")); Serial.println();
}
//--------------------------------------------------------------------------------------------------------/
void pollSerial()
{
// Uses the following globals ...
// String rx_str = "";
// boolean not_number = false;
unsigned int freq;
char rx_byte = 0;
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character
if ((rx_byte >= '0') && (rx_byte <= '9')) {
rx_str += rx_byte;
}
else if (rx_byte == '\n') {
// end of string
if (not_number) {
Serial.println("Invalid Frequency");
}
else {
freq = rx_str.toInt();
// print the result
Serial.print(F("freq = "));
Serial.print(rx_str);
Serial.print(F(", L_Relay = "));
Serial.print(_status.L_relays);
Serial.print(F(", C_Relay = "));
Serial.print(_status.C_relays);
Serial.print(F(", outputZ = "));
Serial.println(_status.outputZ);
eeprom_Load(freq);
Serial.println(F("Enter a frequency to add to eeprom"));
}
not_number = false; // reset flag
rx_str = ""; // clear the string for reuse
}
else {
// non-number character received
not_number = true; // flag a non-number
}
} // end: if (Serial.available() > 0)
}
//--------------------------------------------------------------------------------------------------------/
void eeprom_initialise()
{
// this routine loads some preset values into eeprom for fast tuning. In the final version this will become
// redundant as the values will be loaded by frequency with the counter installation. A magic number is
// loaded into the last byte of the eeprom to indicate that it is already loaded with tune values and we
// don't duplicate the data at each switch on.
// The FT8 frequency for each band is used as the preset frequency
/*
struct MyValues {
unsigned int freq;
byte L;
byte C;
byte Z;
} val;
*/
int eeAddress = 0;
if (EEPROM[EEPROM.length() - 1] != 120) {
val.freq = 3573; val.L = B00101001; val.C = B10010001; val.Z = loZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);//Move address to the next struct item
val.freq = 7074; val.L = B00000000; val.C = B00011100; val.Z = loZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 10136; val.L = B00010100; val.C = B00110000; val.Z = hiZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 14074; val.L = B00001100; val.C = B00010000; val.Z = hiZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 18100; val.L = B00001010; val.C = B00000011; val.Z = hiZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 21074; val.L = B00000111; val.C = B00001110; val.Z = hiZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 24915; val.L = B00000101; val.C = B00000111; val.Z = hiZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 28074; val.L = B00000000; val.C = B00000010; val.Z = hiZ; //
EEPROM.put(eeAddress, val);
eeAddress += sizeof(MyValues);
val.freq = 0; val.L = 0; val.C = 0; val.Z = loZ; //Zero values for a terminator
EEPROM.put(eeAddress, val);
EEPROM[EEPROM.length() - 1] = 120; //Put a marker to show that data has been loaded into the eeprom
Serial.println(F("EEPROM initialised"));
} else {
Serial.println(F("EEPROM was already initialised"));
}
}
//----------------------------------------------------------------------------------------------------------
/* Here I pre-load some settings for each band and see if swr is low enough to indicate a
suitable starting point for a tune.
*/
void tryPresets()
{
float returnLoss;
unsigned int frequency;
byte Crelays;
byte Lrelays;
boolean loadZ;
int eeAddress = 0;
returnLoss = 0.001; //Force _status to be copied to statusTemp first time through the while loop
EEPROM.get(eeAddress, _status.freq);
while (_status.freq) {
eeAddress += sizeof(unsigned int); // Step off freq to L
EEPROM.get(eeAddress, _status.L_relays);
eeAddress += sizeof(byte); // Step off L to C
EEPROM.get(eeAddress, _status.C_relays);
eeAddress += sizeof(byte); // Step off C to Z
EEPROM.get(eeAddress, _status.outputZ);
eeAddress += sizeof(byte);
setRelays();
delay(Relay_Settle_Millis); //Add 20 mSec of settling time before taking the SWR reading
getSWR();
Serial.print(F("Freq, L, C, Vf, Vr, Z, RL, SWR = "));
Serial.print(_status.freq);
Serial.print(F(", ")); Serial.print(_status.L_relays);
Serial.print(F(", ")); Serial.print(_status.C_relays);
Serial.print(F(", ")); Serial.print(_status.fwd);
Serial.print(F(", ")); Serial.print(_status.rev);
Serial.print(F(", ")); Serial.print(_status.outputZ);
Serial.print(F(", ")); Serial.print(_status.retLoss, 5);
Serial.print(F(", ")); Serial.println((pow(10, (_status.retLoss / 20)) + 1) / (pow(10, (_status.retLoss / 20)) - 1));
if (returnLoss < _status.retLoss) {
returnLoss = _status.retLoss;
frequency = _status.freq;
Crelays = _status.C_relays;
Lrelays = _status.L_relays;
loadZ = _status.outputZ;
}
EEPROM.get(eeAddress, _status.freq); //Get next frequency or 0000 if at end
}
Serial.print(F("@void tryPresets() .. Best returnLoss = "));
Serial.println(returnLoss, 5);
Serial.println(F("--------------------")); // TODO remove this debug info on final version
_status.freq = frequency;
_status.C_relays = Crelays;
_status.L_relays = Lrelays;
_status.outputZ = loadZ;
setRelays();
delay(Relay_Settle_Millis); //Add 20 mSec of settling time before taking the SWR reading
getSWR();
Serial.println(F("--------------------")); // TODO remove this debug info on final version
Serial.print(F("Freq, L, C, Vf, Vr, Z, RL, SWR = "));
Serial.print(_status.freq);
Serial.print(F(", ")); Serial.print(_status.L_relays);
Serial.print(F(", ")); Serial.print(_status.C_relays);
Serial.print(F(", ")); Serial.print(_status.fwd);
Serial.print(F(", ")); Serial.print(_status.rev);
Serial.print(F(", ")); Serial.print(_status.outputZ);
Serial.print(F(", ")); Serial.print(_status.retLoss, 5);
Serial.print(F(", ")); Serial.println((pow(10, (_status.retLoss / 20)) + 1) / (pow(10, (_status.retLoss / 20)) - 1));
Serial.println();
}
//----------------------------------------------------------------------------------------------------------
boolean doRelayCoarseSteps()
{
// This subroutine steps through the capacitor and inductor relays looking for the combination which gives
// the best return loss. Only individual relays are stepped with no multiple C or L combinations so a fine
// tune subroutine is later called to set exact values for L and C.
// This procedure is carried out by initially setting capacitor relays to zero C and stepping the inductor
// relays one by one from no relays to all 8. The capacitor relay is incremented and procedure repeated.
// The SWR is read at each step into an 2 dimensional array which is later parsed for the best Return Loss
// and the C and L combination to give this is set along with retLoss in the _status array.
// A check of the command button is made and tune aborted with a return of true if a press detected. The
// caller should perform the abort process.
// Entry: The caller sets the C/O relay to HiZ or LoZ as required
// Exit with relay settings giving best return Loss for the C/O relay setting on entry.
// Result held in _status struct.
float values[numLrelays][numCrelays];
float bestRetLoss = 0;
uint8_t bestC = 0;
uint8_t bestL = 0;
char pntBuffer[16];
// Step through states of no relays operated to all relays operated
getSWR();
for (byte c = 0; c < numCrelays; c++) {
_status.C_relays = 0;
if (c != 0) {
bitSet(_status.C_relays, c - 1);
}
for (byte x = 0; x < numLrelays; x++) {
_status.L_relays = 0;
if (x != 0) {
bitSet(_status.L_relays, x - 1);
}
setRelays();
// Check at this point for a command button press and abandon tune if so.
if (handle_button()) { // Any button change triggers abort tune.
return true;
}
getSWR();
values[c][x] = _status.retLoss;
} // end inner for loop
} //end outer for loop
// We parse the array looking for the combination of L and C relays which give lowest SWR
for (byte c = 0; c < numCrelays; c++) {
for (byte l = 0; l < numLrelays; l++) {
if (values[c][l] > bestRetLoss) {
bestRetLoss = values[c][l];
bestC = c;
bestL = l;
}
}
}
// Now set the relays to give best coarse tune based on bestSWR
_status.C_relays = 0; // No bits set for no relays operated
_status.L_relays = 0;
if (bestC > 0) bitSet(_status.C_relays, bestC - 1); // Set bits 0 .. 7 here (Relays 1 to 8)