This repository has been archived by the owner on Oct 22, 2024. It is now read-only.
forked from JamesP6000/WsprryPi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wspr.cpp
1475 lines (1366 loc) · 50.7 KB
/
wspr.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
// WSPR transmitter for the Raspberry Pi. See accompanying README
// file for a description on how to use this code.
// License:
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ha7ilm: added RPi2 support based on a patch to PiFmRds by Cristophe
// Jacquet and Richard Hirst: http://git.io/vn7O9
#include <algorithm>
#include <assert.h>
#include <cmath>
#include <cstdint>
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <iomanip>
#include <iostream>
#include <malloc.h>
#include <math.h>
#include <pthread.h>
#include <signal.h>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/timex.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <vector>
#ifdef __cplusplus
extern "C" {
#include "mailbox.h"
#include "nhash.h"
}
#endif /* __cplusplus */
// Note on accessing memory in RPi:
//
// There are 3 (yes three) address spaces in the Pi:
// Physical addresses
// These are the actual address locations of the RAM and are equivalent
// to offsets into /dev/mem.
// The peripherals (DMA engine, PWM, etc.) are located at physical
// address 0x2000000 for RPi1 and 0x3F000000 for RPi2/3.
// Virtual addresses
// These are the addresses that a program sees and can read/write to.
// Addresses 0x00000000 through 0xBFFFFFFF are the addresses available
// to a program running in user space.
// Addresses 0xC0000000 and above are available only to the kernel.
// The peripherals start at address 0xF2000000 in virtual space but
// this range is only accessible by the kernel. The kernel could directly
// access peripherals from virtual addresses. It is not clear to me my
// a user space application running as 'root' does not have access to this
// memory range.
// Bus addresses
// This is a different (virtual?) address space that also maps onto
// physical memory.
// The peripherals start at address 0x7E000000 of the bus address space.
// The DRAM is also available in bus address space in 4 different locations:
// 0x00000000 "L1 and L2 cached alias"
// 0x40000000 "L2 cache coherent (non allocating)"
// 0x80000000 "L2 cache (only)"
// 0xC0000000 "Direct, uncached access"
//
// Accessing peripherals from user space (virtual addresses):
// The technique used in this program is that mmap is used to map portions of
// /dev/mem to an arbitrary virtual address. For example, to access the
// GPIO's, the gpio range of addresses in /dev/mem (physical addresses) are
// mapped to a kernel chosen virtual address. After the mapping has been
// set up, writing to the kernel chosen virtual address will actually
// write to the GPIO addresses in physical memory.
//
// Accessing RAM from DMA engine
// The DMA engine is programmed by accessing the peripheral registers but
// must use bus addresses to access memory. Thus, to use the DMA engine to
// move memory from one virtual address to another virtual address, one needs
// to first find the physical addresses that corresponds to the virtual
// addresses. Then, one needs to find the bus addresses that corresponds to
// those physical addresses. Finally, the DMA engine can be programmed. i.e.
// DMA engine access should use addresses starting with 0xC.
//
// The perhipherals in the Broadcom documentation are described using their bus
// addresses and structures are created and calculations performed in this
// program to figure out how to access them with virtual addresses.
#define ABORT(a) exit(a)
// Used for debugging
#define MARK \
std::cout << "Currently in file: " << __FILE__ << " line: " << __LINE__ \
<< std::endl
// PLLD clock frequency.
// For RPi1, after NTP converges, these is a 2.5 PPM difference between
// the PPM correction reported by NTP and the actual frequency offset of
// the crystal. This 2.5 PPM offset is not present in the RPi2 and RPi3.
// This 2.5 PPM offset is compensated for here, but only for the RPi1.
#ifdef RPI23
#define F_PLLD_CLK (500000000.0)
#else
#ifdef RPI1
#define F_PLLD_CLK (500000000.0 * (1 - 2.500e-6))
#else
#error "RPI version macro is not defined"
#endif
#endif
// Empirical value for F_PWM_CLK that produces WSPR symbols that are 'close' to
// 0.682s long. For some reason, despite the use of DMA, the load on the PI
// affects the TX length of the symbols. However, the varying symbol length is
// compensated for in the main loop.
#define F_PWM_CLK_INIT (31156186.6125761)
// WSRP nominal symbol time
#define WSPR_SYMTIME (8192.0 / 12000.0)
// How much random frequency offset should be added to WSPR transmissions
// if the --offset option has been turned on.
#define WSPR_RAND_OFFSET 80
#define WSPR15_RAND_OFFSET 8
// Choose proper base address depending on RPI1/RPI23 macro from makefile.
// PERI_BASE_PHYS is the base address of the peripherals, in physical
// address space.
#ifdef RPI23
#define PERI_BASE_PHYS 0x3f000000
#define MEM_FLAG 0x04
#else
#ifdef RPI1
#define PERI_BASE_PHYS 0x20000000
#define MEM_FLAG 0x0c
#else
#error "RPI version macro is not defined"
#endif
#endif
#define PAGE_SIZE (4 * 1024)
#define BLOCK_SIZE (4 * 1024)
// peri_base_virt is the base virtual address that a userspace program (this
// program) can use to read/write to the the physical addresses controlling
// the peripherals. This address is mapped at runtime using mmap and /dev/mem.
// This must be declared global so that it can be called by the atexit
// function.
volatile unsigned *peri_base_virt = nullptr;
// Given an address in the bus address space of the peripherals, this
// macro calculates the appropriate virtual address to use to access
// the requested bus address space. It does this by first subtracting
// 0x7e000000 from the supplied bus address to calculate the offset into
// the peripheral address space. Then, this offset is added to peri_base_virt
// Which is the base address of the peripherals, in virtual address space.
#define ACCESS_BUS_ADDR(buss_addr) \
*(volatile int *)((long int)peri_base_virt + (buss_addr)-0x7e000000)
// Given a bus address in the peripheral address space, set or clear a bit.
#define SETBIT_BUS_ADDR(base, bit) ACCESS_BUS_ADDR(base) |= 1 << bit
#define CLRBIT_BUS_ADDR(base, bit) ACCESS_BUS_ADDR(base) &= ~(1 << (bit))
// The following are all bus addresses.
#define GPIO_BUS_BASE (0x7E200000)
#define CM_GP0CTL_BUS (0x7e101070)
#define CM_GP0DIV_BUS (0x7e101074)
#define PADS_GPIO_0_27_BUS (0x7e10002c)
#define CLK_BUS_BASE (0x7E101000)
#define DMA_BUS_BASE (0x7E007000)
#define PWM_BUS_BASE (0x7e20C000) /* PWM controller */
// Convert from a bus address to a physical address.
#define BUS_TO_PHYS(x) ((x) & ~0xC0000000)
typedef enum { WSPR, TONE } mode_type;
// Structure used to control clock generator
struct GPCTL {
char SRC : 4;
char ENAB : 1;
char KILL : 1;
char : 1;
char BUSY : 1;
char FLIP : 1;
char MASH : 2;
unsigned int : 13;
char PASSWD : 8;
};
// Structure used to tell the DMA engine what to do
struct CB {
volatile unsigned int TI;
volatile unsigned int SOURCE_AD;
volatile unsigned int DEST_AD;
volatile unsigned int TXFR_LEN;
volatile unsigned int STRIDE;
volatile unsigned int NEXTCONBK;
volatile unsigned int RES1;
volatile unsigned int RES2;
};
// DMA engine status registers
struct DMAregs {
volatile unsigned int CS;
volatile unsigned int CONBLK_AD;
volatile unsigned int TI;
volatile unsigned int SOURCE_AD;
volatile unsigned int DEST_AD;
volatile unsigned int TXFR_LEN;
volatile unsigned int STRIDE;
volatile unsigned int NEXTCONBK;
volatile unsigned int DEBUG;
};
// Virtual and bus addresses of a page of physical memory.
struct PageInfo {
void *b; // bus address
void *v; // virtual address
};
// Must be global so that exit handlers can access this.
static struct {
int handle; /* From mbox_open() */
unsigned mem_ref = 0; /* From mem_alloc() */
unsigned bus_addr; /* From mem_lock() */
unsigned char *virt_addr = nullptr;
/* From mapmem() */ // ha7ilm: originally uint8_t
unsigned pool_size;
unsigned pool_cnt;
} mbox;
// Use the mbox interface to allocate a single chunk of memory to hold
// all the pages we will need. The bus address and the virtual address
// are saved in the mbox structure.
void allocMemPool(unsigned numpages) {
// Allocate space.
mbox.mem_ref = mem_alloc(mbox.handle, 4096 * numpages, 4096, MEM_FLAG);
// Lock down the allocated space and return its bus address.
mbox.bus_addr = mem_lock(mbox.handle, mbox.mem_ref);
// Conert the bus address to a physical address and map this to virtual
// (aka user) space.
mbox.virt_addr =
(unsigned char *)mapmem(BUS_TO_PHYS(mbox.bus_addr), 4096 * numpages);
// The number of pages in the pool. Never changes!
mbox.pool_size = numpages;
// How many of the created pages have actually been used.
mbox.pool_cnt = 0;
// printf("allocMemoryPool bus_addr=%x virt_addr=%x
// mem_ref=%x\n",mbox.bus_addr,(unsigned)mbox.virt_addr,mbox.mem_ref);
}
// Returns the virtual and bus address (NOT physical address!) of another
// page in the pool.
void getRealMemPageFromPool(void **vAddr, void **bAddr) {
if (mbox.pool_cnt >= mbox.pool_size) {
std::cerr << "Error: unable to allocated more pages!" << std::endl;
ABORT(-1);
}
unsigned offset = mbox.pool_cnt * 4096;
*vAddr = (void *)(((unsigned)mbox.virt_addr) + offset);
*bAddr = (void *)(((unsigned)mbox.bus_addr) + offset);
// printf("getRealMemoryPageFromPool bus_addr=%x virt_addr=%x\n",
// (unsigned)*pAddr,(unsigned)*vAddr);
mbox.pool_cnt++;
}
// Free the memory pool
void deallocMemPool() {
if (mbox.virt_addr != nullptr) {
unmapmem(mbox.virt_addr, mbox.pool_size * 4096);
}
if (mbox.mem_ref != 0) {
mem_unlock(mbox.handle, mbox.mem_ref);
mem_free(mbox.handle, mbox.mem_ref);
}
}
// Disable the PWM clock and wait for it to become 'not busy'.
void disable_clock() {
// Check if mapping has been set up yet.
if (peri_base_virt == nullptr) {
return;
}
// Disable the clock (in case it's already running) by reading current
// settings and only clearing the enable bit.
auto settings = ACCESS_BUS_ADDR(CM_GP0CTL_BUS);
// Clear enable bit and add password
settings = (settings & 0x7EF) | 0x5A000000;
// Disable
ACCESS_BUS_ADDR(CM_GP0CTL_BUS) = *((int *)&settings);
// Wait for clock to not be busy.
while (true) {
if ((ACCESS_BUS_ADDR(CM_GP0CTL_BUS) & (1 << 7)) == 0) {
break;
}
}
}
// Turn on TX
void txon() {
// Set function select for GPIO4.
// Fsel 000 => input
// Fsel 001 => output
// Fsel 100 => alternate function 0
// Fsel 101 => alternate function 1
// Fsel 110 => alternate function 2
// Fsel 111 => alternate function 3
// Fsel 011 => alternate function 4
// Fsel 010 => alternate function 5
// Function select for GPIO is configured as 'b100 which selects
// alternate function 0 for GPIO4. Alternate function 0 is GPCLK0.
// See section 6.2 of Arm Peripherals Manual.
SETBIT_BUS_ADDR(GPIO_BUS_BASE, 14);
CLRBIT_BUS_ADDR(GPIO_BUS_BASE, 13);
CLRBIT_BUS_ADDR(GPIO_BUS_BASE, 12);
// Set GPIO drive strength, more info:
// http://www.scribd.com/doc/101830961/GPIO-Pads-Control2
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 0; //2mA -3.4dBm
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 1; //4mA +2.1dBm
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 2; //6mA +4.9dBm
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 3; //8mA
// +6.6dBm(default)
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 4; //10mA +8.2dBm
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 5; //12mA +9.2dBm
// ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 6; //14mA +10.0dBm
ACCESS_BUS_ADDR(PADS_GPIO_0_27_BUS) = 0x5a000018 + 7; // 16mA +10.6dBm
disable_clock();
// Set clock source as PLLD.
struct GPCTL setupword = {6 /*SRC*/, 0, 0, 0, 0, 3, 0x5a};
// Enable clock.
setupword = {6 /*SRC*/, 1, 0, 0, 0, 3, 0x5a};
ACCESS_BUS_ADDR(CM_GP0CTL_BUS) = *((int *)&setupword);
}
// Turn transmitter on
void txoff() {
// struct GPCTL setupword = {6/*SRC*/, 0, 0, 0, 0, 1,0x5a};
// ACCESS_BUS_ADDR(CM_GP0CTL_BUS) = *((int*)&setupword);
disable_clock();
}
// Transmit symbol sym for tsym seconds.
//
// TODO:
// Upon entering this function at the beginning of a WSPR transmission, we
// do not know which DMA table entry is being processed by the DMA engine.
#define PWM_CLOCKS_PER_ITER_NOMINAL 1000
void txSym(const int &sym_num, const double ¢er_freq,
const double &tone_spacing, const double &tsym,
const std::vector<double> &dma_table_freq, const double &f_pwm_clk,
struct PageInfo instrs[], struct PageInfo &constPage, int &bufPtr) {
const int f0_idx = sym_num * 2;
const int f1_idx = f0_idx + 1;
const double f0_freq = dma_table_freq[f0_idx];
const double f1_freq = dma_table_freq[f1_idx];
const double tone_freq =
center_freq - 1.5 * tone_spacing + sym_num * tone_spacing;
// Double check...
assert((tone_freq >= f0_freq) && (tone_freq <= f1_freq));
const double f0_ratio = 1.0 - (tone_freq - f0_freq) / (f1_freq - f0_freq);
// cout << "f0_ratio = " << f0_ratio << std::endl;
assert((f0_ratio >= 0) && (f0_ratio <= 1));
const long int n_pwmclk_per_sym = round(f_pwm_clk * tsym);
long int n_pwmclk_transmitted = 0;
long int n_f0_transmitted = 0;
// printf("<instrs[bufPtr] begin=%x>",(unsigned)&instrs[bufPtr]);
while (n_pwmclk_transmitted < n_pwmclk_per_sym) {
// Number of PWM clocks for this iteration
long int n_pwmclk = PWM_CLOCKS_PER_ITER_NOMINAL;
// Iterations may produce spurs around the main peak based on the iteration
// frequency. Randomize the iteration period so as to spread this peak
// around.
n_pwmclk += round((rand() / ((double)RAND_MAX + 1.0) - .5) * n_pwmclk) * 1;
if (n_pwmclk_transmitted + n_pwmclk > n_pwmclk_per_sym) {
n_pwmclk = n_pwmclk_per_sym - n_pwmclk_transmitted;
}
// Calculate number of clocks to transmit f0 during this iteration so
// that the long term average is as close to f0_ratio as possible.
const long int n_f0 =
round(f0_ratio * (n_pwmclk_transmitted + n_pwmclk)) - n_f0_transmitted;
const long int n_f1 = n_pwmclk - n_f0;
// Configure the transmission for this iteration
// Set GPIO pin to transmit f0
bufPtr++;
while (ACCESS_BUS_ADDR(DMA_BUS_BASE + 0x04 /* CurBlock*/) ==
(long int)(instrs[bufPtr].b)) {
usleep(100);
}
((struct CB *)(instrs[bufPtr].v))->SOURCE_AD =
(long int)constPage.b + f0_idx * 4;
// Wait for n_f0 PWM clocks
bufPtr++;
while (ACCESS_BUS_ADDR(DMA_BUS_BASE + 0x04 /* CurBlock*/) ==
(long int)(instrs[bufPtr].b)) {
usleep(100);
}
((struct CB *)(instrs[bufPtr].v))->TXFR_LEN = n_f0;
// Set GPIO pin to transmit f1
bufPtr++;
while (ACCESS_BUS_ADDR(DMA_BUS_BASE + 0x04 /* CurBlock*/) ==
(long int)(instrs[bufPtr].b)) {
usleep(100);
}
((struct CB *)(instrs[bufPtr].v))->SOURCE_AD =
(long int)constPage.b + f1_idx * 4;
// Wait for n_f1 PWM clocks
bufPtr = (bufPtr + 1) % (1024);
while (ACCESS_BUS_ADDR(DMA_BUS_BASE + 0x04 /* CurBlock*/) ==
(long int)(instrs[bufPtr].b)) {
usleep(100);
}
((struct CB *)(instrs[bufPtr].v))->TXFR_LEN = n_f1;
// Update counters
n_pwmclk_transmitted += n_pwmclk;
n_f0_transmitted += n_f0;
}
// printf("<instrs[bufPtr]=%x
// %x>",(unsigned)instrs[bufPtr].v,(unsigned)instrs[bufPtr].b);
}
// Turn off (reset) DMA engine
void unSetupDMA() {
// Check if mapping has been set up yet.
if (peri_base_virt == nullptr) {
return;
}
// cout << "Exiting!" << std::endl;
struct DMAregs *DMA0 = (struct DMAregs *)&(ACCESS_BUS_ADDR(DMA_BUS_BASE));
DMA0->CS = 1 << 31; // reset dma controller
txoff();
}
// Truncate at bit lsb. i.e. set all bits less than lsb to zero.
double bit_trunc(const double &d, const int &lsb) {
return floor(d / pow(2.0, lsb)) * pow(2.0, lsb);
}
// Program the tuning words into the DMA table.
void setupDMATab(const double ¢er_freq_desired, const double &tone_spacing,
const double &plld_actual_freq,
std::vector<double> &dma_table_freq,
double ¢er_freq_actual, struct PageInfo &constPage) {
// Make sure that all the WSPR tones can be produced solely by
// varying the fractional part of the frequency divider.
center_freq_actual = center_freq_desired;
double div_lo =
bit_trunc(plld_actual_freq / (center_freq_desired - 1.5 * tone_spacing),
-12) +
pow(2.0, -12);
double div_hi = bit_trunc(
plld_actual_freq / (center_freq_desired + 1.5 * tone_spacing), -12);
if (floor(div_lo) != floor(div_hi)) {
center_freq_actual = plld_actual_freq / floor(div_lo) - 1.6 * tone_spacing;
std::stringstream temp;
temp << std::setprecision(6) << std::fixed
<< " Warning: center frequency has been changed to "
<< center_freq_actual / 1e6 << " MHz" << std::endl;
std::cout << temp.str();
std::cout << " because of hardware limitations!" << std::endl;
}
// Create DMA table of tuning words. WSPR tone i will use entries 2*i and
// 2*i+1 to generate the appropriate tone.
double tone0_freq = center_freq_actual - 1.5 * tone_spacing;
std::vector<long int> tuning_word(1024);
for (int i = 0; i < 8; i++) {
double tone_freq = tone0_freq + (i >> 1) * tone_spacing;
double div = bit_trunc(plld_actual_freq / tone_freq, -12);
if (i % 2 == 0) {
div = div + pow(2.0, -12);
}
tuning_word[i] = ((int)(div * pow(2.0, 12)));
}
// Fill the remaining table, just in case...
for (int i = 8; i < 1024; i++) {
double div = 500 + i;
tuning_word[i] = ((int)(div * pow(2.0, 12)));
}
// Program the table
dma_table_freq.resize(1024);
for (int i = 0; i < 1024; i++) {
dma_table_freq[i] = plld_actual_freq / (tuning_word[i] / pow(2.0, 12));
((int *)(constPage.v))[i] = (0x5a << 24) + tuning_word[i];
if ((i % 2 == 0) && (i < 8)) {
assert((tuning_word[i] & (~0xfff)) == (tuning_word[i + 1] & (~0xfff)));
}
}
}
// Create the memory structures needed by the DMA engine and perform initial
// clock configuration.
void setupDMA(struct PageInfo &constPage, struct PageInfo &instrPage,
struct PageInfo instrs[]) {
allocMemPool(1025);
// Allocate a page of ram for the constants
getRealMemPageFromPool(&constPage.v, &constPage.b);
// Create 1024 instructions allocating one page at a time.
// Even instructions target the GP0 Clock divider
// Odd instructions target the PWM FIFO
int instrCnt = 0;
while (instrCnt < 1024) {
// Allocate a page of ram for the instructions
getRealMemPageFromPool(&instrPage.v, &instrPage.b);
// make copy instructions
// Only create as many instructions as will fit in the recently
// allocated page. If not enough space for all instructions, the
// next loop will allocate another page.
struct CB *instr0 = (struct CB *)instrPage.v;
int i;
for (i = 0; i < (signed)(4096 / sizeof(struct CB)); i++) {
instrs[instrCnt].v =
(void *)((long int)instrPage.v + sizeof(struct CB) * i);
instrs[instrCnt].b =
(void *)((long int)instrPage.b + sizeof(struct CB) * i);
instr0->SOURCE_AD = (unsigned long int)constPage.b + 2048;
instr0->DEST_AD = PWM_BUS_BASE + 0x18 /* FIF1 */;
instr0->TXFR_LEN = 4;
instr0->STRIDE = 0;
// instr0->NEXTCONBK = (int)instrPage.b + sizeof(struct CB)*(i+1);
instr0->TI =
(1 /* DREQ */ << 6) | (5 /* PWM */ << 16) | (1 << 26 /* no wide*/);
instr0->RES1 = 0;
instr0->RES2 = 0;
// Shouldn't this be (instrCnt%2) ???
if ((i % 2) != 0) {
instr0->DEST_AD = CM_GP0DIV_BUS;
instr0->STRIDE = 4;
instr0->TI = (1 << 26 /* no wide*/);
}
if (instrCnt != 0) {
((struct CB *)(instrs[instrCnt - 1].v))->NEXTCONBK =
(long int)instrs[instrCnt].b;
}
instr0++;
instrCnt++;
}
}
// Create a circular linked list of instructions
((struct CB *)(instrs[1023].v))->NEXTCONBK = (long int)instrs[0].b;
// set up a clock for the PWM
ACCESS_BUS_ADDR(CLK_BUS_BASE + 40 * 4 /*PWMCLK_CNTL*/) =
0x5A000026; // Source=PLLD and disable
usleep(1000);
// ACCESS_BUS_ADDR(CLK_BUS_BASE + 41*4 /*PWMCLK_DIV*/) = 0x5A002800;
ACCESS_BUS_ADDR(CLK_BUS_BASE + 41 * 4 /*PWMCLK_DIV*/) =
0x5A002000; // set PWM div to 2, for 250MHz
ACCESS_BUS_ADDR(CLK_BUS_BASE + 40 * 4 /*PWMCLK_CNTL*/) =
0x5A000016; // Source=PLLD and enable
usleep(1000);
// set up pwm
ACCESS_BUS_ADDR(PWM_BUS_BASE + 0x0 /* CTRL*/) = 0;
usleep(1000);
ACCESS_BUS_ADDR(PWM_BUS_BASE + 0x4 /* status*/) = -1; // clear errors
usleep(1000);
// Range should default to 32, but it is set at 2048 after reset on my RPi.
ACCESS_BUS_ADDR(PWM_BUS_BASE + 0x10) = 32;
ACCESS_BUS_ADDR(PWM_BUS_BASE + 0x20) = 32;
ACCESS_BUS_ADDR(PWM_BUS_BASE + 0x0 /* CTRL*/) =
-1; //(1<<13 /* Use fifo */) | (1<<10 /* repeat */) | (1<<9 /* serializer
//*/) | (1<<8 /* enable ch */) ;
usleep(1000);
ACCESS_BUS_ADDR(PWM_BUS_BASE + 0x8 /* DMAC*/) =
(1 << 31 /* DMA enable */) | 0x0707;
// activate dma
struct DMAregs *DMA0 = (struct DMAregs *)&(ACCESS_BUS_ADDR(DMA_BUS_BASE));
DMA0->CS = 1 << 31; // reset
DMA0->CONBLK_AD = 0;
DMA0->TI = 0;
DMA0->CONBLK_AD = (unsigned long int)(instrPage.b);
DMA0->CS =
(1 << 0) | (255 << 16); // enable bit = 0, clear end flag = 1, prio=19-16
}
// Encode call, locator, and dBm into WSPR codeblock.
// Assumes that both callsign and locator are uppercase. This is done in
// parse_commandline(), but needs to be ensured if calling this function
// manually.
void wspr(const char *call, const char *l_pre,
const int dbm, // EIRP in
// dBm={0,3,7,10,13,17,20,23,27,30,33,37,40,43,47,50,53,57,60}
unsigned char *symbols) {
// pack 'prefix' in nadd, 'call' in n1, and 'grid' and 'dbm' in n2
char *c, buf[17];
strncpy(buf, call, 16);
buf[16] = '\0';
c = buf;
unsigned long ng = 0, ih = 0, nadd = 0;
unsigned long n1, n2;
if (strnlen(l_pre, 6) == 6) {
// When sending a 6 character grid, the callsign is hashed, then the grid
// wrapped around one character and used as the callsign.
ih = nhash(c, strnlen(c, 16), 146) & 0x7fff; // 15 bit mask
c[0] = l_pre[1];
c[1] = l_pre[2];
c[2] = l_pre[3];
c[3] = l_pre[4];
c[4] = l_pre[5];
c[5] = l_pre[0];
c[6] = '\0';
}
if (strchr(c, '/') != nullptr) { // prefix-suffix
nadd = 2;
int i = strchr(c, '/') - c; // stroke position
int n = strlen(c) - i - 1; // suffix len, prefix-call len
c[i] = '\0';
if (n == 1) {
ng = 60000 - 32768 +
(c[i + 1] >= '0' && c[i + 1] <= '9'
? c[i + 1] - '0'
: c[i + 1] == ' ' ? 38 : c[i + 1] - 'A' +
10); // suffix /A to /Z, /0 to /9
}
if (n == 2) {
ng = 60000 + 26 + 10 * (c[i + 1] - '0') +
(c[i + 2] - '0'); // suffix /10 to /99
}
if (n > 2) { // prefix EA8/, right align
ng = (i < 3 ? 36 : c[i - 3] >= '0' && c[i - 3] <= '9'
? c[i - 3] - '0'
: c[i - 3] - 'A' + 10);
ng = 37 * ng + (i < 2 ? 36 : c[i - 2] >= '0' && c[i - 2] <= '9'
? c[i - 2] - '0'
: c[i - 2] - 'A' + 10);
ng = 37 * ng + (i < 1 ? 36 : c[i - 1] >= '0' && c[i - 1] <= '9'
? c[i - 1] - '0'
: c[i - 1] - 'A' + 10);
if (ng < 32768) {
nadd = 1;
} else {
ng = ng - 32768;
}
c = c + i + 1;
}
}
int i =
(isdigit(c[2]) != 0
? 2
: isdigit(c[1]) != 0
? 1
: 0); // last prefix digit of de-suffixed/de-prefixed callsign
int n = strlen(c) - i - 1; // 2nd part of call len
n1 = (i < 2 ? 36 : c[i - 2] >= '0' && c[i - 2] <= '9' ? c[i - 2] - '0'
: c[i - 2] - 'A' + 10);
n1 = 36 * n1 + (i < 1 ? 36 : c[i - 1] >= '0' && c[i - 1] <= '9'
? c[i - 1] - '0'
: c[i - 1] - 'A' + 10);
n1 = 10 * n1 + c[i] - '0';
n1 = 27 * n1 + (n < 1 ? 26 : c[i + 1] - 'A');
n1 = 27 * n1 + (n < 2 ? 26 : c[i + 2] - 'A');
n1 = 27 * n1 + (n < 3 ? 26 : c[i + 3] - 'A');
if ((nadd == 0u) && strnlen(l_pre, 6) == 4) {
// Encode the 4 character location
ng = 180 * (179 - 10 * (l_pre[0] - 'A') - (l_pre[2] - '0')) +
10 * (l_pre[1] - 'A') + (l_pre[3] - '0');
}
int corr[] = {0, -1, 1, 0, -1, 2, 1, 0, -1, 1};
int p = dbm > 60 ? 60 : dbm < 0 ? 0 : dbm + corr[dbm % 10];
if (strnlen(l_pre, 6) == 4) {
n2 = (ng << 7) | (p + 64 + nadd);
} else {
n2 = (ih << 7) | (-(p + 1) + 64);
}
// pack n1,n2,zero-tail into 50 bits
char packed[11] = {
static_cast<char>(n1 >> 20),
static_cast<char>(n1 >> 12),
static_cast<char>(n1 >> 4),
static_cast<char>(((n1 & 0x0f) << 4) | ((n2 >> 18) & 0x0f)),
static_cast<char>(n2 >> 10),
static_cast<char>(n2 >> 2),
static_cast<char>((n2 & 0x03) << 6),
0,
0,
0,
0};
// convolutional encoding K=32, r=1/2, Layland-Lushbaugh polynomials
int k = 0;
int j, s;
int nstate = 0;
unsigned char symbol[176];
for (j = 0; j != sizeof(packed); j++) {
for (i = 7; i >= 0; i--) {
unsigned long poly[2] = {0xf2d05351L, 0xe4613c47L};
nstate = (nstate << 1) | ((packed[j] >> i) & 1);
for (s = 0; s != 2; s++) { // convolve
unsigned long n = nstate & poly[s];
int even = 0; // even := parity(n)
while (n != 0u) {
even = 1 - even;
n = n & (n - 1);
}
symbol[k] = even;
k++;
}
}
}
// interleave symbols
const unsigned char sync_symbols[162] = {
1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1,
1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,
1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0,
0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1,
0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0};
for (i = 0; i != 162; i++) {
// j0 := bit reversed_values_smaller_than_161[i]
unsigned char j0;
p = -1;
for (k = 0; p != i; k++) {
for (j = 0; j != 8; j++) { // j0:=bit_reverse(k)
j0 = ((k >> j) & 1) | (j0 << 1);
}
if (j0 < 162) {
p++;
}
}
symbols[j0] = sync_symbols[j0] |
symbol[i] << 1; // interleave and add sync std::vector
}
}
// Wait for the system clock's minute to reach one second past 'minute'
void wait_every(int minute) {
time_t t;
struct tm *ptm;
for (;;) {
time(&t);
ptm = gmtime(&t);
if ((ptm->tm_min % minute) == 0 && ptm->tm_sec == 0) {
break;
}
usleep(1000);
}
usleep(1000000); // wait another second
}
void print_usage() {
std::cout << "Usage:" << std::endl;
std::cout << " wspr [options] callsign locator tx_pwr_dBm f1 <f2> <f3> ..."
<< std::endl;
std::cout << " OR" << std::endl;
std::cout << " wspr [options] --test-tone f" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -h --help" << std::endl;
std::cout << " Print out this help screen." << std::endl;
std::cout << " -p --ppm ppm" << std::endl;
std::cout
<< " Known PPM correction to 19.2MHz RPi nominal crystal frequency."
<< std::endl;
std::cout << " -s --self-calibration" << std::endl;
std::cout << " Check NTP before every transmission to obtain the PPM "
"error of the"
<< std::endl;
std::cout << " crystal (default setting!)." << std::endl;
std::cout << " -f --free-running" << std::endl;
std::cout << " Do not use NTP to correct frequency error of RPi crystal."
<< std::endl;
std::cout << " -r --repeat" << std::endl;
std::cout << " Repeatedly, and in order, transmit on all the specified "
"command line freqs."
<< std::endl;
std::cout << " -x --terminate <n>" << std::endl;
std::cout << " Terminate after n transmissions have been completed."
<< std::endl;
std::cout << " -o --offset" << std::endl;
std::cout << " Add a random frequency offset to each transmission:"
<< std::endl;
std::cout << " +/- " << WSPR_RAND_OFFSET << " Hz for WSPR" << std::endl;
std::cout << " +/- " << WSPR15_RAND_OFFSET << " Hz for WSPR-15"
<< std::endl;
std::cout << " -t --test-tone freq" << std::endl;
std::cout
<< " Simply output a test tone at the specified frequency. Only used"
<< std::endl;
std::cout << " for debugging and to verify calibration." << std::endl;
std::cout << " -n --no-delay" << std::endl;
std::cout
<< " Transmit immediately, do not wait for a WSPR TX window. Used"
<< std::endl;
std::cout << " for testing only." << std::endl;
std::cout << std::endl;
std::cout << "Frequencies can be specified either as an absolute TX carrier "
"frequency, or"
<< std::endl;
std::cout << "using one of the following strings. If a string is used, the "
"transmission"
<< std::endl;
std::cout
<< "will happen in the middle of the WSPR region of the selected band."
<< std::endl;
std::cout << " LF LF-15 MF MF-15 160m 160m-15 80m 60m 40m 30m 20m 17m 15m "
"12m 10m 6m 4m 2m"
<< std::endl;
std::cout << "<B>-15 indicates the WSPR-15 region of band <B>." << std::endl;
std::cout << std::endl;
std::cout
<< "Transmission gaps can be created by specifying a TX frequency of 0"
<< std::endl;
std::cout << std::endl;
std::cout << "This program supports both 4 and 6 character Maidenhead grid "
"locators."
<< std::endl;
}
void parse_commandline(
// Inputs
const int &argc, char *const argv[],
// Outputs
std::string &callsign, std::string &locator, int &tx_power,
std::vector<double> ¢er_freq_set, double &ppm, bool &self_cal,
bool &repeat, bool &random_offset, double &test_tone, bool &no_delay,
mode_type &mode, int &terminate) {
// Default values
tx_power = -1;
ppm = 0;
self_cal = true;
repeat = false;
random_offset = false;
test_tone = NAN;
no_delay = false;
mode = WSPR;
terminate = -1;
static struct option long_options[] = {
{"help", no_argument, nullptr, 'h'},
{"ppm", required_argument, nullptr, 'p'},
{"self-calibration", no_argument, nullptr, 's'},
{"free-running", no_argument, nullptr, 'f'},
{"repeat", no_argument, nullptr, 'r'},
{"terminate", required_argument, nullptr, 'x'},
{"offset", no_argument, nullptr, 'o'},
{"test-tone", required_argument, nullptr, 't'},
{"no-delay", no_argument, nullptr, 'n'},
{nullptr, 0, nullptr, 0}};
while (true) {
/* getopt_long stores the option index here. */
int option_index = 0;
int c =
getopt_long(argc, argv, "hp:sfrx:ot:n", long_options, &option_index);
if (c == -1) {
break;
}
switch (c) {
char *endp;
case 0:
// Code should only get here if a long option was given a non-null
// flag value.
std::cout << "Check code!" << std::endl;
ABORT(-1);
break;
case 'h':
print_usage();
ABORT(-1);
break;
case 'p':
ppm = strtod(optarg, &endp);
if ((optarg == endp) || (*endp != '\0')) {
std::cerr << "Error: could not parse ppm value" << std::endl;
ABORT(-1);
}
break;
case 's':
self_cal = true;
break;
case 'f':
self_cal = false;
break;
case 'r':
repeat = true;
break;
case 'x':
terminate = strtol(optarg, &endp, 10);
if ((optarg == endp) || (*endp != '\0')) {
std::cerr << "Error: could not parse termination argument" << std::endl;
ABORT(-1);
}
if (terminate < 1) {
std::cerr << "Error: termination parameter must be >= 1" << std::endl;
ABORT(-1);
}
break;
case 'o':
random_offset = true;
break;
case 't':
test_tone = strtod(optarg, &endp);
mode = TONE;
if ((optarg == endp) || (*endp != '\0')) {
std::cerr << "Error: could not parse test tone frequency" << std::endl;
ABORT(-1);
}
break;
case 'n':
no_delay = true;
break;
case '?':
/* getopt_long already printed an error message. */
ABORT(-1);
default:
ABORT(-1);
}
}
// Parse the non-option parameters
unsigned int n_free_args = 0;
while (optind < argc) {
// Check for callsign, locator, tx_power
if (n_free_args == 0) {
callsign = argv[optind++];
n_free_args++;
continue;
}
if (n_free_args == 1) {
locator = argv[optind++];
if (locator.size() != 4 && locator.size() != 6) {
std::cerr << "Error: grid locator must be 4 or 6 characters"
<< std::endl;
ABORT(-1);
}
n_free_args++;
continue;
}
if (n_free_args == 2) {
tx_power = atoi(argv[optind++]);
n_free_args++;
continue;
}
// Must be a frequency
// First see if it is a string.
double parsed_freq;
if (strcasecmp(argv[optind], "LF") == 0) {
parsed_freq = 137500.0;
} else if (strcasecmp(argv[optind], "LF-15") == 0) {
parsed_freq = 137612.5;
} else if (strcasecmp(argv[optind], "MF") == 0) {
parsed_freq = 475700.0;
} else if (strcasecmp(argv[optind], "MF-15") == 0) {
parsed_freq = 475812.5;
} else if (strcasecmp(argv[optind], "160m") == 0) {
parsed_freq = 1838100.0;
} else if (strcasecmp(argv[optind], "160m-15") == 0) {
parsed_freq = 1838212.5;
} else if (strcasecmp(argv[optind], "80m") == 0) {
parsed_freq = 3594100.0;
} else if (strcasecmp(argv[optind], "60m") == 0) {
parsed_freq = 5288700.0;
} else if (strcasecmp(argv[optind], "40m") == 0) {
parsed_freq = 7040100.0;
} else if (strcasecmp(argv[optind], "30m") == 0) {
parsed_freq = 10140200.0;
} else if (strcasecmp(argv[optind], "20m") == 0) {
parsed_freq = 14097100.0;
} else if (strcasecmp(argv[optind], "17m") == 0) {
parsed_freq = 18106100.0;
} else if (strcasecmp(argv[optind], "15m") == 0) {
parsed_freq = 21096100.0;
} else if (strcasecmp(argv[optind], "12m") == 0) {