forked from nanovna-v2/NanoVNA2-firmware
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main2.cpp
2216 lines (1940 loc) · 60.3 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is derived from libopencm3 example code.
*
* Copyright (C) 2010 Gareth McMullin <[email protected]>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#define PRNT(x)
#define PRNTLN(x)
#include <mculib/fastwiring.hpp>
#include <mculib/softi2c.hpp>
#include <mculib/si5351.hpp>
#include <mculib/dma_adc.hpp>
#include <mculib/usbserial.hpp>
#include <mculib/printf.hpp>
#include <mculib/printk.hpp>
#include <array>
#include <complex>
#include "main.hpp"
#include <board.hpp>
#include "ili9341.hpp"
#include "plot.hpp"
#include "uihw.hpp"
#include "ui.hpp"
#include "uihw.hpp"
#include "common.hpp"
#include "globals.hpp"
#include "synthesizers.hpp"
#include "vna_measurement.hpp"
#include "fifo.hpp"
#include "flash.hpp"
#include "calibration.hpp"
#include "fft.hpp"
#include "command_parser.hpp"
#include "stream_fifo.hpp"
#include "sin_rom.hpp"
#include "gain_cal.hpp"
#ifdef HAS_SELF_TEST
#include "self_test.hpp"
#endif
#include <libopencm3/stm32/timer.h>
#include <libopencm3/cm3/scb.h>
#include <libopencm3/cm3/vector.h>
using namespace mculib;
using namespace std;
using namespace board;
// see https://lists.debian.org/debian-gcc/2003/07/msg00057.html
// this can be any value since we are not using shared libraries.
void* __dso_handle = (void*) &__dso_handle;
static bool outputRawSamples = false;
int cpu_mhz = 8; /* The CPU boots on internal (HSI) 8Mhz */
int lo_freq = 12000; // IF frequency, Hz
int adf4350_freqStep = 12000; // adf4350 resolution, Hz
static USBSerial serial;
static const int adcBufSize=1024; // must be power of 2
static volatile uint16_t adcBuffer[adcBufSize];
static VNAMeasurement vnaMeasurement;
static CommandParser cmdParser;
static StreamFIFO cmdInputFIFO;
static uint8_t cmdInputBuffer[128];
/* This is written in the 'measurement thread' (ADC ISR)
* But read by the 'main thread'. So make it volatile */
static volatile bool lcdInhibit = false;
float gainTable[RFSW_BBGAIN_MAX+1];
__attribute__((packed))
struct usbDataPoint {
//VNAObservation value;
complexf S11, S21;
int freqIndex;
};
static usbDataPoint usbTxQueue[128];
static constexpr int usbTxQueueMask = 127;
static volatile int usbTxQueueWPos = 0;
static volatile int usbTxQueueRPos = 0;
// periods of a 1MHz clock; how often to call adc_process()
static constexpr int tim1Period = 25; // 1MHz / 25 = 40kHz
// periods of a 1MHz clock; how often to call UIHW::checkButtons
static constexpr int tim2Period = 50000; // 1MHz / 50000 = 20Hz
// value is in microseconds; increments at 40kHz by TIM1 interrupt
volatile uint32_t systemTimeCounter = 0;
static FIFO<small_function<void()>, 8> eventQueue;
static volatile bool usbDataMode = false;
static volatile bool usbCaptureMode = false;
static freqHz_t currFreqHz = 0; // current hardware tx frequency
// if nonzero, any ecal data in the next ecalIgnoreValues data points will be ignored.
// this variable is decremented every time a data point arrives, if nonzero.
static volatile int ecalIgnoreValues = 0;
static volatile int collectMeasurementType = -1;
static int collectMeasurementOffset = -1;
static int collectMeasurementState = 0;
static small_function<void()> collectMeasurementCB;
static void adc_process();
static int measurementGetDefaultGain(freqHz_t freqHz);
void cal_interpolate(void);
#define myassert(x) if(!(x)) do { errorBlink(3); } while(1)
template<unsigned int N>
static inline void pinMode(const array<Pad, N>& p, int mode) {
for(int i=0; i<(int)N; i++)
pinMode(p[i], mode);
}
static void errorBlink(int cnt) {
digitalWrite(led, HIGH);
while (1) {
for(int i=0;i<cnt;i++) {
digitalWrite(led, HIGH);
delay(200);
digitalWrite(led, LOW);
delay(200);
}
delay(1000);
}
}
#define errnoToPtr(x) ((void*)(uint32_t)(-x))
typedef void (*emitDataPoint_t)(int freqIndex, freqHz_t freqHz, VNAObservation v, const complexf* ecal, bool clipped);
// the parameters for one point in the sweep
struct sys_sweepPoint {
// populated with startFreq + i * stepFreq
int64_t freqHz = 0;
// populated with 0
uint32_t flags = 0;
// populated with 1; actual averaging factor is this multiplied by global nAverage
uint32_t nAverage = 1;
// populated with global dataPointsPerFreq
uint32_t dataPoints = 1;
// populated with 0; actual synth delay is baseDelay + extraSynthDelay + global extraSynthDelay
int16_t extraSynthDelay = 0;
// populated with 3
uint8_t adf4350_txPower = 3;
// populated with 1
uint8_t si5351_txPower = 1;
enum {
FLAG_POWERDOWN = 1,
FLAG_FORCE_ADF435X = 2,
FLAG_FORCE_SI5351 = 4,
FLAG_SKIP_SYNTH_SET = 8
};
};
struct sys_init_args {
volatile uint16_t* adcBuf;
volatile uint32_t* dmaCndtr;
uint32_t adcBufWords = 0;
emitDataPoint_t emitDataPoint;
};
struct sys_start_args {
};
struct sys_setSweep_args {
freqHz_t startFreqHz, stepFreqHz;
int nPoints, dataPointsPerFreq = 1;
uint32_t flags = 0;
// this function is called to modify the frequency or other parameters at
// each sweep point if FLAG_CUSTOMSWEEP is set.
// outParams is filled with default parameters and freqHz populated with
// startFreqHz + freqIndex * stepFreqHz when this function is called.
void (*sweepMutateParams)(int freqIndex, sys_sweepPoint* outParams);
enum {
FLAG_RFDISABLE=1,
FLAG_CUSTOMSWEEP=2
};
};
struct sys_setTimings_args {
uint32_t extraSynthDelay = 0;
uint32_t nAverage = 1;
};
typedef void* (*sys_syscall_t)(int opcode, void* args);
sys_syscall_t sys_syscall = (sys_syscall_t) 0x08000151;
sys_setSweep_args currSweepArgs;
sys_setTimings_args currTimingsArgs;
void sweepMutateParams(int freqIndex, sys_sweepPoint* outParams);
void setHWSweep(const sys_setSweep_args& sweepArgs) {
currSweepArgs = sweepArgs;
currSweepArgs.flags = sys_setSweep_args::FLAG_CUSTOMSWEEP;
currSweepArgs.sweepMutateParams = &sweepMutateParams;
sys_syscall(3, &currSweepArgs);
}
// period is in units of us
static void startTimer(uint32_t timerDevice, int period) {
// set the timer to count one tick per us
timer_set_mode(timerDevice, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
timer_set_prescaler(timerDevice, cpu_mhz-1);
timer_set_repetition_counter(timerDevice, 0);
timer_continuous_mode(timerDevice);
// this doesn't really set the period, but the "autoreload value"; actual period is this plus 1.
// this should be fixed in libopencm3.
timer_set_period(timerDevice, period - 1);
timer_enable_preload(timerDevice);
timer_enable_preload_complementry_enable_bits(timerDevice);
timer_enable_break_main_output(timerDevice);
timer_enable_irq(timerDevice, TIM_DIER_UIE);
TIM_EGR(timerDevice) = TIM_EGR_UG;
timer_set_counter(timerDevice, 0);
timer_enable_counter(timerDevice);
}
static void ui_timer_setup() {
rcc_periph_clock_enable(RCC_TIM2);
rcc_periph_reset_pulse(RST_TIM2);
nvic_set_priority(NVIC_TIM2_IRQ, 0x80);
nvic_enable_irq(NVIC_TIM2_IRQ);
startTimer(TIM2, tim2Period);
}
static void dsp_timer_setup() {
rcc_periph_clock_enable(RCC_TIM1);
rcc_periph_reset_pulse(RST_TIM1);
// set tim1 to highest priority
nvic_set_priority(NVIC_TIM1_UP_IRQ, 0x00);
nvic_enable_irq(NVIC_TIM1_UP_IRQ);
startTimer(TIM1, tim1Period);
}
extern "C" void tim1_up_isr() {
TIM1_SR = 0;
systemTimeCounter += tim1Period;
adc_process();
}
extern "C" void tim2_isr() {
TIM2_SR = 0;
UIHW::checkButtons();
}
static int si5351_doUpdate(uint32_t freqHz) {
// round frequency to values that can be accurately set, so that IF frequency is not wrong
// if(freqHz <= 10000000)
// freqHz = (freqHz/10) * 10;
// else
// freqHz = (freqHz/100) * 100;
return synthesizers::si5351_set(freqHz+lo_freq, freqHz);
}
static int si5351_update(uint32_t freqHz) {
static uint32_t prevFreq = 0;
int ret = si5351_doUpdate(freqHz);
if(freqHz < prevFreq)
si5351_doUpdate(freqHz);
prevFreq = freqHz;
return ret;
}
static void adf4350_setup() {
adf4350_rx.cpCurrent = 6;
adf4350_tx.cpCurrent = 6;
adf4350_rx.N = 120;
adf4350_rx.rfPower = (BOARD_REVISION >= 3 ? 0b10 : 0b00);
adf4350_rx.sendConfig();
adf4350_rx.sendN();
adf4350_tx.N = 120;
adf4350_tx.rfPower = 0b11;
adf4350_tx.sendConfig();
adf4350_tx.sendN();
}
static void adf4350_update(freqHz_t freqHz) {
adf4350_tx.rfPower = current_props._adf4350_txPower;
freqHz = freqHz_t(freqHz/adf4350_freqStep)*adf4350_freqStep;
synthesizers::adf4350_set(adf4350_tx, freqHz, adf4350_freqStep);
synthesizers::adf4350_set(adf4350_rx, freqHz + lo_freq, adf4350_freqStep);
}
/* Powerdown both devices */
static void adf4350_powerdown(void) {
adf4350_tx.sendPowerDown();
adf4350_rx.sendPowerDown();
}
static void adf4350_powerup(void) {
adf4350_tx.sendPowerUp();
adf4350_rx.sendPowerUp();
}
// automatically set IF frequency depending on rf frequency and board parameters
static void updateIFrequency(freqHz_t txFreqHz) {
#if BOARD_REVISION >= 3
nvic_disable_irq(NVIC_TIM1_UP_IRQ);
if(txFreqHz < 40000) { //|| (txFreqHz > 149000000 && txFreqHz < 151000000)) {
lo_freq = 6000;
adf4350_freqStep = 6000;
vnaMeasurement.setCorrelationTable(sinROM200x1, 200);
vnaMeasurement.adcFullScale = 10000 * 200 * 200;
vnaMeasurement.gainMax = 0;
vnaMeasurement.currThruGain = 0;
} else if(txFreqHz <= 350000) { //|| (txFreqHz > 149000000 && txFreqHz < 151000000)) {
lo_freq = 12000;
adf4350_freqStep = 12000;
vnaMeasurement.setCorrelationTable(sinROM100x1, 100);
vnaMeasurement.adcFullScale = 10000 * 100 * 100;
vnaMeasurement.gainMax = 0;
vnaMeasurement.currThruGain = 0;
} else {
lo_freq = 150000;
adf4350_freqStep = 10000;
vnaMeasurement.setCorrelationTable(sinROM10x2, 20);
vnaMeasurement.adcFullScale = 10000 * 48 * 20;
vnaMeasurement.gainMax = 3;
}
nvic_enable_irq(NVIC_TIM1_UP_IRQ);
#else
// adf4350 freq step and thus IF frequency must be a divisor of the crystal frequency
if(xtalFreqHz == 20000000 || xtalFreqHz == 40000000) {
// 6.25/12.5kHz IF
if(txFreqHz >= 100000) {
lo_freq = 12500;
adf4350_freqStep = 12500;
vnaMeasurement.setCorrelationTable(sinROM24x2, 48);
vnaMeasurement.adcFullScale = 20000 * 48 * 48;
} else {
lo_freq = 6250;
adf4350_freqStep = 6250;
vnaMeasurement.setCorrelationTable(sinROM48x1, 48);
vnaMeasurement.adcFullScale = 20000 * 48 * 48;
}
} else {
// 6.0/12.0kHz IF
if(txFreqHz >= 100000) {
lo_freq = 12000;
adf4350_freqStep = 12000;
vnaMeasurement.setCorrelationTable(sinROM25x2, 50);
vnaMeasurement.adcFullScale = 20000 * 48 * 50;
} else {
lo_freq = 6000;
adf4350_freqStep = 6000;
vnaMeasurement.setCorrelationTable(sinROM50x1, 50);
vnaMeasurement.adcFullScale = 20000 * 48 * 50;
}
}
#endif
}
// needed for correct automatic synthwait setting between board versions
__attribute__((used, noinline)) int calculateSynthWait(bool isSi, int retval) {
if(isSi) return calculateSynthWaitSI(retval);
else return calculateSynthWaitAF(retval);
}
// set the measurement frequency including setting the tx and rx synthesizers
void setFrequency(freqHz_t freqHz) {
updateIFrequency(freqHz);
// On measure, call phase change before update frequency call, so update gain for frequency range here
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(measurementGetDefaultGain(freqHz)));
/* Only if frequency changes apply the new frequency.
* This is to support proper CW mode:
* changing to an existing frequency temporarily breaks the signal */
if(currFreqHz != freqHz) {
currFreqHz = freqHz;
// use adf4350 for f >= 140MHz
if(is_freq_for_adf4350(freqHz)) {
adf4350_update(freqHz);
rfsw(RFSW_TXSYNTH, RFSW_TXSYNTH_HF);
rfsw(RFSW_RXSYNTH, RFSW_RXSYNTH_HF);
#ifdef EXPERIMENTAL_SYNTHWAIT
vnaMeasurement.nWaitSynth = calculateSynthWaitAF(freqHz);
#else
vnaMeasurement.nWaitSynth = calculateSynthWait(false, freqHz);
#endif
} else {
int ret = si5351_update(freqHz);
rfsw(RFSW_TXSYNTH, RFSW_TXSYNTH_LF);
rfsw(RFSW_RXSYNTH, RFSW_RXSYNTH_LF);
if(ret < 0 || ret > 2) ret = 2;
#ifdef EXPERIMENTAL_SYNTHWAIT
vnaMeasurement.nWaitSynth = calculateSynthWaitSI(ret);
#else
vnaMeasurement.nWaitSynth = calculateSynthWait(true, ret);
#endif
}
}
}
void sweepMutateParams(int freqIndex, sys_sweepPoint* outParams) {
sys_sweepPoint& sp = *outParams;
sp.adf4350_txPower = current_props._adf4350_txPower;
}
static void adc_setup() {
static uint8_t channel_array[1] = {adc_rxChannel};
dmaADC.buffer = adcBuffer;
dmaADC.bufferSizeBytes = sizeof(adcBuffer);
dmaADC.init(channel_array, 1);
adc_set_sample_time_on_all_channels(dmaADC.adcDevice, adc_ratecfg);
dmaADC.start();
}
// read and consume data from the adc ring buffer
void adc_read(volatile uint16_t*& data, int& len, int modulus=1) {
static uint32_t lastIndex = 0;
uint32_t cIndex = dmaADC.position();
uint32_t bufWords = dmaADC.bufferSizeBytes / 2;
cIndex &= (bufWords-1);
cIndex = (cIndex / modulus) * modulus;
lastIndex = (lastIndex / modulus) * modulus;
data = ((volatile uint16_t*) dmaADC.buffer) + lastIndex;
if(cIndex >= lastIndex) {
len = cIndex - lastIndex;
} else {
len = bufWords - lastIndex;
}
len = (len/modulus) * modulus;
lastIndex += len;
if(lastIndex >= bufWords) lastIndex = 0;
}
static void lcd_and_ui_setup() {
lcd_spi_init();
digitalWrite(ili9341_cs, HIGH);
digitalWrite(xpt2046_cs, HIGH);
pinMode(ili9341_cs, OUTPUT);
pinMode(xpt2046_cs, OUTPUT);
// setup hooks
ili9341_conf_dc = ili9341_dc;
ili9341_spi_set_cs = [](bool selected) {
lcd_spi_waitDMA();
while(lcdInhibit) ;
// if the xpt2046 is currently selected, deselect it
if(selected && digitalRead(xpt2046_cs) == LOW) {
digitalWrite(xpt2046_cs, HIGH);
}
digitalWrite(ili9341_cs, selected ? LOW : HIGH);
};
ili9341_spi_transfer = [](uint32_t sdi, int bits) {
return lcd_spi_transfer(sdi, bits);
};
ili9341_spi_transfer_bulk = [](uint32_t words) {
while(lcdInhibit) ;
lcd_spi_transfer_bulk((uint8_t*)ili9341_spi_buffer, words*2);
};
ili9341_spi_wait_bulk = []() {
lcd_spi_waitDMA();
};
ili9341_spi_read = [](uint8_t *buf, uint32_t bytes) {
lcd_spi_read_bulk(buf, bytes);
};
xpt2046.spiSetCS = [](bool selected) {
// a single SPI master is used for both the ILI9346 display and the
// touch controller; if an outstanding background DMA is in progress,
// we must wait for it to complete.
lcd_spi_waitDMA();
// if the ili9341 is currently selected, deselect it.
if(selected && digitalRead(ili9341_cs) == LOW) {
digitalWrite(ili9341_cs, HIGH);
}
digitalWrite(xpt2046_cs, selected ? LOW : HIGH);
};
xpt2046.spiTransfer = [](uint32_t sdi, int bits) {
myassert(digitalRead(ili9341_cs) == HIGH);
digitalWrite(ili9341_cs, HIGH);
lcd_spi_slow();
// delayMicroseconds(10);
uint32_t ret = lcd_spi_transfer(sdi, bits);
// delayMicroseconds(10);
lcd_spi_write();
return ret;
};
delay(10);
xpt2046.begin(LCD_WIDTH, LCD_HEIGHT);
ili9341_init();
lcd_spi_write();
// show test pattern
//ili9341_test(5);
// clear screen
ili9341_clear_screen();
// tell the plotting code how to calculate frequency in Hz given an index
plot_getFrequencyAt = [](int index) {
return UIActions::frequencyAt(index);
};
// the plotter will periodically call this function when doing cpu-heavy work;
// use it to process outstanding UI events so that the UI isn't sluggish.
plot_tick = []() {
UIActions::application_doEvents();
};
plot_init();
// redraw all zones next time we draw
redraw_request |= 0xff;
// don't block events
uiEnableProcessing();
// when the UI hardware emits an event, forward it to the UI code
UIHW::emitEvent = [](UIHW::UIEvent evt) {
// process the event on main thread; we are currently in interrupt context.
UIActions::enqueueEvent([evt]() {
ui_process(evt);
});
};
}
static void enterUSBDataMode() {
usbDataMode = true;
}
static void exitUSBDataMode() {
usbDataMode = false;
}
#ifdef BOARD_DISABLE_ECAL
// Made measure ecal, and apply correction
#define ecalApplyReflection(refl, freqIndex) refl
#else
complexf measuredEcal[ECAL_CHANNELS][USB_POINTS_MAX] alignas(8);
static complexf ecalApplyReflection(complexf refl, int freqIndex) {
#if defined(ECAL_PARTIAL)
return refl - measuredEcal[0][freqIndex];
#else
return SOL_compute_reflection(
measuredEcal[1][freqIndex],
1.f,
measuredEcal[0][freqIndex],
refl);
#endif
}
#endif
static complexf applyFixedCorrections(complexf refl, freqHz_t freq) {
// These corrections do not affect calibrated measurements
// and is only there to fix uglyness when uncalibrated and
// without full ecal.
// magnitude correction:
// - Near DC the balun is ineffective and measured refl is
// 0 for short circuit, 0.5 for load, and 1.0 for open circuit,
// requiring a correction of (refl*2 - 1.0).
// - Above 5MHz no correction is needed.
// - Between DC and 5MHz we apply something in between, with
// interpolation factor defined by a polynomial that is
// experimentally determined.
if(freq < 5000000) {
float x = float(freq) * 1e-6 * (3./5.);
x = 1 - x*(0.7 - x*(0.141 - x*0.006));
refl = refl * (1.f + x) - x;
}
// phase correction; experimentally determined polynomial
// x: frequency in MHz
// arg = -0.25 * x * (-1.39 + x*(0.35 - 0.022*x));
if(freq < 7500000) {
float x = float(freq) * 1e-6;
float im = -0.8f * x*(0.45f + x*(-0.12f + x*0.008f));
float re = 1.f;
refl *= complexf(re, im);
}
return refl;
}
static complexf applyFixedCorrectionsThru(complexf thru, freqHz_t freq) {
float scale = 0.5;
if(freq > 1900000000) {
float x = float(freq - 1900000000) / (4400000000 - 1900000000);
scale *= (1 - 0.8*x*(2 - x));
}
return thru * scale;
}
bool serialSendTimeout(const char* s, int len, int timeoutMillis) {
for(int i = 0; i < timeoutMillis; i++) {
if(serial.trySend(s, len))
return true;
delay(1);
}
return false;
}
/*
For a description of the command interface see command_parser.hpp
-- register map:
-- 00: sweepStartHz[7..0]
-- 01: sweepStartHz[15..8]
-- 02: sweepStartHz[23..16]
-- 03: sweepStartHz[31..24]
-- 04: sweepStartHz[39..32]
-- 05: sweepStartHz[47..40]
-- 06: sweepStartHz[55..48]
-- 07: sweepStartHz[63..56]
-- 10: sweepStepHz[7..0]
-- 11: sweepStepHz[15..8]
-- 12: sweepStepHz[23..16]
-- 13: sweepStepHz[31..24]
-- 14: sweepStepHz[39..32]
-- 15: sweepStepHz[47..40]
-- 16: sweepStepHz[55..48]
-- 17: sweepStepHz[63..56]
-- 20: sweepPoints[7..0]
-- 21: sweepPoints[15..8]
-- 22: valuesPerFrequency[7..0]
-- 23: valuesPerFrequency[15..8]
-- 26: dataMode: 0 => VNA data, 1 => raw data, 2 => exit usb data mode
-- 30: valuesFIFO - returns data points; elements are 32-byte. See below for data format.
-- command 0x14 reads FIFO data; writing any value clears FIFO.
-- 40: adf4350 power
-- 41: si5351 power (reserved)
-- 42: average setting
-- f0: device variant (01)
-- f1: protocol version (01)
-- f2: hardware revision
-- f3: firmware major version
-- register descriptions:
-- sweepStartHz - Sweep start frequency in Hz.
-- sweepStepHz - Sweep step frequency in Hz.
-- sweepPoints - Number of points in sweep.
-- valuesFIFO - Only command 0x13 supported; returns VNA data.
-- valuesFIFO element data format:
-- bytes:
-- 00: fwd0Re[7..0]
-- 01: fwd0Re[15..8]
-- 02: fwd0Re[23..16]
-- 03: fwd0Re[31..24]
-- 04: fwd0Im[7..0]
-- 05: fwd0Im[15..8]
-- 06: fwd0Im[23..16]
-- 07: fwd0Im[31..24]
-- 08: rev0Re[7..0]
-- 09: rev0Re[15..8]
-- 0a: rev0Re[23..16]
-- 0b: rev0Re[31..24]
-- 0c: rev0Im[7..0]
-- 0d: rev0Im[15..8]
-- 0e: rev0Im[23..16]
-- 0f: rev0Im[31..24]
-- 10: rev1Re[7..0]
-- 11: rev1Re[15..8]
-- 12: rev1Re[23..16]
-- 13: rev1Re[31..24]
-- 14: rev1Im[7..0]
-- 15: rev1Im[15..8]
-- 16: rev1Im[23..16]
-- 17: rev1Im[31..24]
-- 18: freqIndex[7..0]
-- 19: freqIndex[15..8]
-- 1a - 1f: reserved
*/
static void cmdRegisterWrite(int address);
//1425tX^^^^^^^^^^^^^^XXXXXXXXXXXXXXXXXXXXXXMMMMMM%Vc222$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$44443 \uuuuuuuuuuuuiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiyhz<ggggggggggggggggggggggggggggggggggg
static void cmdReadFIFO(int address, int nValues) {
if(address != 0x30) return;
if(!usbDataMode)
enterUSBDataMode();
// Set count as sweepPoints if 0
if (nValues == 0) nValues = *(uint16_t*)(registers + 0x20);
for(int i=0; i<nValues;) {
int rdRPos = usbTxQueueRPos;
int rdWPos = usbTxQueueWPos;
__sync_synchronize();
if(rdRPos == rdWPos) { // queue empty
continue;
}
usbDataPoint& usbDP = usbTxQueue[rdRPos];
if(usbDP.freqIndex < 0 || usbDP.freqIndex > USB_POINTS_MAX)
continue;
/*VNAObservation& value = usbDP.value;
value[0] = ecalApplyReflection(value[0] / value[1], usbDP.freqIndex) * value[1];
int32_t fwdRe = value[1].real();
int32_t fwdIm = value[1].imag();
int32_t reflRe = value[0].real();
int32_t reflIm = value[0].imag();
int32_t thruRe = value[2].real();
int32_t thruIm = value[2].imag();*/
complexf refl = ecalApplyReflection(usbDP.S11, usbDP.freqIndex);
complexf thru = usbDP.S21;
int32_t fwdRe = 1073741824;
int32_t fwdIm = 0;
int32_t reflRe = int32_t(refl.real() * 1073741824.f);
int32_t reflIm = int32_t(refl.imag() * 1073741824.f);
int32_t thruRe = int32_t(thru.real() * 1073741824.f);
int32_t thruIm = int32_t(thru.imag() * 1073741824.f);
uint8_t txbuf[32];
txbuf[0] = uint8_t(fwdRe >> 0);
txbuf[1] = uint8_t(fwdRe >> 8);
txbuf[2] = uint8_t(fwdRe >> 16);
txbuf[3] = uint8_t(fwdRe >> 24);
txbuf[4] = uint8_t(fwdIm >> 0);
txbuf[5] = uint8_t(fwdIm >> 8);
txbuf[6] = uint8_t(fwdIm >> 16);
txbuf[7] = uint8_t(fwdIm >> 24);
txbuf[8] = uint8_t(reflRe >> 0);
txbuf[9] = uint8_t(reflRe >> 8);
txbuf[10] = uint8_t(reflRe >> 16);
txbuf[11] = uint8_t(reflRe >> 24);
txbuf[12] = uint8_t(reflIm >> 0);
txbuf[13] = uint8_t(reflIm >> 8);
txbuf[14] = uint8_t(reflIm >> 16);
txbuf[15] = uint8_t(reflIm >> 24);
txbuf[16] = uint8_t(thruRe >> 0);
txbuf[17] = uint8_t(thruRe >> 8);
txbuf[18] = uint8_t(thruRe >> 16);
txbuf[19] = uint8_t(thruRe >> 24);
txbuf[20] = uint8_t(thruIm >> 0);
txbuf[21] = uint8_t(thruIm >> 8);
txbuf[22] = uint8_t(thruIm >> 16);
txbuf[23] = uint8_t(thruIm >> 24);
txbuf[24] = uint8_t(usbDP.freqIndex >> 0);
txbuf[25] = uint8_t(usbDP.freqIndex >> 8);
txbuf[26] = 0;
txbuf[27] = 0;
txbuf[28] = 0;
txbuf[29] = 0;
txbuf[30] = 0;
txbuf[31] = 0;
uint8_t checksum=0b01000110;
for(int i=0; i<31; i++)
checksum = (checksum xor ((checksum<<1) | 1)) xor txbuf[i];
txbuf[31] = checksum;
if(!serialSendTimeout((char*)txbuf, sizeof(txbuf), 1500)) {
return;
}
__sync_synchronize();
usbTxQueueRPos = (rdRPos + 1) & usbTxQueueMask;
i++;
}
}
// apply usb-configured sweep parameters
static void setVNASweepToUSB() {
int points = *(uint16_t*)(registers + 0x20);
int values = *(uint16_t*)(registers + 0x22);
if(points > USB_POINTS_MAX)
points = USB_POINTS_MAX;
#if BOARD_REVISION < 4
vnaMeasurement.sweepStartHz = (freqHz_t)*(uint64_t*)(registers + 0x00);
vnaMeasurement.sweepStepHz = (freqHz_t)*(uint64_t*)(registers + 0x10);
vnaMeasurement.sweepDataPointsPerFreq = values;
vnaMeasurement.sweepPoints = points;
vnaMeasurement.resetSweep();
if(outputRawSamples) {
setFrequency((freqHz_t)*(uint64_t*)(registers + 0x00));
}
#else
setHWSweep(sys_setSweep_args {
(freqHz_t)*(uint64_t*)(registers + 0x00),
(freqHz_t)*(uint64_t*)(registers + 0x10),
points,
values
});
if(outputRawSamples) {
// TODO: syscall: stop sweep
}
#endif
}
static void cmdRegisterWrite(int address) {
if(address == 0xee) {
usbCaptureMode = true;
#pragma pack(push, 1)
constexpr struct {
uint16_t width;
uint16_t height;
uint8_t pixelFormat;
} meta = { LCD_WIDTH, LCD_HEIGHT, 16 };
#pragma pack(pop)
serial.print((char*) &meta, sizeof(meta));
// use uint16_t ili9341_spi_buffers for read buffer
static_assert(meta.width * 2 <= sizeof(ili9341_spi_buffers));
for (int y=0; y < meta.height; y+=1){
ili9341_read_memory(0, y, meta.width, 1, ili9341_spi_buffers);
serial.print((char*) ili9341_spi_buffers, meta.width * 2 * 1);
}
usbCaptureMode = false;
return;
}
if (address == 0x40) {UIActions::set_averaging(registers[0x40]); return;}
if (address == 0x42) {UIActions::set_adf4350_txPower(registers[0x42]); return;}
if(!usbDataMode)
enterUSBDataMode();
if(address == 0x00 || address == 0x10 || address == 0x20 || address == 0x22) {
setVNASweepToUSB();
}
if(address == 0x26) {
auto val = registers[0x26];
if(val == 0) {
outputRawSamples = false;
} else if(val == 1) {
outputRawSamples = true;
} else if(val == 2) {
outputRawSamples = false;
exitUSBDataMode();
}
}
if(address == 0x00 || address == 0x10 || address == 0x20) {
ecalState = ECAL_STATE_MEASURING;
vnaMeasurement.ecalIntervalPoints = 1;
}
if(address == 0x30) {
usbTxQueueRPos = usbTxQueueWPos;
}
}
static void cmdInit() {
cmdParser.handleReadFIFO = [](int address, int nValues) {
return cmdReadFIFO(address, nValues);
};
cmdParser.handleWriteFIFO = [](int address, int totalBytes, int nBytes, const uint8_t* data) {};
cmdParser.handleWrite = [](int address) {
return cmdRegisterWrite(address);
};
cmdParser.send = [](const uint8_t* s, int len) {
serialSendTimeout((char*) s, len, 1500);
};
cmdParser.registers = registers;
cmdParser.registersSizeMask = registersSizeMask;
cmdInputFIFO.buffer = cmdInputBuffer;
cmdInputFIFO.bufferSize = sizeof(cmdInputBuffer);
cmdInputFIFO.output = [](const uint8_t* s, int len) {
cmdParser.handleInput(s, len);
};
}
static int measurementGetDefaultGain(freqHz_t freqHz) {
if(freqHz > 2500000000)
return 2;
else if(freqHz > FREQUENCY_CHANGE_OVER)
return 1;
else
return 0;
}
// callback called by VNAMeasurement to change rf switch positions.
static void measurementPhaseChanged(VNAMeasurementPhases ph) {
lcdInhibit = false;
switch(ph) {
case VNAMeasurementPhases::REFERENCE:
rfsw(RFSW_REFL, RFSW_REFL_ON);
rfsw(RFSW_RECV, RFSW_RECV_REFL);
rfsw(RFSW_ECAL, RFSW_ECAL_OPEN);
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(measurementGetDefaultGain(currFreqHz)));
break;
case VNAMeasurementPhases::REFL:
// If only measuring REFL and THRU, we skip REFERENCE and thus
// the rfsw are not setup correct, so fix it here
if (vnaMeasurement.measurement_mode == MEASURE_MODE_REFL_THRU) {
rfsw(RFSW_REFL, RFSW_REFL_ON);
rfsw(RFSW_RECV, RFSW_RECV_REFL);
}
rfsw(RFSW_ECAL, RFSW_ECAL_NORMAL);
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(measurementGetDefaultGain(currFreqHz)));
break;
case VNAMeasurementPhases::THRU:
rfsw(RFSW_ECAL, RFSW_ECAL_NORMAL);
rfsw(RFSW_REFL, RFSW_REFL_OFF);
rfsw(RFSW_RECV, RFSW_RECV_PORT2);
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(vnaMeasurement.currThruGain));
lcdInhibit = true;
break;
case VNAMeasurementPhases::ECALTHRU:
rfsw(RFSW_ECAL, RFSW_ECAL_LOAD);
rfsw(RFSW_RECV, RFSW_RECV_REFL);
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(measurementGetDefaultGain(currFreqHz)));
lcdInhibit = true;
break;
case VNAMeasurementPhases::ECALLOAD:
rfsw(RFSW_REFL, RFSW_REFL_ON);
rfsw(RFSW_RECV, RFSW_RECV_REFL);
rfsw(RFSW_ECAL, RFSW_ECAL_LOAD);
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(measurementGetDefaultGain(currFreqHz)));
break;
case VNAMeasurementPhases::ECALSHORT:
rfsw(RFSW_ECAL, RFSW_ECAL_SHORT);
rfsw(RFSW_BBGAIN, RFSW_BBGAIN_GAIN(measurementGetDefaultGain(currFreqHz)));
break;
}
}
// Allow smooth complex data point array (this remove noise, smooth power depend form count)
static void measurementDataSmooth(complexf *data, int points, int count){
int j;
while(count--){
complexf prev = data[0];
// first point smooth
data[0] = (prev + prev + data[1])/3.0f;
for (j=1;j<points-1;j++){
complexf old = data[j]; // save current data point for next point smooth
data[j] = (prev + data[j] + data[j] + data[j+1])/4.0f;
prev = old;
}
// last point smooth
data[j] = (data[j] + data[j] + prev)/3.0f;
}
}
#define USE_FIXED_CORRECTION
// callback called by VNAMeasurement when an observation is available.
static void measurementEmitDataPoint(int freqIndex, freqHz_t freqHz, VNAObservation v, const complexf* ecal, bool clipped) {
digitalWrite(led, clipped?1:0);
bool collectAllowed = true;
#if BOARD_REVISION < 4
v[2]*= gainTable[vnaMeasurement.currThruGain] / gainTable[measurementGetDefaultGain(freqHz)];
#ifdef USE_FIXED_CORRECTION
v[2] = applyFixedCorrectionsThru(v[2], freqHz);