mirror of
https://github.com/cnlohr/lolra.git
synced 2026-06-21 18:29:28 +00:00
Compare commits
87 Commits
200d271c0a
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 3bb8c87519 | |||
| 77cfc9f3b7 | |||
| ae63b4208f | |||
| 1940782c3d | |||
| e5cd85ebf8 | |||
| 7f57e4b003 | |||
| 966076d5ed | |||
| ce7b9c05d1 | |||
| c7900d08b0 | |||
| 7f0f6ecb67 | |||
| 58aae1becd | |||
| 56ac27833b | |||
| 22c2149507 | |||
| e3ed2e9084 | |||
| 73a80f4099 | |||
| 0033874cab | |||
| 21a585236d | |||
| 710a07d913 | |||
| ac768babae | |||
| 1115329d6b | |||
| ccf9c1305b | |||
| 2cb413d827 | |||
| fc83ea3c40 | |||
| a08fdc845b | |||
| f6b5dfe68d | |||
| a65de155c0 | |||
| 9239f43759 | |||
| c1bdfe0acf | |||
| 147fdc514d | |||
| 933a3d4347 | |||
| 4c84e5e538 | |||
| 01216baaf9 | |||
| 9044689537 | |||
| 529e85e066 | |||
| b2995f435f | |||
| 85fe805e32 | |||
| 6802a917ae | |||
| 39dbd6df19 | |||
| 591065938d | |||
| 0273cb8d94 | |||
| be82329774 | |||
| 2843e226a9 | |||
| 4574e87120 | |||
| ec9206346e | |||
| 84b7b478c0 | |||
| 64c8253055 | |||
| 7f3ebcc732 | |||
| e9f97f7757 | |||
| 8cf6fa53a9 | |||
| 0379e7cb30 | |||
| 5028657d02 | |||
| 21e6aab95c | |||
| 6c7adbdcc2 | |||
| edede9d517 | |||
| e0d41ca056 | |||
| d206128b38 | |||
| 0a6e76034f | |||
| 4fe9638062 | |||
| 0f71fdafe0 | |||
| a8ab17013f | |||
| 41ec379ad6 | |||
| e0db86d513 | |||
| 26d8facf2c | |||
| 25dc0234c0 | |||
| 2b75c51cd9 | |||
| 9f0cc2c50d | |||
| 5067970ec3 | |||
| 64335ae653 | |||
| 7052e8c111 | |||
| 70caf8b76a | |||
| 17b7d3fdcb | |||
| 9bbca912a0 | |||
| 696701ffb7 | |||
| f31cb4595d | |||
| ae273dbcce | |||
| 298035f8eb | |||
| 31809a0a78 | |||
| 3a4e1bfda8 | |||
| 956ac4a0c2 | |||
| d5d9de86bd | |||
| a9b780daea | |||
| d5dbc3a7c0 | |||
| 53a4ac1115 | |||
| 0872256b3c | |||
| d17b0ee51e | |||
| dc1d3d1d2c | |||
| 6948175113 |
@@ -1,25 +1,73 @@
|
||||
# LoLRa
|
||||
|
||||
*Transmit 900MHz LoRa frames surprisingly far without a radio*
|
||||
Transmit 900MHz LoRa frames surprisingly far without a radio (And other radio shenanigans using ADCs, PWMs and I2S/SPI busses) including sending other RF data, as well as receiving RF signals (Though admittedly not a LoRa receiver).
|
||||
|
||||
* [Introduction](#introduction)
|
||||
* [Background](#background)
|
||||
* [LoRaWAN](#lorawan)
|
||||
* [Limitations](#limitations)
|
||||
* [Future Work](#future_Work)
|
||||
* [Resources](#resources)
|
||||
* [Special Thanks](#special_thanks)
|
||||
* [Range Tests](#range_tests)
|
||||
If you are looking for the Hackaday 2024 microcontroller radio talk, you can <a href=https://cnlohr.github.io/lolra_talk>click here</a>.
|
||||
|
||||
## Introduction
|
||||
If you are looking for LoLRa Merch (Like t-shirts, etc.), <a href="https://cnlohr-shop.fourthwall.com/">click here</a>.
|
||||
|
||||
Firmware-only LoRa transmission, for a variety of processors. Send LoRa packets, without any radio, chips, external hardware or built-in radios at all on a variety of common, inexpensive processors. While not truly bit banging, this repository shows how using either a shift register (i.e. I2S or SPI port) or an APLL, you can send lora packets that can be decoded by commercial off the shelf LoRa gateways and other chips.
|
||||
* [Introduct and repo overview](#introduction-and-repo-overview)
|
||||
* LoRa
|
||||
* [Introduction (LoRa)](#introduction-lora)
|
||||
* [Background](#background)
|
||||
* [LoRaWAN](#lorawan)
|
||||
* [Limitations](#limitations)
|
||||
* [Future Work](#future-work)
|
||||
* [Resources](#resources)
|
||||
* [Special Thanks](#special-thanks)
|
||||
* [Range Tests](#range-tests)
|
||||
|
||||
> [!NOTE]
|
||||
> This repo is designed for use with ITU Region 2 (The Americas) tageting 902-928MHz. Code changes are needed for use in Region 1 (EU, Russia, Afraica) to target 863-870MHz or 3 (Australia, China, India) to target 920-923MHz.
|
||||
> 1. Portions of code in this repo are under various licenses and cannot be trivially incorporated into other libraries, including some files containing a no-ai-training license for any of the RF-specific portions of the project. Be cautious when using code from this repo. See  for more information.
|
||||
> 2. The LoRa® and LoRaWAN® Mark and LoRa Logo are trademarks of Semtech Corporation.
|
||||
> 3. LoLRa is not associated with Semtech in any way whatsoever.
|
||||
> 4. This repo is designed for use with ITU Region 2 (The Americas) targeting 902-928MHz. Code changes are needed for use in Region 1 (EU, Russia, Africa) to target 863-870MHz or Region 3 (Australia, China, India) to target 920-923MHz.
|
||||
|
||||
> [!CAUTION]
|
||||
> Because we rely on harmdonics and aliasing, the primary frequency components emitted by your microcontroller are going to be in portions of the RF spectrum where RF transmissions are banned. Please filter your output or perform your tests in an area where you are unlikely to leak significant RF. The overall EIRP output is genreally ≪300uW across the whole spectrum spread out over hundreds of emission frequencies, but there is virtually no way a device deliberately transmitting on these frequencies could ever pass FCC part 15 compliance, even with filtering.
|
||||
> Because we rely on harmonics and aliasing, the primary frequency components emitted by your microcontroller are going to be in portions of the RF spectrum where RF transmissions are banned. Please filter your output or perform your tests in an area where you are unlikely to leak significant RF. The overall EIRP output is genreally ≪300uW across the whole spectrum spread out over hundreds of emission frequencies, but there is virtually no way a device deliberately transmitting on these frequencies could ever pass FCC part 15 compliance, even with filtering.
|
||||
|
||||
|
||||
## Introduction and Repo Overview
|
||||
|
||||
I have always been fascinated with sending and receiving radio signals from microcontrollers that don't have dedicated radio hardware. This repo serves as a overview of many of the projects I've done to do this decoding, along with example code (Though some of it is restrictively licensed)
|
||||
|
||||
In general the repo is split up in to many projects, but categoriezed by device type.
|
||||
|
||||
* ch32v (Note, all examples require 8MHz (v203) or 24Mhz (v003) crystal oscillator)
|
||||
* General Note: All OLED displays used here are 128x128 SPI-mode OLED displays.
|
||||
* [ch32v003-adcrx](ch32v/ch32v003-adcrx) - prints quadrature values for receiving at 1/4 sample rate signals, or harmonics thereof. Specifically this is tuned to receiv CW on citizen band frequencies, specifically 27.000050 MHz
|
||||
* [ch32v003-lora](ch32v/ch32v003-lora) - Successful (but very poor) transmission of LoRa messages with a ch32v003.
|
||||
* [ch32v003-timer](ch32v/ch32v003-timer) - An attempt to use non-tabled dithering of PWM signals to send FM radio and/or 315MHz signals. *This does not work well* but it is included as a reference for dtrying to dither RF on the 003.
|
||||
* [ch32v003-txrx](ch32v/ch32v003-txrx) - Trying to send from one 003 to another 003 receiving. This does not work well - only about 1'.
|
||||
* [ch32v203-adcrx](ch32v203-adcrx) - Very basic quadrature decoding on a ch32v203.
|
||||
* [ch32v203-fft](ch32v203-fft) - Perform an FFT on a small window of samples on a ch32v203. This outputs to an OLED display. It doesn't keep up in realtime though. It also relies on <a href=https://gist.github.com/cnlohr/c4f9647a220781c005ff1a733dc9ed7f>fix_fft.h</a> (which cannot be distirbuted with this project because of a lack of license.
|
||||
* [**ch32v203-goertzel**](ch32v/ch32v203-goertzel) - Perform a full goertzel's tuning on an incoming ADC signal so that it can listen to multiple AM and NBFM radio stations from an ADC pin.
|
||||
* [lib/calculator.html](ch32v/lib/calculator.html) - webpage that can use webhid with ch32v203-goertzel.
|
||||
* [**ch32v203-lora**](ch32v/ch32v203-lora) - Proper transmission of LoRaWAN packets (from the tests outlined below).
|
||||
* [ch32v203-tx](ch32v/ch32v203-tx) - Very basic test, setup to just turn on a PWM on the ch32v203.
|
||||
* esp32-s2
|
||||
* [**loratest**](esp32-s2/loratest) - Full stack protocol for sending LoRa messages from an esp32-s2. (From range test)
|
||||
* [**narrow_fsk_test**](esp32-s2/narrow_fsk_test) - Very basic test using dithering and the PLL in the esp32-s2 to see how tight/narrow control is possible with the esp32-s2. This does not do a dithered closed loop, but would not be terribly hard to add.
|
||||
* [**videoending**](esp32-s2/videoending) - Mechanism for allowing an ESP32-S2 to FSK, hopping around to draw a picture in a spectrogram. This was used for the video ending.
|
||||
* esp8266
|
||||
* [example_125k_raw](esp8266/example_125k_raw) - Sending a raw 125kHz wide LoRa message.
|
||||
* [example_500k_raw](esp8266/example_500k_raw) - Sending a raw 500kHz wide LoRa message.
|
||||
* [**lorawan_example**](esp8266/lorawan_example) - Using the I2S bus on the ESP8266 to send a full-stack LoRaWAN message to the things network.
|
||||
* [non_lora_310_transmit](esp8266/non_lora_310_transmit) - Exmaple of how to transmit 310MHz OOK with an ESP8266.
|
||||
* lib
|
||||
* [aes-cbc-cmac.h](lib/aes-cbc-cmac.h) - Public Domain RFC4493 AES-CMAC header only library.
|
||||
* [LoRa-SDR-Code.h](lib/LoRa-SDR-Code.h) - MIT (unrestrictive) Licensed code to construct LoRa packets
|
||||
* [lorawan_simple.h](lib/lorawan_simple.h) - MIT (unrestrictive) Licensed code to construct LoRaWAN packets.
|
||||
* [rf_data_gen.h](lib/rf_data_gen.h) - Helper function for helping generate bit tables for I2S/SPI outpiut of carefully crafted signals.
|
||||
* [tiny-AES-c.h](lib/rf_data_gen.h) - Public Domain AES encryption/decryption library.
|
||||
* tools
|
||||
* [60-rtlsdr.rules](tools/60-rtlsdr.rules) - Make it so you can use your airspy from Linux as a user.
|
||||
* [complex_magsink_to_image.c](tools/complex_magsink_to_image.c) - Generate ultra high resolution (in time domain) waterfall views.
|
||||
* [testloradec.grc](tools/testloradec.grc) - Using gr_lora exmaple to decode LoRa in GNURadio
|
||||
|
||||
## Introduction (LoRa)
|
||||
|
||||
Firmware-only LoRa transmission, for a variety of processors. Send LoRa packets, without any radio, chips, external hardware or built-in radios at all on a variety of common, inexpensive processors. While not truly bit banging, this repository shows how using either a shift register (i.e. I2S or SPI port) or an APLL, you can send LoRa packets that can be decoded by commercial off the shelf LoRa gateways and other chips.
|
||||
|
||||
There are two major modes that this repository works with.
|
||||
|
||||
@@ -31,16 +79,13 @@ Click Below for the Youtube Video version of this page:
|
||||
|
||||
[](https://www.youtube.com/watch?v=eIdHBDSQHyw)
|
||||
|
||||
> [!NOTE]
|
||||
> Portions of code in this repo are under various licenses and cannot be trivially incorporated into other libraries without a bit of a mess, including a no-ai-training license for any of the RF-specific portions of the project. Be cautious when using code from this repo. See  for more information.
|
||||
|
||||
## Background
|
||||
|
||||
### Square waves, and images
|
||||
|
||||
Any time a signal changes state from low to high or high to low, a disturbance is created in the electromagnetic fields surrounding that wire. Any time. The difference is, are you, as an engineer going to fear it, squelching it waddling, being afraid of whatever EMI it might cause, or are you going to grab the bull by its horns and emit some artesinally crafted signals? The major principles you will need to understand are:
|
||||
Any time a signal changes state from low to high or high to low, a disturbance is created in the electromagnetic fields surrounding that wire. Any time. The difference is, are you, as an engineer, going to fear it, squelching it waddling, being afraid of whatever EMI it might cause, or are you going to grab the bull by its horns and emit some artisanally crafted signals? The major principles you will need to understand are:
|
||||
|
||||
* The actual emission of a wave is made from several frequency components at different frequencies and phases.
|
||||
* The actual emission of a wave is made from several frequency components at different frequencies and phases. You can read more about it [in this wolfram article](https://mathworld.wolfram.com/FourierSeriesSquareWave.html) or [This 3Brown1Blue Video](https://www.youtube.com/watch?v=spUNpyF58BY)
|
||||
|
||||

|
||||
|
||||
@@ -68,13 +113,13 @@ The second principle is signal mixing. If you create a signal, then "mix" it wi
|
||||
|
||||

|
||||
|
||||
Now, the real magic happens, when you realize these two principles actually work together. You get an image at the base band, a reflected image around the sampling frequency, then around ×3 the sampling frequency, you get another 2 images, the forward and reverse. And ×5, and ×7, etc.
|
||||
Now the real magic happens, when you realize these two principles actually work together. You get an image at the base band, a reflected image around the sampling frequency, then around ×3 the sampling frequency, you get another 2 images, the forward and reverse. And ×5, and ×7, etc.
|
||||
|
||||
With this, with a precise enough clock, we can arbitrarily generate any frequency we wish, provided there's enough bandwidth left on the GPIO of our micro to generate it, even if the "actual" signal we're generating is much much lower in frequency.
|
||||
|
||||
#### A side-note: RC/RLC oscllators vs crystal oscillators.
|
||||
#### A side-note: RC/RLC oscillators vs crystal oscillators.
|
||||
|
||||
Internal oscillators in microcontrollers aren't only inacacurate, but they also jitter around in frequency. You might think this a negative, but in fact, using the internal oscillator built into micros can often be a lifesaver, getting you past EMI/EMC. Because the internal oscillators aren't just imprecise but jittery, they prevent harmonics of individual frequencies higher up in the spectrum because the clock rate drifts around so heavily.
|
||||
Internal oscillators in microcontrollers aren't only inaccurate, but they also jitter around in frequency. You might think this a negative, but in fact, using the internal oscillator built into micros can often be a lifesaver, getting you past EMI/EMC. Because the internal oscillators aren't just imprecise but jittery, they prevent harmonics of individual frequencies higher up in the spectrum because the clock rate drifts around so heavily.
|
||||
|
||||
Crystal Output:
|
||||

|
||||
@@ -86,24 +131,24 @@ RC Output:
|
||||
|
||||
See the section below for the nitty gritty of how LoRa signals *actually work* or the things that none of the other PhDs on the internet ever were willing to tell you about it.
|
||||
|
||||
LoRa typically can operate in 433MHz or the 900MHz spectrum, usually with 125kHz channels. In principle, LoRa creates chirps, starting at one frequency, 62.5kHz below the channel center, then over a short period of time (1.024uS at SF7) the tone creeps up to 62.5kHz above the channel center.
|
||||
LoRa typically operates in the 433MHz or the 900MHz spectrum, usually with 125kHz channels. In principle, LoRa creates chirps, starting at one frequency, 62.5kHz below the channel center, then over a short period of time (1.024uS at SF7) the tone creeps up to 62.5kHz above the channel center.
|
||||
|
||||
While LoRa can be used with many different channel widths, 125kHz and 500kHz are both very well supported, whereas other channel widths are not configurable with routers like the LR9.
|
||||
|
||||

|
||||
|
||||
You can see from the above diagram in:
|
||||
* **𝔸** our output on a platform like the CH32V203 is not perfect, that's because the SPI bus on the CH32V203 glitches by parts of a bit here and there. This causes other, weaker images in the output. But, largely we can produce totally valid and readable (at a long distance) LoRa packets.
|
||||
* **𝔹** LoRa consists of several upchirps some in a preamble.
|
||||
* **ℂ** two more upchirps with a phase offset indicating a sync word if we select 0x43 (or 0x34 depending on endain) for the upchirps here our packets will be decoded and potentially forwarded by commercial LoRa gateways.
|
||||
* **𝔻** 2.25 down chrips in. That extra .25 causes some pain 😈 (the minimum logical unit is a quarter chirp, not a whole chirp).
|
||||
* Then a payload where each upchirp is offset by a phase to convey information in **𝔼**.
|
||||
This diagram shows frequency on the X axis, and time on the Y axis (top to bottom)... You can see:
|
||||
* **�** our output on a platform like the CH32V203 is not perfect, that's because the SPI bus on the CH32V203 glitches by parts of a bit here and there. This causes other, weaker images in the output. But, largely we can produce totally valid and readable (at a long distance) LoRa packets.
|
||||
* **�** LoRa consists of several upchirps some in a preamble.
|
||||
* **ℂ** two more upchirps with a phase offset indicating a sync word if we select 0x43 (or 0x34 depending on endian) for the upchirps here, our packets will be decoded and potentially forwarded by commercial LoRa gateways.
|
||||
* **�** 2.25 down chrips in. That extra .25 causes some pain � (the minimum logical unit is a quarter chirp, not a whole chirp).
|
||||
* Then a payload where each upchirp is offset by a phase to convey information in **�**.
|
||||
|
||||
Conveniently the window for a given chirp is stable depending on the spreading factor. For the above packet, with SF7, it works out to 1,024us per symbol, or for SF8, 2,048us per symbol. Each symbol/chirp can represent a number of bits, by a phase offset.
|
||||
|
||||
The raw "phase" of a chirp is grey-coded in order to better spread the bit error between bits to higher layers of the process. For instance, if you are off-by-one with regards to the phase you believe the chirp is at, it could be over a boundary from say 0b1111 and 0b10000 and would cause 5 bit errors. By grey coding it, it minimizes the bit errors created by an off-by-one or even a few of the phase.
|
||||
|
||||
After this raw bitstream is decoded from the individual chirps and de-grey-coded (see `encodeHamming84sx`) in [`LoRa-SDR-Code.h`](https://github.com/cnlohr/lolra/blob/master/lib/LoRa-SDR-Code.h), then we transpose/interleve the bits so any one symbol that could get taken out (see `diagonalInterleaveSx`) to spread any errors out so a single lost symbol can be recovered, whitened (I believe this is actually a worthless step in this protocol, correct me if I'm wrong) see `Sx1272ComputeWhitening`. Above whitening is an error correction layer to help fix any of the bit errors taht could happen at a lower layer (see `encodeFec`).
|
||||
After this raw bitstream is decoded from the individual chirps and de-grey-coded (see `encodeHamming84sx`) in [`LoRa-SDR-Code.h`](https://github.com/cnlohr/lolra/blob/master/lib/LoRa-SDR-Code.h), then we transpose/interleve the bits so any one symbol that could get taken out (see `diagonalInterleaveSx`) to spread any errors out so a single lost symbol can be recovered and whitened (I believe this is actually a worthless step in this protocol, correct me if I'm wrong) see `Sx1272ComputeWhitening`. Above whitening is an error correction layer to help fix any of the bit errors that could happen at a lower layer (see `encodeFec`).
|
||||
|
||||
Overall the messages have a header, and a payload. Note that this can be a little tricky, because the header sometimes uses different encoding settings than the payload. And that's it.
|
||||
|
||||
@@ -115,16 +160,16 @@ A more detailed view of the protocol can be found [here, for a more academic vie
|
||||
|
||||
I started the project with an ESP32-S2 to see if I could output a signal using the internal built-in APLL, and routing the APLL/2 clock out via the IOMUX, and the answer was I could. Because this generates a simple square wave, and square waves have harmonics at F×3, F×5, F×7, etc... up the spectrum, if I set the APLL to 139.06 MHz, it outputs 69.53MHz. The 13th harmonic is 903.9 MHz, or the first 125kHz LoRa channel. Then by tuning the least significant PLL control bits, we can tune it from 903.9 MHz - 62.5kHz to 903.9 + 62.5kHz, by tuning the APLL to 139.06 MHz - 9.62kHz to 139.06 MHz + 9.62 kHz. This lets us generate the characteristic LoRa chirps and indeed this is receivable!
|
||||
|
||||
The ESP32-S2 also has another trick - the gpio mux is capable of outputting a signal or the inverse of that signal. That way we can differentially create the 139.06MHz signal, boosting the power output by 3dB!
|
||||
The ESP32-S2 also has another trick - the GPIO mux is capable of outputting a signal or the inverse of that signal. That way we can differentially create the 139.06MHz signal, boosting the power output by 3dB!
|
||||
|
||||
There are issues with the ESP32-S2, however. Notably that:
|
||||
1. The APLL is quite rough since it's actually an analog device fundamentally and struggles to keep tight control on the output signal.
|
||||
2. Its output looks very unusual, and is something that fundamentally limits the performance of the sending of frames.
|
||||
1. The APLL is quite rough since it's fundamentally an analog device and struggles to keep tight control on the output signal.
|
||||
2. Its output looks very unusual, and is something that limits the performance of the sending of frames.
|
||||
3. Because it is operating down at the F÷13 node, it has to operate over a very, very small window, ±9.62 kHz, which is quite challenging.
|
||||
|
||||
Additioanlly, very few processors even have an APLL, so in spite of this fast success, I decided to move onto direct synthesis.
|
||||
Additioanlly, very few processors even have an APLL, so in spite of this fast success, I decided to move onto...
|
||||
|
||||
### Direct bitstream synthesis.
|
||||
### Direct bitstream synthesis
|
||||
|
||||
Several years ago, I did a number of projects that used direct bitstream synthesis to do a few things, like [Broadcasting RF Color NTSC television on Channel 3 with an ESP8266](https://www.youtube.com/watch?v=bcez5pcp55w) or [Using Ethernet Packets to transmit AM radio](https://www.youtube.com/watch?v=-7jlRfqaYuY). One of the neat tricks is, if you transmit a bitstream out on an SPI or I2S shift register, it causes aliasing at the sample rate, with images at F×3, F×5, F×7, etc. But, the neat part is it preserves the size/shape of the transmitted waveform at images/aliases up the spectrum. For Channel 3, the 65MHz signal was being refelcted around the 40MHz sampling rate. Harry Nyquist can go bite a lemon.
|
||||
|
||||
@@ -132,21 +177,21 @@ This technique gives an incredible amount of fidelity even in extremely poor sit
|
||||
|
||||
There are several ways to accomplish this, but typically it's easiest with a shift register. A shift register like that in an I2S or SPI bus. And, if you use DMA, you can easily feed the shift register with more data without waking the CPU up every cycle. There are other ways, though, such as directly toggling an IO, or using a timer to turn an IO on and off at the right time, but it's easiest to write code to generate a bitstream and shift it out.
|
||||
|
||||
For shift registers, a few considerations must be made, such as making sure that the endianness and bit widths and memory arrangements are corret, but, in general, you can keep up, and unless there is lag, like time between each word, they are typically able to faithfully-enough represent a bit pattern on output to be transferred and shifted out of a pin.
|
||||
For shift registers, a few considerations must be made, such as making sure that the endianness and bit widths and memory arrangements are correct, but, in general, you can keep up, and unless there is lag, like time between each word, they are typically able to faithfully-enough represent a bit pattern on output to be transferred and shifted out of a pin.
|
||||
|
||||
The "lohrcut" described in the video involves writing a function that, given a point in time determines the amplitude of a signal. This function can be to determine the amplitude of a very high frequency signal, then, the sample rate can be whatever physically realizable sample rate that's avaialble. This will create an image of the high frequency signal at a much lower frequency signal, building it out of power between 0 and Fs/2.
|
||||
The "lohrcut" described in the video involves writing a function that, given a point in time, determines the amplitude of a signal. This function can be to determine the amplitude of a very high frequency signal, then, the sample rate can be whatever physically realizable sample rate that's avaialble. This will create an image of the high frequency signal at a much lower frequency signal, building it out of power between 0 and Fs/2.
|
||||
|
||||
Another concern is flash on some systems accesses inconsistently or doesn't work well at certain frequencies. In those cases, like on the ESP8266, the tables must be read into RAM and played from there.
|
||||
Another concern is flash, on some systems accesses inconsistently or doesn't work well at certain frequencies. In those cases, like on the ESP8266, the tables must be read into RAM and played from there.
|
||||
|
||||
## LoRaWAN
|
||||
|
||||
LoRa frames are totally encapsulated. If you wanted, we could stop here. You could even use a commercial gateway, but the frames could not be set to brokers like The Things Network. For instance, if you ran a raspberry pi gateway, you could just accept whatever old LoRa frames you wanted, but, we took this a step further by hleping the packets get forwarded around the world. LoRaWAN is "end to end" encryption, in that none of your neighbors, or gateways can read the messages. Though, it is curious - the things network CAN read youe messages because they have the encryption keys.
|
||||
LoRa frames are totally encapsulated. If you wanted, we could stop here. You could even use a commercial gateway, but without using LoRaWAN, the frames could not be sent to brokers like The Things Network. For instance, if you ran a raspberry pi gateway, you could just accept whatever old LoRa frames you wanted, but, we took this a step further by helping the packets get forwarded around the world. LoRaWAN is "end to end" encryption, in that none of your neighbors, or gateways can read the messages. Though, it is curious - The Things Network CAN read your messages because they have the encryption keys.
|
||||
|
||||
Conveniently, there is a single function call, `GenerateLoRaWANPacket` in [`lib/lorawan_simple.h`](https://github.com/cnlohr/lolra/blob/master/lib/lorawan_simple.h) that handles all of the required encapsulation. Simply use this function to getnerate your frames, and broadcast them!
|
||||
Conveniently, you can call, `GenerateLoRaWANPacket` in [`lib/lorawan_simple.h`](https://github.com/cnlohr/lolra/blob/master/lib/lorawan_simple.h) handles all of the required encapsulation. Simply use this function to generate your frames, and broadcast them!
|
||||
|
||||
### The LoRa Gateway
|
||||
|
||||
We can transmit these messages. Cool. But now to receive them, we either will need a devices like a [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module) or a gateway like a [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit). The latter is really interesting here because there are thousands of these set up all over the world, and connected to [The Things Network](https://www.thethingsnetwork.org/). That means if we transmit a properly formatted LoRaWAN packet within earshot of one of those gateways, we can get the frame elsewhere on the planet!
|
||||
We can transmit these messages. Cool. But now to receive them, we will either need a devices like a [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module) or a gateway like a [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit). The latter is really interesting here because there are thousands of these set up all over the world, and connected to [The Things Network](https://www.thethingsnetwork.org/). That means if we transmit a properly formatted LoRaWAN packet within earshot of one of those gateways, we can get the frame elsewhere on the planet!
|
||||
|
||||
Setup is pretty starightforward. You need to:
|
||||
1. Create an account (they are free for personal/academic use)
|
||||
@@ -175,14 +220,14 @@ Setup is pretty starightforward. You need to:
|
||||
|
||||
## Limitations
|
||||
|
||||
* SF <= 6, SF >= 11 are unavailable. I spent 10+ hours trying to figure them out and gave up.
|
||||
PR's are open if you can figure any of these out! I just spent all the time I plan to spend on this project before I got here.
|
||||
|
||||
* SF <= 6, SF >= 11 are unavailable. I spent 10+ hours trying to figure them out and gave up.
|
||||
* There seems to be something not quite perfect for some sizes. As in I was getting CRC errors in some places that my code "should" work but doesn't.
|
||||
* I never got LDRO to work correctly. I believe it might have to do with the LoRa Code Word (prefixing the 2 downchirps)
|
||||
* The SPI on the ch32v203 still isn't perfect. I was unable to get the I2S engine working, perhaps it doesn't work on the ch32v203?
|
||||
* The licenses in this project are a hodgepodge. I encourage people to just use this project as a starting point for other work.
|
||||
|
||||
PR's are open if you can figure any of these three out! I just spent all the time I plan to spend on this project before I got here.
|
||||
|
||||
|
||||
## Future Work
|
||||
|
||||
For LoRa specifically, waves are very well behaved and should be completely creatable with timer circuitry on the fly and should not need any precomputation, but I haven't gotten around to it yet. This would forego the need to have a large table for the chirps flashed into a device.
|
||||
@@ -193,38 +238,6 @@ Additionally, it would be fun to add a filter, or maybe try to build a filter in
|
||||
|
||||
Additionally, additionally, it would be very cool to try to build a Class C amplifier for the 900MHz signal. This would be very cool because it could be efficient, incredibly cheap and simple and also provide as much as 10-20dB of gain!
|
||||
|
||||
## Resources
|
||||
|
||||
### LoRa Software
|
||||
* [The C++ Library I based my LoRa Frames On](https://github.com/myriadrf/LoRa-SDR)
|
||||
* [A gnuradio LoRa library](https://github.com/tapparelj/gr-lora_sdr)
|
||||
* [Another gnuradio LoRa library](https://github.com/rpp0/gr-lora)
|
||||
* [GQRX](https://www.gqrx.dk/)
|
||||
* [gnuradio](https://www.gnuradio.org/)
|
||||
* [LoRa Baud Rate Calculator](https://unsigned.io/understanding-lora-parameters/) << be sure to select 125 or 500k Bandwidths, the default bandwidth is intenable.
|
||||
|
||||
### Papers and other resources
|
||||
* [A Great LoRa Introduction](https://medium.com/@prajzler/what-is-lora-the-fundamentals-79a5bb3e6dec)
|
||||
* [A more grounded paper on LoRa](https://chrisye-liu.github.io/files/yang22emu.pdf)
|
||||
* [Reversing LoRa by Matt Knight](https://github.com/matt-knight/research/blob/master/2016_05_20_jailbreak/Reversing-Lora-Knight.pdf)
|
||||
* [An academic paper on LoRa](https://dl.acm.org/doi/10.1145/3546869)
|
||||
|
||||
### Software Resources Directly Used
|
||||
* [ch32v003fun](https://github.com/cnlohr/ch32v003fun)
|
||||
* [esputil](https://github.com/cpq/esputil) dependency-free ESP programming
|
||||
* [nosdk8266](github.com/cnlohr/nosdk8266)
|
||||
|
||||
Hardware
|
||||
* [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit)
|
||||
* [Airspy Mini SDR](https://v3.airspy.us/product/a-airspy-mini/)
|
||||
* [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module)
|
||||
|
||||
## Special Thanks
|
||||
* @MustardTiger for a crazy amount of support work in this project
|
||||
* Willmore for the editing work
|
||||
* My girlfriend for testing help and auxiliary camera work
|
||||
* Everyone who helped out with my various open source projects.
|
||||
|
||||
## Range Tests
|
||||
|
||||
Urban testing was performed on 2024-02-23, Suburban on 2022-02-26 and Rural testing was performed on 2022-02-27.
|
||||
@@ -238,7 +251,7 @@ For TTGO Lora32, there was a +3dBi antenna added. For the MikroTik LR9, it used
|
||||
|------------|---------------------|--------------|-----------|-----|----------------------------------------------------|---------------|------------------|--------|
|
||||
| 2024-02-23 | CH32V203 | MikroTik LR9 | SF8/CR48 | 125 | Downtown Bellevue (Urban) | 435' 132m | -98 / -9 | Ground |
|
||||
| 2024-02-23 | CH32V203 | MikroTik LR9 | SF10/CR48 | 500 | Downtown Bellevue (Urban) | 435' 132m | -90 / -18 | Ground |
|
||||
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Mirramont Park (Light Suburban + Woods) | >576' >176m | -134 / -12 | Ground |
|
||||
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Miramont Park (Light Suburban + Woods) | >576' >176m | -134 / -12 | Ground |
|
||||
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Poo Poo Point Trailhead (Rural) | >1117' >340m | -123 / -6 | Ground |
|
||||
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Issaquah Suburb (+Light Trees) | 2200' 669m | -133 / -10 | Ground |
|
||||
| 2024-02-27 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Meadowbrook (Rural) Red Longer Antenna | 2220' 677m | -135 / -13 | Drone |
|
||||
@@ -248,8 +261,8 @@ For TTGO Lora32, there was a +3dBi antenna added. For the MikroTik LR9, it used
|
||||
| 2024-02-27 | ESP8266 @ 80MHz | TTGO Lora32 | SF8/CR48 | 125 | Meadowbrook (Rural) Grey VNA Matched Antenna | 2789' 850m | -138 / -13 | Drone |
|
||||
| 2024-02-27 | ESP8266 @ 173MHz | TTGO Lora32 | SF7/CR48 | 125 | Meadowbrook (Rural) Grey VNA Matched Antenna | 2812' 857m | -131 / -8 | Drone |
|
||||
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Meadowbrook (Rural) (Note 1) | 3428' 1044m | -137 / -13 | Ground |
|
||||
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Meadowbrook (Rural) Light Percipitation | >4895' >1492m | -130 / -8 | Drone |
|
||||
| 2024-02-27 | ESP32-S2 + Funtenna | TTGO Lora32 | SF10/CR48 | 125 | Meadow brook (Rural) Light Percipitation | 705' / 215m | -139 / -15 | Drone |
|
||||
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Meadowbrook (Rural) Light Precipitation | >4895' >1492m | -130 / -8 | Drone |
|
||||
| 2024-02-27 | ESP32-S2 + Funtenna | TTGO Lora32 | SF10/CR48 | 125 | Meadow brook (Rural) Light Precipitation | 705' / 215m | -139 / -15 | Drone |
|
||||
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Snoqualmie Trail, Dog Park to Ribary Creek (Rural) Light Percipitation | 8460' / 2580m | -141 / -16 | Drone |
|
||||
|
||||
1. There were two ground ESP32-S2 + Bitenna Tests. The one mentioned in the video is not recorded here, since I didn't get accurate results.
|
||||
@@ -257,3 +270,46 @@ For TTGO Lora32, there was a +3dBi antenna added. For the MikroTik LR9, it used
|
||||
3. On the CH32V203, there is a 60 uA difference at 3.3V with anteanna on/off (some is going to be capacitive / inductive loading / reflected back because of SWR). The EIRP is **less** than this, based on the antenna stub SWR, but this is the total power consumption, so it is probably less than 120uW of EIRP.
|
||||
|
||||
|
||||
## Resources
|
||||
|
||||
### LoRa Software
|
||||
* [The C++ Library I based my LoRa Frames On](https://github.com/myriadrf/LoRa-SDR)
|
||||
* [A gnuradio LoRa library](https://github.com/tapparelj/gr-lora_sdr)
|
||||
* [Another gnuradio LoRa library](https://github.com/rpp0/gr-lora)
|
||||
* [GQRX](https://www.gqrx.dk/)
|
||||
* [gnuradio](https://www.gnuradio.org/)
|
||||
* [LoRa Baud Rate Calculator](https://unsigned.io/understanding-lora-parameters/) << be sure to select 125 or 500k Bandwidths, the default bandwidth is not useful.
|
||||
|
||||
### Papers and other resources
|
||||
* [A Great LoRa Introduction](https://medium.com/@prajzler/what-is-lora-the-fundamentals-79a5bb3e6dec)
|
||||
* [A more grounded paper on LoRa](https://chrisye-liu.github.io/files/yang22emu.pdf)
|
||||
* [Reversing LoRa by Matt Knight](https://github.com/matt-knight/research/blob/master/2016_05_20_jailbreak/Reversing-Lora-Knight.pdf)
|
||||
* [An academic paper on LoRa](https://dl.acm.org/doi/10.1145/3546869)
|
||||
* Brought to my attention after I published, [Everything has its Bad Side and Good Side: Turning Processors to
|
||||
Low Overhead Radios Using Side-Channels](https://dl.acm.org/doi/abs/10.1145/3583120.3586959) Accomplished something very similar to this, with an arduino!
|
||||
|
||||
### Software Resources Directly Used
|
||||
* [ch32v003fun](https://github.com/cnlohr/ch32v003fun)
|
||||
* [esputil](https://github.com/cpq/esputil) dependency-free ESP programming
|
||||
* [nosdk8266](https://github.com/cnlohr/nosdk8266)
|
||||
|
||||
### Hardware
|
||||
* [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit)
|
||||
* [Airspy Mini SDR](https://v3.airspy.us/product/a-airspy-mini/)
|
||||
* [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module)
|
||||
|
||||
### LoLRa Like Things
|
||||
* [Wirelessly control 49 MHz toy with I/O line flipping on Pi Pico](https://www.youtube.com/watch?v=K-6dos8Hvm8)
|
||||
|
||||
### Other Interesting Radio Links
|
||||
|
||||
* [Radio station snafu in Seattle bricks some Mazda infotainment systems](https://arstechnica.com/cars/2022/02/radio-station-snafu-in-seattle-bricks-some-mazda-infotainment-systems/)
|
||||
|
||||
## Special Thanks
|
||||
* @MustardTiger for a crazy amount of support work in this project
|
||||
* Willmore for the editing work
|
||||
* Several other folks in my discord for review work and editing work on this page
|
||||
* My girlfriend for testing help and auxiliary camera work
|
||||
* Everyone who helped out with my various open source projects
|
||||
|
||||
|
||||
|
||||
@@ -89,22 +89,23 @@ SOFTWARE.
|
||||
Calculated to use the 19.75th harmonic @ 27.08571429MHz, but ideal found at 27.08643MHz
|
||||
*/
|
||||
|
||||
#define Q 80
|
||||
#define Q 1000
|
||||
|
||||
#define PWM_PERIOD (31-1) //For 27.0857MHz
|
||||
#define QUADRATURE
|
||||
#define PWM_PERIOD (28-1) //For 27.000500MHz
|
||||
//#define QUADRATURE
|
||||
//#define TIGHT_OUT
|
||||
//#define DUMPBUFF
|
||||
#define PWM_OUTPUT 7
|
||||
|
||||
//#define PWM_PERIOD (32-1)
|
||||
//#define QUADRATURE
|
||||
#define PWM_OUTPUT 3
|
||||
//#define PWM_OUTPUT 3
|
||||
|
||||
#define ADC_BUFFSIZE 256
|
||||
volatile uint16_t adc_buffer[ADC_BUFFSIZE];
|
||||
|
||||
void SetupADC()
|
||||
{
|
||||
// PD4 is analog input chl 7
|
||||
GPIOD->CFGLR &= ~(0xf<<(4*4)); // CNF = 00: Analog, MODE = 00: Input
|
||||
|
||||
// Reset the ADC to init all regs
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1;
|
||||
@@ -117,10 +118,14 @@ void SetupADC()
|
||||
// Set up single conversion on chl 7
|
||||
ADC1->RSQR1 = 0;
|
||||
ADC1->RSQR2 = 0;
|
||||
ADC1->RSQR3 = 7; // 0-9 for 8 ext inputs and two internals
|
||||
ADC1->RSQR3 = 6; // 0-9 for 8 ext inputs and two internals /// 7 or 6 means one of the ADC inputs.
|
||||
|
||||
// Not using injection group.
|
||||
|
||||
// PD4 is analog input chl 7 + 6
|
||||
GPIOD->CFGLR &= ~(0xf<<(4*4)); // CNF = 00: Analog, MODE = 00: Input
|
||||
GPIOD->CFGLR &= ~(0xf<<(4*6)); // CNF = 00: Analog, MODE = 00: Input
|
||||
|
||||
// Sampling time for channels. Careful: This has PID tuning implications.
|
||||
// Note that with 3 and 3,the full loop (and injection) runs at 138kHz.
|
||||
ADC1->SAMPTR2 = (0<<(3*7));
|
||||
@@ -214,23 +219,31 @@ void InnerLoop()
|
||||
|
||||
int tstart = 0;
|
||||
|
||||
#ifdef DUMPBUFF
|
||||
uint16_t shadowbuff[Q+16];
|
||||
int shadowplace = 0;
|
||||
#define SHADOWSTORE(X) shadowbuff[frcnt+X] = t;
|
||||
#else
|
||||
#define SHADOWSTORE(X)
|
||||
#endif
|
||||
|
||||
while( 1 )
|
||||
{
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR; // Warning, sometimes this is == to the base, or == 0 (i.e. might be 256, if top is 255)
|
||||
if( tpl == ADC_BUFFSIZE ) tpl = 0;
|
||||
|
||||
adc_buffer_end = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
|
||||
//printf( "%3d %4d %d %04x\n", DMA1_Channel1->CNTR, TIM1->CNT, ADC1->RDATAR, ADC1->STATR );
|
||||
while( adc != adc_buffer_end )
|
||||
{
|
||||
#ifdef QUADRATURE
|
||||
int32_t t = adc[0];
|
||||
int32_t t = adc[0]; SHADOWSTORE(0);
|
||||
i += t; q += t;
|
||||
t = adc[1];
|
||||
t = adc[1]; SHADOWSTORE(1);
|
||||
i -= t; q += t;
|
||||
t = adc[2];
|
||||
t = adc[2]; SHADOWSTORE(2);
|
||||
i -= t; q -= t;
|
||||
t = adc[3];
|
||||
t = adc[3]; SHADOWSTORE(3);
|
||||
i += t; q -= t;
|
||||
adc += 4;
|
||||
frcnt += 4;
|
||||
@@ -241,37 +254,48 @@ void InnerLoop()
|
||||
#endif
|
||||
|
||||
if( adc == adc_buffer_top ) adc = adc_buffer;
|
||||
if( frcnt >= Q ) break;
|
||||
}
|
||||
|
||||
if( frcnt > Q )
|
||||
|
||||
if( frcnt >= Q )
|
||||
{
|
||||
#ifdef QUADRATURE
|
||||
int ti = i>>1;
|
||||
int tq = q>>1;
|
||||
int s = (ti*ti + tq*tq)>>8;
|
||||
#else
|
||||
int s = i>>2;
|
||||
|
||||
#ifdef DUMPBUFF
|
||||
int j;
|
||||
for( j = 0; j < Q; j++ )
|
||||
printf( "%d,%d\n", j, shadowbuff[j] );
|
||||
#endif
|
||||
#ifdef QUADRATURE
|
||||
int ti = i>>3;
|
||||
int tq = q>>3;
|
||||
int is = (ti*ti + tq*tq)>>8;
|
||||
#else
|
||||
int is = ((i<0)?-i:i)>>2;
|
||||
#endif
|
||||
int s = 1<<( ( 32 - __builtin_clz(is) )/2);
|
||||
s = (s + is/s)/2;
|
||||
|
||||
#ifdef TIGHT_OUT
|
||||
printf( "%d\n", i );
|
||||
printf( "%d\n", is );
|
||||
#elif defined( PWM_OUTPUT )
|
||||
int tv = (s>>PWM_OUTPUT) + (PWM_PERIOD/2);
|
||||
|
||||
|
||||
int tv = (i>>PWM_OUTPUT) + (PWM_PERIOD/2);
|
||||
if( tv < 0 ) tv = 0;
|
||||
if( tv >= PWM_PERIOD ) tv = PWM_PERIOD-1;
|
||||
|
||||
TIM1->CH4CVR = tv;
|
||||
#else
|
||||
int ti = i>>2;
|
||||
int tq = q>>2;
|
||||
int s = (ti*ti + tq*tq)>>8;
|
||||
//s = usqrt4(s);
|
||||
|
||||
printf( "%8d I:%7d Q:%7d [%d %d %d %d] / %d\n",s, i ,q, adc_buffer[0], adc_buffer[1], adc_buffer[2], adc_buffer[3], SysTick->CNT - tstart );
|
||||
printf( "%8d I:%7d Q:%7d [%d %d %d %d] / %d\n",s, i ,q, adc_buffer[0], adc_buffer[1], adc_buffer[2], adc_buffer[3], (int)(SysTick->CNT - tstart) );
|
||||
#endif
|
||||
//printf( "%d\n", s );
|
||||
frcnt = 0;
|
||||
i = 0;
|
||||
q = 0;
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR;
|
||||
adc = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
tstart = SysTick->CNT;
|
||||
}
|
||||
/*
|
||||
@@ -285,6 +309,7 @@ void InnerLoop()
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
@@ -294,6 +319,8 @@ int main()
|
||||
|
||||
SystemInit();
|
||||
|
||||
Delay_Ms(10);
|
||||
|
||||
printf( "System On\n" );
|
||||
|
||||
// Enable Peripherals
|
||||
@@ -303,6 +330,11 @@ int main()
|
||||
|
||||
RCC->APB1PCENR = RCC_APB1Periph_TIM2;
|
||||
|
||||
// Disable HSI
|
||||
RCC->CTLR &= ~(RCC_HSION);
|
||||
|
||||
printf( "CTLR: %08x CFGR0: %08x\n", RCC->CTLR, RCC->CFGR0 );
|
||||
|
||||
SetupADC();
|
||||
|
||||
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<SCRIPT>
|
||||
|
||||
|
||||
function DrawSpan( colspan, freq, target, docolor )
|
||||
{
|
||||
var fdist = Math.abs( freq - target );
|
||||
fdist = Math.pow( fdist, 0.5 ) * 500;
|
||||
// if( fdist > 255 ) fdist = 255;
|
||||
let ret = "<TD COLSPAN=" + colspan + ' ';
|
||||
if( docolor ) ret += 'STYLE="background-color:rgb(' + fdist + ',' + (511-fdist) + ',0)";';
|
||||
ret += '>' + freq.toFixed(6) + "</TD>";
|
||||
return ret;
|
||||
}
|
||||
|
||||
function computeTable()
|
||||
{
|
||||
const max_harmonics = 28|0;
|
||||
const min_harmonics = 1|0;
|
||||
let xtal = Number(document.getElementById("crystalmhz").value );
|
||||
let target = Number(document.getElementById("targetmhz").value );
|
||||
let contents = "<TABLE BORDER=1>";
|
||||
|
||||
contents += '<TR><TH>d\\h</div></TH>';
|
||||
for( let h = 0|min_harmonics; h <= max_harmonics; h++ )
|
||||
{
|
||||
contents += "<TH COLSPAN=2>" + h + "</TH>";
|
||||
}
|
||||
contents += "</TR>";
|
||||
|
||||
|
||||
for( let n = 0|28; n <= 66; n++ )
|
||||
{
|
||||
for( let mode = 0; mode < 4; mode++ )
|
||||
{
|
||||
contents += "<TR>";
|
||||
if( mode == 0 )
|
||||
contents += "<TD ROWSPAN=4>" + n + "</TD>";
|
||||
for( let h = 0|min_harmonics; h <= max_harmonics; h++ )
|
||||
{
|
||||
let freq = ( xtal / n );
|
||||
if( mode == 0 )
|
||||
contents += DrawSpan( 2, freq * h, target, false );
|
||||
else if( mode == 1 )
|
||||
contents += DrawSpan( 2, freq * (h-.25), target, true );
|
||||
else if( mode == 2 )
|
||||
contents += DrawSpan( 2, freq * (h+.25), target, true );
|
||||
else if( mode == 3 )
|
||||
contents += DrawSpan( 2, freq + (h+ 0.5), target, true );
|
||||
|
||||
}
|
||||
contents += "</TD>";
|
||||
}
|
||||
}
|
||||
contents += "</TABLE>";
|
||||
document.getElementById( "TABLE" ).innerHTML = contents;
|
||||
}
|
||||
|
||||
</SCRIPT>
|
||||
</HEAD>
|
||||
<BODY>
|
||||
|
||||
<p>Tool for computing tuning to specific frequencies by use of direct ADC reading at specific timer-controlled rate to "tune" to specific frequencies either by quadrature or differential.</p>
|
||||
<TABLE>
|
||||
<TR><TD>Crystal MHz</TD><TD><INPUT ID=crystalmhz VALUE=48></TD></TR>
|
||||
<TR><TD>Target MHz</TD><TD><INPUT ID=targetmhz VALUE=27.1></TD></TR>
|
||||
<TR><TD COLSPAN=2><INPUT TYPE=SUBMIT ONCLICK="computeTable()"></TD></TR>
|
||||
</TABLE>
|
||||
|
||||
<TABLE>
|
||||
<TR><TD>Quadrature:</TD></TR>
|
||||
<TR><TD>I = + + - -</TD></TR>
|
||||
<TR><TD>Q = + - - +</TD></TR>
|
||||
<TR><TD>Differntial:</TD></TR>
|
||||
<TR><TD>V = + - + -</TD></TR>
|
||||
<TR><TD>You choose the mode you operate in, either Quadrature or differential</TD></TR>
|
||||
</TABLE>
|
||||
|
||||
<p> Table shows: </P>
|
||||
<TABLE BORDER=1>
|
||||
<TR><TD>Sample Frequency Harmonic</TD></TR>
|
||||
<TR><TD>Lower Quadrature Frequency</TD></TR>
|
||||
<TR><TD>Upper Quadrature Frequency</TD></TR>
|
||||
<TR><TD>Differential Frequency</TD></TR>
|
||||
</TABLE>
|
||||
|
||||
<DIV ID=TABLE></DIV>
|
||||
|
||||
</BODY>
|
||||
</HTML>
|
||||
@@ -0,0 +1,21 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=adcrx
|
||||
TARGET_MCU:=CH32V003
|
||||
CH32V003FUN:=../ch32v003fun/ch32v003fun
|
||||
|
||||
ADDITIONAL_C_FILES+=../rv003usb/rv003usb/rv003usb.S ../rv003usb/rv003usb/rv003usb.c
|
||||
EXTRA_CFLAGS:=-I../rv003usb/lib -I../rv003usb/rv003usb -mstrict-align -Wno-unused-function
|
||||
|
||||
include ../ch32v003fun/ch32v003fun/ch32v003fun.mk
|
||||
|
||||
programmerclock :
|
||||
$(MINICHLINK)/minichlink -X ECLK 1:0:0:8:3
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
rm -rf rf_data_gen chirpbuff.dat chirpbuff.h chirpbuffinfo.h
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
THIS DOES NOT WORK DO NOT USE IT YET
|
||||
@@ -0,0 +1,378 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
**/
|
||||
|
||||
// NOT LORA!!! -- but experimenting with the possibility of rx.
|
||||
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "rv003usb.h"
|
||||
|
||||
uint8_t scratchout[15];
|
||||
volatile int outready = 0;
|
||||
uint8_t scratchin[255];
|
||||
volatile int inready = 0;
|
||||
|
||||
|
||||
#define PWM_PERIOD (28-1) //For 27.000500MHz
|
||||
#define QUADRATURE
|
||||
|
||||
uint32_t TQ = 128;
|
||||
|
||||
#define ADC_BUFFSIZE 256
|
||||
volatile uint16_t adc_buffer[ADC_BUFFSIZE];
|
||||
|
||||
void SetupADC()
|
||||
{
|
||||
// Reset the ADC to init all regs
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_ADC1;
|
||||
|
||||
// ADCCLK = 12 MHz => RCC_ADCPRE divide by 4
|
||||
RCC->CFGR0 &= ~RCC_ADCPRE; // Clear out the bis in case they were set
|
||||
RCC->CFGR0 |= RCC_ADCPRE_DIV2; // Fastest possible (divide-by-2) NOTE: This is OUTSIDE the specified value in the datasheet.
|
||||
|
||||
// Set up single conversion on chl 7
|
||||
ADC1->RSQR1 = 0;
|
||||
ADC1->RSQR2 = 0;
|
||||
ADC1->RSQR3 = 6; // 0-9 for 8 ext inputs and two internals /// 7 or 6 means one of the ADC inputs.
|
||||
|
||||
// Not using injection group.
|
||||
|
||||
// PD4 is analog input chl 7 + 6
|
||||
GPIOD->CFGLR &= ~(0xf<<(4*4)); // CNF = 00: Analog, MODE = 00: Input
|
||||
GPIOD->CFGLR &= ~(0xf<<(4*6)); // CNF = 00: Analog, MODE = 00: Input
|
||||
|
||||
// Sampling time for channels. Careful: This has PID tuning implications.
|
||||
// Note that with 3 and 3,the full loop (and injection) runs at 138kHz.
|
||||
ADC1->SAMPTR2 = (0<<(3*7));
|
||||
|
||||
// Turn on ADC and set rule group to sw trig
|
||||
// 0 = Use TRGO event for Timer 1 to fire ADC rule.
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_EXTTRIG | ADC_DMA;
|
||||
|
||||
// Reset calibration
|
||||
ADC1->CTLR2 |= ADC_RSTCAL;
|
||||
while(ADC1->CTLR2 & ADC_RSTCAL);
|
||||
|
||||
// Calibrate ADC
|
||||
ADC1->CTLR2 |= ADC_CAL;
|
||||
while(ADC1->CTLR2 & ADC_CAL);
|
||||
|
||||
// ADC_SCAN: Allow scanning.
|
||||
ADC1->CTLR1 = ADC_SCAN;
|
||||
|
||||
// Turn on DMA
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
//DMA1_Channel1 is for ADC
|
||||
DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR;
|
||||
DMA1_Channel1->MADDR = (uint32_t)adc_buffer;
|
||||
DMA1_Channel1->CNTR = ADC_BUFFSIZE;
|
||||
DMA1_Channel1->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_VeryHigh |
|
||||
DMA_MemoryDataSize_HalfWord |
|
||||
DMA_PeripheralDataSize_HalfWord |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Circular |
|
||||
DMA_DIR_PeripheralSRC;
|
||||
|
||||
// Turn on DMA channel 1
|
||||
DMA1_Channel1->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
// Enable continuous conversion and DMA
|
||||
//ADC1->CTLR2 |= ADC_DMA | ADC_EXTSEL; //ADC_CONT
|
||||
|
||||
// start conversion
|
||||
ADC1->CTLR2 |= ADC_SWSTART;
|
||||
|
||||
}
|
||||
|
||||
static void SetupTimer1()
|
||||
{
|
||||
// Enable Timer 1
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_TIM1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_TIM1;
|
||||
|
||||
TIM1->PSC = 0x0000; // Prescalar to 0x0000 (so, 48MHz base clock)
|
||||
TIM1->ATRLR = PWM_PERIOD;
|
||||
|
||||
#ifdef PWM_OUTPUT
|
||||
GPIOC->CFGLR &= ~(0xf<<(4*4));
|
||||
GPIOC->CFGLR |= (GPIO_Speed_10MHz | GPIO_CNF_OUT_PP_AF)<<(4*4);
|
||||
|
||||
TIM1->CCER = TIM_CC4E | TIM_CC4P;
|
||||
TIM1->CHCTLR2 = TIM_OC4M_2 | TIM_OC4M_1;
|
||||
TIM1->CH4CVR = 5; // Actual duty cycle (Off to begin with)
|
||||
#endif
|
||||
|
||||
// Setup TRGO for ADC. This makes is to the ADC will trigger on timer
|
||||
// reset, so we trigger at the same position every time relative to the
|
||||
// FET turning on.
|
||||
TIM1->CTLR2 = TIM_MMS_1;
|
||||
|
||||
// Enable TIM1 outputs
|
||||
TIM1->BDTR = TIM_MOE;
|
||||
TIM1->CTLR1 = TIM_CEN;
|
||||
}
|
||||
|
||||
|
||||
void InnerLoop() __attribute__((noreturn));
|
||||
|
||||
|
||||
void InnerLoop()
|
||||
{
|
||||
int i = 0;
|
||||
int q = 0;
|
||||
int tpl = 0;
|
||||
int Q = TQ;
|
||||
|
||||
// Timer goes backwards when we are moving forwards.
|
||||
volatile uint16_t * adc_buffer_end = 0;
|
||||
volatile uint16_t * adc_buffer_top = adc_buffer + ADC_BUFFSIZE;
|
||||
volatile uint16_t * adc = adc_buffer;
|
||||
|
||||
int frcnt = 0;
|
||||
|
||||
int tstart = 0;
|
||||
|
||||
#ifdef DUMPBUFF
|
||||
uint16_t shadowbuff[Q+16];
|
||||
int shadowplace = 0;
|
||||
#define SHADOWSTORE(X) shadowbuff[frcnt+X] = t;
|
||||
#else
|
||||
#define SHADOWSTORE(X)
|
||||
#endif
|
||||
|
||||
while( 1 )
|
||||
{
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR; // Warning, sometimes this is == to the base, or == 0 (i.e. might be 256, if top is 255)
|
||||
if( tpl == ADC_BUFFSIZE ) tpl = 0;
|
||||
|
||||
adc_buffer_end = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
//printf( "%3d %4d %d %04x\n", DMA1_Channel1->CNTR, TIM1->CNT, ADC1->RDATAR, ADC1->STATR );
|
||||
while( adc != adc_buffer_end )
|
||||
{
|
||||
int32_t t = adc[0]; SHADOWSTORE(0);
|
||||
i += t; q += t;
|
||||
t = adc[1]; SHADOWSTORE(1);
|
||||
i -= t; q += t;
|
||||
t = adc[2]; SHADOWSTORE(2);
|
||||
i -= t; q -= t;
|
||||
t = adc[3]; SHADOWSTORE(3);
|
||||
i += t; q -= t;
|
||||
adc += 4;
|
||||
frcnt += 4;
|
||||
|
||||
if( adc == adc_buffer_top ) adc = adc_buffer;
|
||||
if( frcnt >= Q ) break;
|
||||
}
|
||||
|
||||
|
||||
if( frcnt >= Q )
|
||||
{
|
||||
|
||||
int ti = i>>3;
|
||||
int tq = q>>3;
|
||||
int is = (ti*ti + tq*tq)>>8;
|
||||
|
||||
int s = 1<<( ( 32 - __builtin_clz(is) )/2);
|
||||
s = (s + is/s)/2;
|
||||
|
||||
//int tv = (i>>PWM_OUTPUT) + (PWM_PERIOD/2);
|
||||
//if( tv < 0 ) tv = 0;
|
||||
//if( tv >= PWM_PERIOD ) tv = PWM_PERIOD-1;
|
||||
//TIM1->CH4CVR = tv;
|
||||
|
||||
//printf( "%d\n", s );
|
||||
frcnt = 0;
|
||||
i = 0;
|
||||
q = 0;
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR;
|
||||
adc = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
tstart = SysTick->CNT;
|
||||
}
|
||||
/*
|
||||
Delay_Us( 100 );
|
||||
int end = DMA1_Channel1->CNTR;
|
||||
int v0 = adc_buffer[0];
|
||||
int v1 = adc_buffer[1];
|
||||
int v2 = adc_buffer[2];
|
||||
int v3 = adc_buffer[3];
|
||||
printf( "%d %d %d %d %d\n", (uint8_t)(start-end), v0, v1, v2, v3 );
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// REQUIRES External 24MHz oscillator
|
||||
printf( "Initializing\n" );
|
||||
|
||||
SystemInit();
|
||||
|
||||
Delay_Ms(10);
|
||||
|
||||
printf( "System On\n" );
|
||||
|
||||
// Enable Peripherals
|
||||
RCC->APB2PCENR |= RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOC |
|
||||
RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1 | RCC_APB2Periph_ADC1 |
|
||||
RCC_APB2Periph_AFIO;
|
||||
|
||||
RCC->APB1PCENR = RCC_APB1Periph_TIM2;
|
||||
|
||||
// Disable HSI
|
||||
RCC->CTLR &= ~(RCC_HSION);
|
||||
|
||||
printf( "CTLR: %08lx CFGR0: %08lx\n", RCC->CTLR, RCC->CFGR0 );
|
||||
|
||||
SetupADC();
|
||||
|
||||
while(1)
|
||||
printf( "ADC Setup\n" );
|
||||
|
||||
#if 0
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_EN; // turn on the op-amp
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_PSEL; // select op-amp pos pin: 0 = PA2, 1 = PD7
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_NSEL; // select op-amp neg pin: 0 = PA1, 1 = PD0
|
||||
#endif
|
||||
|
||||
// SetupTimer1();
|
||||
printf( "Timer 1 setup\n" );
|
||||
InnerLoop();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
void usb_handle_user_in_request( struct usb_endpoint * e, uint8_t * scratchpad, int endp, uint32_t sendtok, struct rv003usb_internal * ist )
|
||||
{
|
||||
// Make sure we only deal with control messages. Like get/set feature reports.
|
||||
if( endp )
|
||||
{
|
||||
usb_send_empty( sendtok );
|
||||
}
|
||||
}
|
||||
|
||||
void usb_handle_user_data( struct usb_endpoint * e, int current_endpoint, uint8_t * data, int len, struct rv003usb_internal * ist )
|
||||
{
|
||||
if( outready )
|
||||
{
|
||||
// Send NACK (can't accept any more data right now)
|
||||
usb_send_data( 0, 0, 2, 0x5A );
|
||||
return;
|
||||
}
|
||||
|
||||
usb_send_data( 0, 0, 2, 0xD2 ); // Send ACK
|
||||
int offset = e->count<<3;
|
||||
int torx = e->max_len - offset;
|
||||
if( torx > len ) torx = len;
|
||||
if( torx > 0 )
|
||||
{
|
||||
memcpy( scratchout + offset, data, torx );
|
||||
e->count++;
|
||||
if( ( e->count << 3 ) >= e->max_len )
|
||||
{
|
||||
outready = e->max_len;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void usb_handle_hid_get_report_start( struct usb_endpoint * e, int reqLen, uint32_t lValueLSBIndexMSB )
|
||||
{
|
||||
if( reqLen > sizeof( scratchin ) ) reqLen = sizeof( scratchin );
|
||||
|
||||
// You can check the lValueLSBIndexMSB word to decide what you want to do here
|
||||
// But, whatever you point this at will be returned back to the host PC where
|
||||
// it calls hid_get_feature_report.
|
||||
//
|
||||
// Please note, that on some systems, for this to work, your return length must
|
||||
// match the length defined in HID_REPORT_COUNT, in your HID report, in usb_config.h
|
||||
|
||||
if( reqLen > inready ) inready = inready;
|
||||
e->opaque = scratchin;
|
||||
e->max_len = reqLen;
|
||||
}
|
||||
|
||||
void usb_handle_hid_set_report_start( struct usb_endpoint * e, int reqLen, uint32_t lValueLSBIndexMSB )
|
||||
{
|
||||
// Here is where you get an alert when the host PC calls hid_send_feature_report.
|
||||
//
|
||||
// You can handle the appropriate message here. Please note that in this
|
||||
// example, the data is chunked into groups-of-8-bytes.
|
||||
//
|
||||
// Note that you may need to make this match HID_REPORT_COUNT, in your HID
|
||||
// report, in usb_config.h
|
||||
|
||||
if( outready ) reqLen = 0;
|
||||
if( reqLen > sizeof( scratchout ) ) reqLen = sizeof( scratchout );
|
||||
e->opaque = scratchout;
|
||||
e->max_len = reqLen;
|
||||
}
|
||||
|
||||
|
||||
void usb_handle_other_control_message( struct usb_endpoint * e, struct usb_urb * s, struct rv003usb_internal * ist )
|
||||
{
|
||||
LogUEvent( SysTick->CNT, s->wRequestTypeLSBRequestMSB, s->lValueLSBIndexMSB, s->wLength );
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
#define FUNCONF_SYSTICK_USE_HCLK 1
|
||||
|
||||
#endif
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,155 @@
|
||||
#ifndef _USB_CONFIG_H
|
||||
#define _USB_CONFIG_H
|
||||
|
||||
//Defines the number of endpoints for this device. (Always add one for EP0). For two EPs, this should be 3.
|
||||
#define ENDPOINTS 2
|
||||
|
||||
#define USB_PORT D // [A,C,D] GPIO Port to use with D+, D- and DPU
|
||||
#define USB_PIN_DP 3 // [0-4] GPIO Number for USB D+ Pin
|
||||
#define USB_PIN_DM 4 // [0-4] GPIO Number for USB D- Pin
|
||||
#define USB_PIN_DPU 5 // [0-7] GPIO for feeding the 1.5k Pull-Up on USB D- Pin; Comment out if not used / tied to 3V3!
|
||||
|
||||
#define RV003USB_DEBUG_TIMING 0
|
||||
#define RV003USB_OPTIMIZE_FLASH 1
|
||||
#define RV003USB_EVENT_DEBUGGING 0
|
||||
#define RV003USB_HANDLE_IN_REQUEST 1
|
||||
#define RV003USB_OTHER_CONTROL 0
|
||||
#define RV003USB_HANDLE_USER_DATA 1
|
||||
#define RV003USB_HID_FEATURES 1
|
||||
#define RV003USB_USER_DATA_HANDLES_TOKEN 1
|
||||
|
||||
#ifndef __ASSEMBLER__
|
||||
|
||||
#include <tinyusb_hid.h>
|
||||
|
||||
#ifdef INSTANCE_DESCRIPTORS
|
||||
|
||||
//Taken from http://www.usbmadesimple.co.uk/ums_ms_desc_dev.htm
|
||||
static const uint8_t device_descriptor[] = {
|
||||
18, //Length
|
||||
1, //Type (Device)
|
||||
0x10, 0x01, //Spec
|
||||
0x0, //Device Class
|
||||
0x0, //Device Subclass
|
||||
0x0, //Device Protocol (000 = use config descriptor)
|
||||
0x08, //Max packet size for EP0 (This has to be 8 because of the USB Low-Speed Standard)
|
||||
0xcd, 0xab, //ID Vendor
|
||||
0x11, 0x11, //ID Product
|
||||
0x02, 0x00, //ID Rev
|
||||
1, //Manufacturer string
|
||||
2, //Product string
|
||||
3, //Serial string
|
||||
1, //Max number of configurations
|
||||
};
|
||||
|
||||
static const uint8_t special_hid_desc[] = {
|
||||
HID_USAGE_PAGE ( 0xff ), // Vendor-defined page.
|
||||
HID_USAGE ( 0x00 ),
|
||||
HID_REPORT_SIZE ( 8 ),
|
||||
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),
|
||||
HID_REPORT_COUNT ( 255 ), // IN
|
||||
HID_REPORT_ID ( 0xa4 )
|
||||
HID_USAGE ( 0x01 ),
|
||||
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,
|
||||
HID_REPORT_COUNT_N ( 256, 2 ), // OUT
|
||||
HID_REPORT_ID ( 0xad )
|
||||
HID_USAGE ( 0x01 ),
|
||||
HID_COLLECTION_END,
|
||||
};
|
||||
|
||||
static const uint8_t config_descriptor[] = {
|
||||
// configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
|
||||
9, // bLength;
|
||||
2, // bDescriptorType;
|
||||
0x22, 0x00, // wTotalLength
|
||||
|
||||
//34, 0x00, //for just the one descriptor
|
||||
|
||||
0x01, // bNumInterfaces (Normally 1)
|
||||
0x01, // bConfigurationValue
|
||||
0x00, // iConfiguration
|
||||
0x80, // bmAttributes (was 0xa0)
|
||||
0x64, // bMaxPower (200mA)
|
||||
|
||||
//Class FF device.
|
||||
9, // bLength
|
||||
4, // bDescriptorType
|
||||
0, // bInterfaceNumber = 1 instead of 0 -- well make it second.
|
||||
0, // bAlternateSetting
|
||||
1, // bNumEndpoints
|
||||
0x03, // bInterfaceClass (0x03 = HID)
|
||||
0x00, // bInterfaceSubClass
|
||||
0xff, // bInterfaceProtocol (1 = Keyboard, 2 = Mouse)
|
||||
0, // iInterface
|
||||
|
||||
9, // bLength
|
||||
0x21, // bDescriptorType (HID)
|
||||
0x10,0x01, // bcd 1.1
|
||||
0x00, //country code
|
||||
0x01, // Num descriptors
|
||||
0x22, // DescriptorType[0] (HID)
|
||||
sizeof(special_hid_desc), 0x00,
|
||||
|
||||
7, // endpoint descriptor (For endpoint 1)
|
||||
0x05, // Endpoint Descriptor (Must be 5)
|
||||
0x81, // Endpoint Address
|
||||
0x03, // Attributes
|
||||
0x01, 0x00, // Size (We aren't using it)
|
||||
100, // Interval (We don't use it.)
|
||||
};
|
||||
|
||||
#define STR_MANUFACTURER u"CNLohr"
|
||||
#define STR_PRODUCT u"RV003 RVSWDIO Programmer"
|
||||
#define STR_SERIAL u"RVSWDIO003-01"
|
||||
|
||||
struct usb_string_descriptor_struct {
|
||||
uint8_t bLength;
|
||||
uint8_t bDescriptorType;
|
||||
uint16_t wString[];
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string0 __attribute__((section(".rodata"))) = {
|
||||
4,
|
||||
3,
|
||||
{0x0409}
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string1 __attribute__((section(".rodata"))) = {
|
||||
sizeof(STR_MANUFACTURER),
|
||||
3,
|
||||
STR_MANUFACTURER
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string2 __attribute__((section(".rodata"))) = {
|
||||
sizeof(STR_PRODUCT),
|
||||
3,
|
||||
STR_PRODUCT
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string3 __attribute__((section(".rodata"))) = {
|
||||
sizeof(STR_SERIAL),
|
||||
3,
|
||||
STR_SERIAL
|
||||
};
|
||||
|
||||
// This table defines which descriptor data is sent for each specific
|
||||
// request from the host (in wValue and wIndex).
|
||||
const static struct descriptor_list_struct {
|
||||
uint32_t lIndexValue;
|
||||
const uint8_t *addr;
|
||||
uint8_t length;
|
||||
} descriptor_list[] = {
|
||||
{0x00000100, device_descriptor, sizeof(device_descriptor)},
|
||||
{0x00000200, config_descriptor, sizeof(config_descriptor)},
|
||||
// interface number // 2200 for hid descriptors.
|
||||
{0x00002200, special_hid_desc, sizeof(special_hid_desc)},
|
||||
{0x00002100, config_descriptor + 18, 9 }, // Not sure why, this seems to be useful for Windows + Android.
|
||||
|
||||
{0x00000300, (const uint8_t *)&string0, 4},
|
||||
{0x04090301, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)},
|
||||
{0x04090302, (const uint8_t *)&string2, sizeof(STR_PRODUCT)},
|
||||
{0x04090303, (const uint8_t *)&string3, sizeof(STR_SERIAL)}
|
||||
};
|
||||
#define DESCRIPTOR_LIST_ENTRIES ((sizeof(descriptor_list))/(sizeof(struct descriptor_list_struct)) )
|
||||
|
||||
#endif // INSTANCE_DESCRIPTORS
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,551 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
**/
|
||||
|
||||
|
||||
// NOT LORA!!!
|
||||
|
||||
// Transmit a sweep on 97.7MHz
|
||||
#define FM_TRANSMITTER_SWEEP
|
||||
|
||||
// Nothing = Transmit a 315MHz signal.
|
||||
|
||||
// XXX WARNING: Something is wrong with this -
|
||||
// The output isn't perfectly time aligned
|
||||
// And as such there are extra images in weird places.
|
||||
// TODO: Investigate the DMA+SPI Port jankyness.
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "LoRa-SDR-Code.h"
|
||||
|
||||
#ifdef LORAWAN
|
||||
#include "lorawan_simple.h"
|
||||
#endif
|
||||
|
||||
#define DMA_SIZE_WORDS 128
|
||||
|
||||
#define SENDBUFF_WORDS (DMA_SIZE_WORDS*2)
|
||||
uint8_t sendbuff[SENDBUFF_WORDS];
|
||||
|
||||
// Bits are shifted out MSBit first, then to LSBit
|
||||
|
||||
|
||||
#define MAX_BYTES 25
|
||||
#define MAX_SYMBOLS (MAX_BYTES*2+16)
|
||||
|
||||
// Our table is bespoke for the specific SF.
|
||||
#define CHIPSSPREAD CHIRPLENGTH_WORDS// QUARTER_CHIRP_LENGTH_WORDS (TODO: Use the quater value elsewhere in the code)
|
||||
#define MARK_FROM_SF0 (1<<SF_NUMBER) // SF7
|
||||
|
||||
#define PREAMBLE_CHIRPS 10
|
||||
#define CODEWORD_LENGTH 2
|
||||
|
||||
uint32_t quadsetcount;
|
||||
int16_t quadsets[MAX_SYMBOLS*4+PREAMBLE_CHIRPS*4+9+CODEWORD_LENGTH*4];
|
||||
int runningcount_bits = 0;
|
||||
volatile int fxcycle;
|
||||
volatile int quadsetplace = -1;
|
||||
volatile uint32_t temp;
|
||||
|
||||
#if 0
|
||||
|
||||
int16_t * AddChirp( int16_t * qso, int offset, int verneer )
|
||||
{
|
||||
offset = offset * CHIPSSPREAD / (MARK_FROM_SF0);
|
||||
offset += verneer;
|
||||
*(qso++) = (CHIPSSPREAD * 0 / 4 + offset + CHIPSSPREAD ) % CHIPSSPREAD;
|
||||
*(qso++) = (CHIPSSPREAD * 1 / 4 + offset + CHIPSSPREAD ) % CHIPSSPREAD;
|
||||
*(qso++) = (CHIPSSPREAD * 2 / 4 + offset + CHIPSSPREAD ) % CHIPSSPREAD;
|
||||
*(qso++) = (CHIPSSPREAD * 3 / 4 + offset + CHIPSSPREAD ) % CHIPSSPREAD;
|
||||
return qso;
|
||||
}
|
||||
|
||||
// This IRQ is called periodically to fill the output buffer that is shifted to SPI
|
||||
void DMA1_Channel3_IRQHandler( void ) __attribute__((interrupt)) __attribute__((section(".srodata")));
|
||||
void DMA1_Channel3_IRQHandler( void )
|
||||
{
|
||||
//GPIOD->BSHR = 1; // Turn on GPIOD0 for profiling
|
||||
|
||||
// Backup flags.
|
||||
volatile int intfr = DMA1->INTFR;
|
||||
do
|
||||
{
|
||||
// Clear all possible flags.
|
||||
DMA1->INTFCR = DMA1_IT_GL3;
|
||||
|
||||
|
||||
//int place = DMA1_Channel3->CNTR;
|
||||
// CNTR says that there are THIS MANY bytes left in the transfer.
|
||||
// So a high CNTR value indicates a very early place in the buffer.
|
||||
|
||||
uint16_t * sb = 0;
|
||||
|
||||
temp++;
|
||||
|
||||
if( intfr & DMA1_IT_HT3 )
|
||||
{
|
||||
sb = sendbuff;
|
||||
}
|
||||
else if( intfr & DMA1_IT_TC3 )
|
||||
{
|
||||
sb = sendbuff + SENDBUFF_WORDS/2;
|
||||
}
|
||||
|
||||
if( sb )
|
||||
{
|
||||
if( quadsetplace < 0 )
|
||||
{
|
||||
// Abort Send
|
||||
memset( sb, 0, SENDBUFF_WORDS*2/2 );
|
||||
DMA1_Channel3->CFGR &= ~DMA_CFGR1_EN;
|
||||
goto complete;
|
||||
}
|
||||
|
||||
fxcycle += DMA_SIZE_WORDS;
|
||||
if( fxcycle == NUM_DMAS_PER_QUARTER_CHIRP*DMA_SIZE_WORDS )
|
||||
{
|
||||
fxcycle = 0;
|
||||
// Advance to next quarter word.
|
||||
quadsetplace++;
|
||||
|
||||
if( quadsetplace > quadsetcount )
|
||||
{
|
||||
#ifdef TEST_TONE
|
||||
quadsetplace = 0;
|
||||
#else
|
||||
quadsetplace = -1;
|
||||
#endif
|
||||
memset( sb, 0, SENDBUFF_WORDS*2/2 );
|
||||
goto complete;
|
||||
}
|
||||
}
|
||||
|
||||
int symbol = quadsets[quadsetplace]; // Actually 0...CHIRPLENGTHWORDS
|
||||
|
||||
const uint16_t * tsb = 0;
|
||||
|
||||
// Select down- or up-chirp.
|
||||
if( symbol < 0 )
|
||||
{
|
||||
int word = fxcycle - symbol - 1;
|
||||
if( word >= CHIRPLENGTH_WORDS ) word -= CHIRPLENGTH_WORDS;
|
||||
word++;
|
||||
tsb = (&chirpbuff[word+REVERSE_START_OFFSET_BYTES/4]);
|
||||
}
|
||||
else
|
||||
{
|
||||
int word = fxcycle + symbol;
|
||||
if( word >= CHIRPLENGTH_WORDS ) word -= CHIRPLENGTH_WORDS;
|
||||
tsb = (&chirpbuff[word]);
|
||||
}
|
||||
|
||||
// I tried using the DMA to do the copy - but that didn't work for some reason.
|
||||
//while( DMA1_Channel5->CFGR & 1 );
|
||||
// DMA1_Channel5->CNTR = DMA_SIZE_WORDS/2;
|
||||
// DMA1_Channel5->MADDR = (uint32_t)tsb;
|
||||
// DMA1_Channel5->PADDR = (uint32_t)sb;
|
||||
// DMA1_Channel5->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
int cpy = DMA_SIZE_WORDS/2;
|
||||
#ifdef TEST_TONE
|
||||
// Test tone
|
||||
memset( sb, 0xaa, cpy*2 );
|
||||
#else
|
||||
#if DMA_SIZE_WORDS_DIVISIBLE_BY_FOUR == 0
|
||||
#error need divisibiltiy by 2.
|
||||
#else
|
||||
//while( cpy-- ) { *(sb++) = wordo; }
|
||||
// Guarantee aligned access.
|
||||
uint32_t * sbw = (uint32_t*)(((uint32_t)sb)&~3);
|
||||
uint32_t * tsbw = (uint32_t*)(((uint32_t)tsb)&~3);
|
||||
//while( cpy-- ) { *(sbw++) = *(tsbw++); }
|
||||
|
||||
// Align the data copy if needed
|
||||
if( cpy & 1 )
|
||||
{
|
||||
*(sbw++) = *(tsbw++);
|
||||
}
|
||||
cpy /= 2; // Doubled up per loop
|
||||
asm volatile("\
|
||||
1:\
|
||||
c.lw a3, 0(%[from])\n\
|
||||
c.lw a4, 4(%[from])\n\
|
||||
c.addi %[from], 8\n\
|
||||
c.addi %[cpy], -1\n\
|
||||
c.sw a3, 0(%[to])\n\
|
||||
c.sw a4, 4(%[to])\n\
|
||||
c.addi %[to], 8\n\
|
||||
c.bnez %[cpy], 1b\n\
|
||||
" : [cpy]"+r"(cpy), [from]"+r"(tsbw), [to]"+r"(sbw) : : "a3", "a4", "memory");
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
complete:
|
||||
intfr = DMA1->INTFR;
|
||||
} while( intfr );
|
||||
|
||||
//GPIOD->BSHR = 1<<16; // Turn off GPIOD0 for profiling
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
void LoopFunction() __attribute__((section(".srodata")));
|
||||
void LoopFunction()
|
||||
{
|
||||
uint8_t * start = (uint8_t*)DMA1_Channel5->MADDR;
|
||||
uint8_t * end = (uint8_t*)((uint32_t)DMA1_Channel5->MADDR + SENDBUFF_WORDS);
|
||||
uint8_t * here = start+ 8;
|
||||
uint32_t targ = 2000;
|
||||
uint32_t running = 0;
|
||||
uint8_t * tail = end - DMA1_Channel5->CNTR;
|
||||
uint32_t * cntr = DMA1_Channel5->CNTR;
|
||||
uint32_t temp = 0;
|
||||
uint32_t temp2 = 0;
|
||||
|
||||
asm volatile("\n\
|
||||
li %[targ], 2000\n\
|
||||
genloop:\n\
|
||||
lw %[temp], 0(%[cntr])\n\
|
||||
sub %[tail], %[end], %[temp]\n\
|
||||
beq %[here], %[tail], genloop\n\
|
||||
innerloop:\
|
||||
li %[temp], 17\n\
|
||||
blt %[running], %[targ], noskip\n\
|
||||
li %[temp], 18\n\
|
||||
sub %[running], %[running], %[targ]\n\
|
||||
noskip:\n\
|
||||
sb %[temp], 0(%[here])\n\
|
||||
addi %[here], %[here], 1\n\
|
||||
bne %[here], %[end], skipreset\n\
|
||||
add %[here], x0, %[start]\n\
|
||||
skipreset:\n\
|
||||
bne %[here], %[tail], innerloop\n\
|
||||
j genloop\n\
|
||||
" : [here]"+r"(here) :
|
||||
[start]"r"(start),
|
||||
[end]"r"(end),
|
||||
[targ]"r"(targ),
|
||||
[running]"r"(running),
|
||||
[tail]"r"(tail),
|
||||
[cntr]"r"(cntr),
|
||||
[temp]"r"(temp),
|
||||
[temp2]"r"(temp2) );
|
||||
|
||||
/*
|
||||
while(1)
|
||||
{
|
||||
int targ_f = 2000; //(frameno & 511)*9 + 1700;
|
||||
int run_f = 0;
|
||||
uint8_t * tail = end - DMA1_Channel5->CNTR;
|
||||
|
||||
while( here != tail )
|
||||
{
|
||||
int setf = 17;
|
||||
if( run_f > targ_f )
|
||||
{
|
||||
setf = 18;
|
||||
run_f -= targ_f;
|
||||
}
|
||||
run_f += setf*32;
|
||||
|
||||
*here = setf;
|
||||
|
||||
here++;
|
||||
}
|
||||
*/
|
||||
/*
|
||||
for( j = 0; j < sizeof( sendbuff ); j++ )
|
||||
{
|
||||
int setf = 10;
|
||||
if( run_f > targ_f )
|
||||
{
|
||||
setf = 9;
|
||||
run_f -= targ_f;
|
||||
}
|
||||
run_f += setf*32;
|
||||
|
||||
sendbuff[j] = setf;
|
||||
}
|
||||
*/
|
||||
}
|
||||
void LoopFunction2() __attribute__((aligned(256))) __attribute__((section(".srodata"))) __attribute__ ((noinline));
|
||||
|
||||
__attribute__((section(".sdata"))) __attribute__((aligned(256))) const uint32_t tablef[] = {
|
||||
0x06060606,
|
||||
0x06060607,
|
||||
0x06070607,
|
||||
0x07070706,
|
||||
0x07070707,
|
||||
0x07070708,
|
||||
0x07080708,
|
||||
0x08080807,
|
||||
0x08080808,
|
||||
0x08080809,
|
||||
0x08090809,
|
||||
0x09090908,
|
||||
0x09090909,
|
||||
0x0909090a,
|
||||
0x090a090a,
|
||||
0x0a0a0a09,
|
||||
0x0a0a0a0a, // Below this line is unstable - i.e. sometimes there are missing DMA transfers.
|
||||
0x0a0a0a0b,
|
||||
0x0a0b0a0b,
|
||||
0x0b0b0b0a,
|
||||
0x0b0b0b0b,
|
||||
0x0b0b0b0c,
|
||||
0x0b0c0b0c,
|
||||
0x0c0c0c0b,
|
||||
0x0c0c0c0c,
|
||||
0x0c0c0c0d,
|
||||
0x0c0d0c0d,
|
||||
0x0d0d0d0c,
|
||||
0x0d0d0d0d,
|
||||
0x0d0d0d0e,
|
||||
0x0d0e0d0e,
|
||||
0x0e0e0e0d,
|
||||
0x0e0e0e0e,
|
||||
0x0e0e0e0f,
|
||||
0x0e0f0e0f,
|
||||
0x0f0f0f0e,
|
||||
0x0f0f0f0f,
|
||||
0x0f0f0f10,
|
||||
0x0f100f10,
|
||||
0x1010100f,
|
||||
0x10101010,
|
||||
0x10101011,
|
||||
0x10111011,
|
||||
0x11111110,
|
||||
};
|
||||
|
||||
void LoopFunction2()
|
||||
{
|
||||
|
||||
uint32_t * start = (uint8_t*)DMA1_Channel5->MADDR;
|
||||
uint32_t * end = (uint8_t*)((uint32_t)DMA1_Channel5->MADDR + SENDBUFF_WORDS);
|
||||
uint32_t * here = start;
|
||||
|
||||
int run_f = 0;
|
||||
|
||||
volatile uint32_t * cntrptr = &DMA1_Channel5->CNTR;
|
||||
|
||||
while(1)
|
||||
{
|
||||
//uint32_t * tail = 0xfffffffc & (uintptr_t)(((uint8_t*)end) - *cntrptr);
|
||||
//if( tail == end ) tail--;
|
||||
uint32_t * tail = ((SENDBUFF_WORDS-1) & (0xfffffffc)) & (uintptr_t)(((uint8_t*)start) + SENDBUFF_WORDS - *cntrptr);
|
||||
|
||||
while( here != tail )
|
||||
{
|
||||
#ifdef FM_TRANSMITTER_SWEEP
|
||||
// 97.7MHz FM Station
|
||||
int notein = (SysTick->CNT>>3)&0x1fff;
|
||||
if( notein > 0xfff ) notein = 0x2000-notein;
|
||||
uint32_t cp = (notein)+0x20000;
|
||||
#else
|
||||
// 315MHz
|
||||
uint32_t cp = 0x1bfc3;
|
||||
#endif
|
||||
*(here++) = tablef[run_f>>12];
|
||||
run_f &= (1<<12)-1;
|
||||
run_f += cp;
|
||||
if( here == end )
|
||||
here = start;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
funGpioInitAll();
|
||||
|
||||
// Set a wait state (1 = normal <= 48MHz)
|
||||
FLASH->ACTLR = 1;
|
||||
|
||||
// MCO for testing.
|
||||
// funPinMode( PA8, GPIO_CFGLR_OUT_50Mhz_AF_PP ); RCC->CFGR0 |= RCC_CFGR0_MCO_PLL;
|
||||
|
||||
// printf( "Switching to HSE\n" );
|
||||
Delay_Ms( 10 );
|
||||
|
||||
// Disable clock security system.
|
||||
RCC->CTLR &= ~RCC_CSSON;
|
||||
|
||||
// Enable external crystal
|
||||
RCC->CTLR |= RCC_HSEON;
|
||||
|
||||
// XXX NOTE: This is only used if you have a clock, not an oscillator.
|
||||
// RCC->CTLR |= RCC_HSEBYP;
|
||||
|
||||
// Set System Clock Source to be 0.
|
||||
RCC->CFGR0 = (RCC->CFGR0 & ~RCC_SW) | 0;
|
||||
|
||||
// Disable PLL
|
||||
RCC->CTLR &= ~RCC_PLLON;
|
||||
|
||||
// Switch to HSE
|
||||
RCC->CFGR0 |= RCC_PLLSRC;
|
||||
|
||||
// Enable PLL
|
||||
RCC->CTLR |= RCC_PLLON;
|
||||
|
||||
// Wait for HSE to become ready.
|
||||
while( !( RCC->CTLR & RCC_HSERDY) );
|
||||
while( !( RCC->CTLR & RCC_PLLRDY) );
|
||||
|
||||
RCC->CFGR0 |= RCC_SW_1; // Switch system clock to PLL
|
||||
// printf( "HSE Switched\n" );
|
||||
Delay_Ms( 10 );
|
||||
RCC->CTLR &= ~RCC_HSION;
|
||||
Delay_Ms( 10 );
|
||||
//printf( "HSI Off [%08lx %08lx]\n", RCC->CTLR, RCC->CFGR0 ); HSI Off [03035180 0001000a]
|
||||
|
||||
RCC->APB2PCENR |= RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOC |
|
||||
RCC_APB2Periph_TIM1;
|
||||
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
funPinMode( PC3, GPIO_CFGLR_OUT_50Mhz_AF_PP ); // T1C3 on PC3
|
||||
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_TIM1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_TIM1;
|
||||
|
||||
|
||||
// Prescaler
|
||||
TIM1->PSC = 0x0000;
|
||||
|
||||
// Auto Reload - sets period
|
||||
TIM1->ATRLR = 17;
|
||||
|
||||
// Reload immediately
|
||||
TIM1->SWEVGR |= TIM_UG;
|
||||
|
||||
// Enable CH1N output, positive pol
|
||||
TIM1->CCER |= TIM_CC3E;
|
||||
TIM1->CCER |= TIM_CC1E;
|
||||
|
||||
// Compare 3 = for output
|
||||
// Modes:
|
||||
// 0, 1, 2: Nothing
|
||||
// 3: Flip
|
||||
// 4, 5: Nothing
|
||||
// 6: "Fast PWM mode 1"
|
||||
// 7: Flipping (Further out)
|
||||
#ifdef FM_TRANSMITTER_SWEEP
|
||||
TIM1->CHCTLR2 = TIM_OC3M_0 | TIM_OC3M_1 | TIM_OC3PE | TIM_OC3FE;
|
||||
#else
|
||||
TIM1->CHCTLR2 = TIM_OC3M_2 | TIM_OC3M_1 | TIM_OC3PE | TIM_OC3FE;
|
||||
#endif
|
||||
|
||||
// Compare 1 = for triggering
|
||||
TIM1->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1FE;
|
||||
|
||||
// Set the Capture Compare Register value to 50% initially
|
||||
TIM1->CH3CVR = 4; // ACTUALLY Ignored typically it seems.
|
||||
TIM1->CH1CVR = 0; // This triggers DMA.
|
||||
|
||||
// Enable TIM1 outputs
|
||||
TIM1->BDTR |= TIM_MOE;
|
||||
|
||||
// Enable TIM1
|
||||
TIM1->CTLR1 |= TIM_CEN;
|
||||
|
||||
TIM1->DMAINTENR = TIM_TDE | TIM_UDE; // Outputs DMA1_Channel5
|
||||
|
||||
#if 0
|
||||
// Another try - use TIM2 to trigger DMA?
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
RCC->APB1PRSTR |= RCC_APB1Periph_TIM2;
|
||||
RCC->APB1PRSTR &= ~RCC_APB1Periph_TIM2;
|
||||
|
||||
TIM2->PSC = 0x0000;
|
||||
TIM2->ATRLR = 37;
|
||||
TIM2->SWEVGR |= TIM_UG;
|
||||
TIM2->BDTR |= TIM_MOE;
|
||||
TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1FE;
|
||||
TIM2->DMAINTENR |= TIM_UDE | TIM_TDE | TIM_TDE | TIM_CC1DE;
|
||||
TIM2->CTLR1 |= TIM_CEN;
|
||||
// TIM2_UP = DMA Channel 2.
|
||||
#endif
|
||||
|
||||
DMA1_Channel5->PADDR = (uint32_t)&TIM1->CH3CVR;
|
||||
DMA1_Channel5->MADDR = (uint32_t)sendbuff;
|
||||
DMA1_Channel5->CNTR = 0;// sizeof( bufferset )/2; // Number of unique copies. (Don't start, yet!)
|
||||
DMA1_Channel5->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_VeryHigh |
|
||||
DMA_PeripheralDataSize_HalfWord |
|
||||
DMA_MemoryDataSize_Byte |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Circular | // OR DMA_Mode_Circular or DMA_Mode_Normal
|
||||
DMA_DIR_PeripheralDST |
|
||||
0;
|
||||
//DMA_IT_TC | DMA_IT_HT; // Transmission Complete + Half Empty Interrupts.
|
||||
|
||||
// NVIC_EnableIRQ( DMA1_Channel3_IRQn );
|
||||
|
||||
int j;
|
||||
for( j = 0; j < sizeof( sendbuff ); j++ )
|
||||
{
|
||||
sendbuff[j] = 12;
|
||||
}
|
||||
|
||||
|
||||
// Enter critical section.
|
||||
DMA1_Channel5->MADDR = (uint32_t)sendbuff;
|
||||
DMA1_Channel5->CNTR = SENDBUFF_WORDS; // Number of unique uint16_t entries.
|
||||
DMA1_Channel5->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
|
||||
LoopFunction2();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
Trying to use a plain 003 to send and receive (one for each).
|
||||
|
||||
One generates a 12MHz tone.
|
||||
|
||||
The other samples at 48/47MHz.
|
||||
|
||||
This doesn't particularly work well.
|
||||
|
||||
It only goes about 1'
|
||||
@@ -0,0 +1,13 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=ch32v003rx
|
||||
TARGET_MCU:=CH32V003
|
||||
CH32V003FUN:=../../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_CFLAGS:=-Wno-unused-function -I../../lib
|
||||
|
||||
include $(CH32V003FUN)/ch32v003fun.mk
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
**/
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#define ADC_NUMCHLS 1
|
||||
#define DMA_SIZE 512
|
||||
|
||||
#define ADC_PIN PC4
|
||||
#define ADCNO 2
|
||||
|
||||
#define LEDPIN PD6
|
||||
|
||||
#define USE_TIMER
|
||||
|
||||
uint32_t dmadata[DMA_SIZE/2] __attribute__((aligned(64)));
|
||||
|
||||
|
||||
uint32_t ercnt = 0;
|
||||
|
||||
#define IQDLEN 32
|
||||
int32_t lastintenR[IQDLEN], lastintenI[IQDLEN];
|
||||
uint32_t intenhead;
|
||||
uint32_t intentail;
|
||||
|
||||
uint32_t wordouts;
|
||||
|
||||
void DMA1_Channel1_IRQHandler( void ) __attribute__((interrupt));
|
||||
void DMA1_Channel1_IRQHandler( void )
|
||||
{
|
||||
DMA1_Channel1->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
// Clear all possible flags.
|
||||
DMA1->INTFCR = DMA1_IT_GL1;
|
||||
uint32_t * head = dmadata;
|
||||
uint32_t * end = dmadata + DMA_SIZE/2;
|
||||
static uint32_t * here = dmadata;
|
||||
static uint32_t thisintenR;
|
||||
static uint32_t thisintenI;
|
||||
static uint32_t rcnt;
|
||||
|
||||
// We have a pointer to the next data we want to analyize.
|
||||
// We have a pointer to where the tail of the new data is.
|
||||
// We want to process data from where we are to where the
|
||||
// data ends.
|
||||
// So, we set and end point, which could be either the end
|
||||
// of where the data is or the end of the array with the
|
||||
// data.
|
||||
// Then we plow through the data until we get to one of those
|
||||
// two. And we either reset the pointer to the beginning of
|
||||
// the array, OR, we stop because we ran out of data.
|
||||
|
||||
uint32_t cnt = DMA1_Channel1->CNTR;
|
||||
if( cnt == 0 ) cnt = 1;
|
||||
uint32_t tail_offset = DMA_SIZE - cnt;
|
||||
uint32_t * tail = dmadata + tail_offset/2; // Tuncate down to quads if a pair has not been fully written.
|
||||
uint32_t * stopat = (here < tail) ? tail : end;
|
||||
|
||||
do
|
||||
{
|
||||
do
|
||||
{
|
||||
int32_t vA = *(here++);
|
||||
int32_t vB = *(here++);
|
||||
thisintenR += (vA&0xfff) - (vB&0xfff);
|
||||
thisintenI += (vA >> 16) - (vB >> 16);
|
||||
rcnt++;
|
||||
} while( here != stopat );
|
||||
|
||||
|
||||
if( here == end )
|
||||
{
|
||||
lastintenR[intenhead] = thisintenR; // Fixup (because when we were subtracting, it should be -1)
|
||||
lastintenI[intenhead] = thisintenI; // Fixup (because when we were subtracting, it should be -1)
|
||||
|
||||
intenhead = (intenhead+1) & (IQDLEN-1);
|
||||
|
||||
thisintenR = 0;
|
||||
thisintenI = 0;
|
||||
here = head;
|
||||
ercnt = rcnt;
|
||||
rcnt = 0;
|
||||
wordouts++;
|
||||
}
|
||||
|
||||
if( here == tail ) break;
|
||||
}
|
||||
while( 1 );
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
Delay_Ms( 100 );
|
||||
|
||||
EXTEND->CTR = 1<<10; // LDO trim
|
||||
|
||||
funGpioInitAll();
|
||||
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
RCC->APB2PCENR |= RCC_APB2Periph_ADC1;
|
||||
|
||||
// Reset the ADC to init all regs
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_ADC1;
|
||||
|
||||
ADC1->RSQR1 = (1-1) << 20; // One channel.
|
||||
ADC1->RSQR2 = 0;
|
||||
ADC1->RSQR3 = (ADCNO<<(5*0));
|
||||
|
||||
// set sampling time for chl 7, 4, 3, 2
|
||||
// 0:7 => 3/9/15/30/43/57/73/241 cycles
|
||||
#ifdef USE_TIMER
|
||||
ADC1->SAMPTR2 = (1<<(3*ADCNO));
|
||||
#else
|
||||
ADC1->SAMPTR2 = (3<<(3*ADCNO));
|
||||
#endif
|
||||
|
||||
// turn on ADC
|
||||
ADC1->CTLR2 = ADC_ADON;
|
||||
|
||||
// Reset calibration
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_RSTCAL;
|
||||
while(ADC1->CTLR2 & ADC_RSTCAL);
|
||||
|
||||
// Calibrate
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_CAL;
|
||||
while(ADC1->CTLR2 & ADC_CAL);
|
||||
|
||||
// Turn on DMA
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
//DMA1_Channel1 is for ADC
|
||||
DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR;
|
||||
DMA1_Channel1->MADDR = (uint32_t)dmadata;
|
||||
DMA1_Channel1->CNTR = DMA_SIZE;
|
||||
DMA1_Channel1->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_VeryHigh |
|
||||
DMA_MemoryDataSize_HalfWord |
|
||||
DMA_PeripheralDataSize_HalfWord |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Circular |
|
||||
DMA_DIR_PeripheralSRC |
|
||||
DMA_IT_TC | DMA_IT_HT; // Transmission Complete + Half Empty Interrupts.
|
||||
|
||||
// NVIC_SetPriority( DMA1_Channel3_IRQn, 0<<4 ); //We don't need to tweak priority.
|
||||
NVIC_EnableIRQ( DMA1_Channel1_IRQn );
|
||||
DMA1_Channel1->CFGR |= DMA_CFGR1_EN; // Turn on DMA channel 1
|
||||
|
||||
ADC1->CTLR1 = ADC_SCAN; // enable scanning
|
||||
// Enable continuous conversion and DMA, selected by TIM2CC1
|
||||
#ifdef USE_TIMER
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_DMA | ADC_EXTSEL_2 | ADC_EXTTRIG;
|
||||
#else
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_DMA | ADC_EXTSEL | ADC_SWSTART | ADC_CONT;
|
||||
#endif
|
||||
|
||||
// Reset TIM2 to init all regs
|
||||
RCC->APB1PRSTR |= RCC_APB1Periph_TIM2;
|
||||
RCC->APB1PRSTR &= ~RCC_APB1Periph_TIM2;
|
||||
|
||||
#ifdef USE_TIMER
|
||||
|
||||
TIM2->PSC = 0x0000; // Prescalar
|
||||
TIM2->ATRLR = 46; // TIM2 max before reset. 48 = Period of 49 cycles.
|
||||
TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE;
|
||||
TIM2->CTLR1 = TIM_ARPE;
|
||||
TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP;
|
||||
TIM2->SWEVGR = TIM_UG;
|
||||
|
||||
// Enable TIM2 (T2C1 = Trigger ADC)
|
||||
TIM2->CTLR1 |= TIM_CEN;
|
||||
TIM2->CH1CVR = 1;
|
||||
|
||||
#endif
|
||||
|
||||
// PD4 = T2C1
|
||||
funPinMode( LEDPIN, GPIO_CFGLR_OUT_50Mhz_PP );
|
||||
//funPinMode( PD4, GPIO_CFGLR_OUT_50Mhz_AF_PP );
|
||||
|
||||
funPinMode( ADC_PIN,
|
||||
//GPIO_CFGLR_IN_PUPD
|
||||
GPIO_CFGLR_IN_ANALOG
|
||||
);
|
||||
|
||||
while(1)
|
||||
{
|
||||
printf( "%5d %5d %ld %ld %ld %ld\n", (int)lastintenR[intenhead], (int)lastintenI[intenhead], dmadata[0]&0xfff, dmadata[0]>>16, dmadata[1]&0xfff, dmadata[1]>>16 );
|
||||
|
||||
int i;
|
||||
int32_t lR[8], lI[8];
|
||||
int head = (intenhead - 8) & (IQDLEN-1);
|
||||
for( i = 0; i < 8; i++ )
|
||||
{
|
||||
lR[i] = lastintenR[head];
|
||||
lI[i] = lastintenI[head];
|
||||
head = (head+1)&(IQDLEN-1);
|
||||
}
|
||||
|
||||
for( i = 0; i < 8; i++ )
|
||||
{
|
||||
printf( "%6ld%6ld\n", lR[i], lI[i] );
|
||||
}
|
||||
|
||||
printf( "%08lx %ld ** %d\n", dmadata[0], wordouts, ercnt );
|
||||
Delay_Ms( 1000 );
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=ch32v003tx
|
||||
TARGET_MCU:=CH32V003
|
||||
CH32V003FUN:=../../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_CFLAGS:=-Wno-unused-function -I../../lib
|
||||
|
||||
include $(CH32V003FUN)/ch32v003fun.mk
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
**/
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#define LEDPIN PD6
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
Delay_Ms( 100 );
|
||||
|
||||
funGpioInitAll();
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
// PD4 = T2C1
|
||||
funPinMode( PD4, GPIO_CFGLR_OUT_50Mhz_AF_PP );
|
||||
funPinMode( LEDPIN, GPIO_CFGLR_OUT_50Mhz_PP );
|
||||
|
||||
// Reset TIM2 to init all regs
|
||||
RCC->APB1PRSTR |= RCC_APB1Periph_TIM2;
|
||||
RCC->APB1PRSTR &= ~RCC_APB1Periph_TIM2;
|
||||
|
||||
TIM2->PSC = 0x0000; // Prescalar
|
||||
TIM2->ATRLR = 3; // Max
|
||||
TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE | TIM_OC1FE;
|
||||
TIM2->CTLR1 = TIM_ARPE;
|
||||
TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP;
|
||||
TIM2->SWEVGR = TIM_UG;
|
||||
|
||||
// Enable TIM2
|
||||
TIM2->CTLR1 |= TIM_CEN;
|
||||
TIM2->CH1CVR = TIM2->ATRLR/2;
|
||||
|
||||
while(1);
|
||||
|
||||
while(1)
|
||||
{
|
||||
TIM2->CH1CVR = 2;
|
||||
TIM2->CCER = TIM_CC1E | TIM_CC1P;
|
||||
funDigitalWrite( LEDPIN, 1 );
|
||||
Delay_Us( 1500 );
|
||||
TIM2->CCER = TIM_CC1E;
|
||||
TIM2->CH1CVR = 2;
|
||||
funDigitalWrite( LEDPIN, 0 );
|
||||
Delay_Us( 1500 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
|
||||
#endif
|
||||
|
||||
+1
-1
Submodule ch32v/ch32v003fun updated: 397bad7576...f41db0dc30
@@ -0,0 +1,15 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=adcrx
|
||||
TARGET_MCU:=CH32V203G6U6
|
||||
TARGET_MCU_PACKAGE:=CH32V203G6U6
|
||||
CH32V003FUN:=../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_CFLAGS:=-Wno-unused-function -I../../lib
|
||||
|
||||
include ../ch32v003fun/ch32v003fun/ch32v003fun.mk
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
rm -rf rf_data_gen chirpbuff.dat chirpbuff.h chirpbuffinfo.h
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
**/
|
||||
|
||||
// NOT LORA!!! -- but experimenting with the possibility of rx.
|
||||
|
||||
// SETUP INSTRUCTIONS:
|
||||
// (1) `make` in the optionbytes folder to configure `RESET` correctly.
|
||||
// (2) Create a tone (if using the funprog, ../ch32v003fun/minichlink/minichlink -X ECLK 1:235:189:9:3 for 27.48387097MHz
|
||||
// (2) or, for 24.387096762MHz - ../ch32v003fun/minichlink/minichlink -X ECLK 1:150:49:8:3
|
||||
|
||||
/* More notes
|
||||
|
||||
* Minimum sample time with DMA = fCPU / 28 (5.14MHz)
|
||||
|
||||
*/
|
||||
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
|
||||
/* General note:
|
||||
*/
|
||||
|
||||
#define Q 1024
|
||||
|
||||
#define PWM_PERIOD (36-1) //For 27.0MHz -- It appears to be good for *244 in the table? WHY 26MHz???!?!!?
|
||||
#define TIGHT_OUT 1
|
||||
#define QUADRATURE
|
||||
//#define DUMPBUFF
|
||||
|
||||
//#define PWM_PERIOD (32-1)
|
||||
//#define QUADRATURE
|
||||
//#define PWM_OUTPUT 3
|
||||
|
||||
#define ADC_BUFFSIZE 256
|
||||
volatile uint16_t adc_buffer[ADC_BUFFSIZE];
|
||||
|
||||
void SetupADC()
|
||||
{
|
||||
// XXX TODO -look into PGA
|
||||
// XXX TODO - look into BUFEN and TKITUNE
|
||||
// XXX TODO - Look into tag-teaming the ADCs
|
||||
|
||||
// PDA is analog input chl 7
|
||||
GPIOA->CFGLR &= ~(0xf<<(4*7)); // CNF = 00: Analog, MODE = 00: Input
|
||||
|
||||
// ADC CLK is chained off of APB2.
|
||||
|
||||
// Reset the ADC to init all regs
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_ADC1;
|
||||
|
||||
// ADCCLK = 12 MHz => RCC_ADCPRE divide by 4
|
||||
RCC->CFGR0 &= ~RCC_ADCPRE; // Clear out the bis in case they were set
|
||||
RCC->CFGR0 |= RCC_ADCPRE_DIV2; // Fastest possible (divide-by-2) NOTE: This is OUTSIDE the specified value in the datasheet.
|
||||
|
||||
// Set up single conversion on chl 7
|
||||
ADC1->RSQR1 = 0;
|
||||
ADC1->RSQR2 = 0;
|
||||
ADC1->RSQR3 = 7; // 0-9 for 8 ext inputs and two internals
|
||||
|
||||
// Not using injection group.
|
||||
|
||||
// Sampling time for channels. Careful: This has PID tuning implications.
|
||||
// Note that with 3 and 3,the full loop (and injection) runs at 138kHz.
|
||||
ADC1->SAMPTR2 = (0<<(3*7));
|
||||
|
||||
// Turn on ADC and set rule group to sw trig
|
||||
// 0 = Use TRGO event for Timer 1 to fire ADC rule.
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_EXTTRIG | ADC_DMA;
|
||||
|
||||
// Reset calibration
|
||||
ADC1->CTLR2 |= ADC_RSTCAL;
|
||||
while(ADC1->CTLR2 & ADC_RSTCAL);
|
||||
|
||||
// Calibrate ADC
|
||||
ADC1->CTLR2 |= ADC_CAL;
|
||||
while(ADC1->CTLR2 & ADC_CAL);
|
||||
|
||||
// ADC_SCAN: Allow scanning.
|
||||
ADC1->CTLR1 = /*ADC_Pga_64 | */ADC_SCAN;
|
||||
|
||||
|
||||
// Turn on DMA
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
//DMA1_Channel1 is for ADC
|
||||
DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR;
|
||||
DMA1_Channel1->MADDR = (uint32_t)adc_buffer;
|
||||
DMA1_Channel1->CNTR = ADC_BUFFSIZE;
|
||||
DMA1_Channel1->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_VeryHigh |
|
||||
DMA_MemoryDataSize_HalfWord |
|
||||
DMA_PeripheralDataSize_HalfWord |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Circular |
|
||||
DMA_DIR_PeripheralSRC;
|
||||
|
||||
// Turn on DMA channel 1
|
||||
DMA1_Channel1->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
// Enable continuous conversion and DMA
|
||||
ADC1->CTLR2 |= ADC_DMA; // | ADC_CONT;
|
||||
|
||||
// start conversion
|
||||
ADC1->CTLR2 |= ADC_SWSTART;// | ADC_CONT;
|
||||
|
||||
}
|
||||
|
||||
static void SetupTimer1()
|
||||
{
|
||||
// Enable Timer 1
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_TIM1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_TIM1;
|
||||
|
||||
TIM1->PSC = 0; // Prescalar to 0x0000 (so, 48MHz base clock)
|
||||
TIM1->ATRLR = PWM_PERIOD;
|
||||
|
||||
#ifdef PWM_OUTPUT
|
||||
// PA10 = T1CH3.
|
||||
GPIOA->CFGHR &= ~(0xf<<(4*2));
|
||||
GPIOA->CFGHR |= (GPIO_Speed_10MHz | GPIO_CNF_OUT_PP_AF)<<(4*2);
|
||||
|
||||
TIM1->CCER = TIM_CC3E | TIM_CC3P;
|
||||
TIM1->CHCTLR2 = TIM_OC3M_2 | TIM_OC3M_1;
|
||||
TIM1->CH3CVR = 5; // Actual duty cycle (Off to begin with)
|
||||
#endif
|
||||
|
||||
TIM1->CCER = TIM_CC1E;
|
||||
TIM1->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1;
|
||||
TIM1->CH1CVR = 1;
|
||||
|
||||
// Setup TRGO to trigger for ADC (NOTE: Not on the 203! TIM1_TRGO is only connected to injection)
|
||||
//TIM1->CTLR2 = TIM_MMS_1;
|
||||
|
||||
// Enable TIM1 outputs
|
||||
TIM1->BDTR = TIM_MOE;
|
||||
TIM1->CTLR1 = TIM_CEN;
|
||||
}
|
||||
|
||||
|
||||
void InnerLoop() __attribute__((noreturn));
|
||||
|
||||
|
||||
void InnerLoop()
|
||||
{
|
||||
int i = 0;
|
||||
int q = 0;
|
||||
int tpl = 0;
|
||||
|
||||
// Timer goes backwards when we are moving forwards.
|
||||
volatile uint16_t * adc_buffer_end = 0;
|
||||
volatile uint16_t * adc_buffer_top = adc_buffer + ADC_BUFFSIZE;
|
||||
volatile uint16_t * adc = adc_buffer;
|
||||
|
||||
int frcnt = 0;
|
||||
|
||||
int tstart = 0;
|
||||
|
||||
#ifdef DUMPBUFF
|
||||
uint16_t shadowbuff[Q+16];
|
||||
int shadowplace = 0;
|
||||
#define SHADOWSTORE(X) shadowbuff[frcnt+X] = t;
|
||||
#else
|
||||
#define SHADOWSTORE(X)
|
||||
#endif
|
||||
|
||||
while( 1 )
|
||||
{
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR; // Warning, sometimes this is == to the base, or == 0 (i.e. might be 256, if top is 255)
|
||||
if( tpl == ADC_BUFFSIZE ) tpl = 0;
|
||||
|
||||
adc_buffer_end = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
//printf( "%3d %4d %d %04x\n", DMA1_Channel1->CNTR, TIM1->CNT, ADC1->RDATAR, ADC1->STATR );
|
||||
while( adc != adc_buffer_end )
|
||||
{
|
||||
#ifdef QUADRATURE
|
||||
int32_t t = adc[0]; SHADOWSTORE(0);
|
||||
i += t; q += t;
|
||||
t = adc[1]; SHADOWSTORE(1);
|
||||
i -= t; q += t;
|
||||
t = adc[2]; SHADOWSTORE(2);
|
||||
i -= t; q -= t;
|
||||
t = adc[3]; SHADOWSTORE(3);
|
||||
i += t; q -= t;
|
||||
adc += 4;
|
||||
frcnt += 4;
|
||||
#else
|
||||
i = i + adc[0] - adc[1];
|
||||
adc += 2;
|
||||
frcnt += 2;
|
||||
#endif
|
||||
|
||||
if( adc == adc_buffer_top ) adc = adc_buffer;
|
||||
if( frcnt >= Q ) break;
|
||||
}
|
||||
|
||||
|
||||
if( frcnt >= Q )
|
||||
{
|
||||
|
||||
#ifdef DUMPBUFF
|
||||
int j;
|
||||
for( j = 0; j < Q; j++ )
|
||||
printf( "%d,%d\n", j, shadowbuff[j] );
|
||||
#endif
|
||||
#ifdef QUADRATURE
|
||||
int ti = i>>3;
|
||||
int tq = q>>3;
|
||||
int is = (ti*ti + tq*tq)>>8;
|
||||
#else
|
||||
int is = i>>2;
|
||||
#endif
|
||||
int s = 1<<( ( 32 - __builtin_clz(is) )/2);
|
||||
s = (s + is/s)/2;
|
||||
|
||||
|
||||
#ifdef TIGHT_OUT
|
||||
printf( "%d\n", s );
|
||||
#elif defined( PWM_OUTPUT )
|
||||
int tv = (s>>PWM_OUTPUT) + (PWM_PERIOD/2);
|
||||
if( tv < 0 ) tv = 0;
|
||||
if( tv >= PWM_PERIOD ) tv = PWM_PERIOD-1;
|
||||
TIM1->CH3CVR = tv;
|
||||
#else
|
||||
|
||||
printf( "%8d I:%7d Q:%7d [%d %d %d %d] / %d\n",s, i ,q, adc_buffer[0], adc_buffer[1], adc_buffer[2], adc_buffer[3], (int)(SysTick->CNT - tstart) );
|
||||
#endif
|
||||
//printf( "%d\n", s );
|
||||
frcnt = 0;
|
||||
i = 0;
|
||||
q = 0;
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR;
|
||||
adc = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
tstart = SysTick->CNT;
|
||||
}
|
||||
/*
|
||||
Delay_Us( 100 );
|
||||
int end = DMA1_Channel1->CNTR;
|
||||
int v0 = adc_buffer[0];
|
||||
int v1 = adc_buffer[1];
|
||||
int v2 = adc_buffer[2];
|
||||
int v3 = adc_buffer[3];
|
||||
printf( "%d %d %d %d %d\n", (uint8_t)(start-end), v0, v1, v2, v3 );
|
||||
*/
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
SysTick->CTLR = (1<<2) | 1; // HCLK
|
||||
Delay_Ms(100);
|
||||
|
||||
printf( "System On\n" );
|
||||
|
||||
// x18; 8MHz x 18 = 144 MHz
|
||||
RCC->CFGR0 &= ~RCC_PPRE2; // No divisor on APB1/2
|
||||
RCC->CFGR0 &= ~RCC_PPRE1;
|
||||
RCC->CFGR0 |= RCC_PLLMULL_0 | RCC_PLLMULL_1 | RCC_PLLMULL_2 | RCC_PLLMULL_3;
|
||||
|
||||
Delay_Ms(50);
|
||||
|
||||
// Disable HSI
|
||||
RCC->CTLR &= ~(RCC_HSION);
|
||||
|
||||
// printf( "RCC: %08x\n", (RCC->CFGR0) );
|
||||
RCC->AHBPCENR |= 3; //DMA2EN | DMA1EN
|
||||
RCC->APB2PCENR |= RCC_APB2Periph_TIM1 | RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | 0x07; // Enable all GPIO
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
|
||||
SetupADC();
|
||||
|
||||
#if 0
|
||||
// turn on the op-amp
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_EN;
|
||||
|
||||
// select op-amp pos pin: 0 = PA2, 1 = PD7
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_PSEL;
|
||||
|
||||
// select op-amp neg pin: 0 = PA1, 1 = PD0
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_NSEL;
|
||||
#endif
|
||||
|
||||
|
||||
printf( "ADC Setup\n" );
|
||||
|
||||
SetupTimer1();
|
||||
|
||||
printf( "Timer 1 setup\n" );
|
||||
|
||||
InnerLoop();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
#define FUNCONF_SYSTICK_USE_HCLK 1
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=adcfft
|
||||
TARGET_MCU:=CH32V203G6U6
|
||||
TARGET_MCU_PACKAGE:=CH32V203G6U6
|
||||
CH32V003FUN:=../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_CFLAGS:=-Wno-unused-function -I../../lib -I../lib
|
||||
|
||||
include ../ch32v003fun/ch32v003fun/ch32v003fun.mk
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
rm -rf rf_data_gen chirpbuff.dat chirpbuff.h chirpbuffinfo.h
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# Example with an FFT for quickly figuring out where on the spectrum to look.
|
||||
|
||||
* Display on PB8/PB9 for SCL/SDA
|
||||
* Analog is on PA7
|
||||
@@ -0,0 +1,491 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
**/
|
||||
|
||||
// NOT LORA!!! -- but experimenting with the possibility of rx.
|
||||
|
||||
// SETUP INSTRUCTIONS:
|
||||
// (1) `make` in the optionbytes folder to configure `RESET` correctly.
|
||||
// (2) Create a tone (if using the funprog, ../ch32v003fun/minichlink/minichlink -X ECLK 1:235:189:9:3 for 27.48387097MHz
|
||||
// (2) or, for 24.387096762MHz - ../ch32v003fun/minichlink/minichlink -X ECLK 1:150:49:8:3
|
||||
|
||||
/* More notes
|
||||
|
||||
* Minimum sample time with DMA = fCPU / 28 (5.14MHz)
|
||||
|
||||
*/
|
||||
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#define SH1107_128x128
|
||||
#define SSD1306_RST_PIN PA3
|
||||
#define SSD1306_CS_PIN PA4
|
||||
#define SSD1306_DC_PIN PA6
|
||||
#define SSD1306_MOSI_PIN PA7
|
||||
#define SSD1306_SCK_PIN PA5
|
||||
#define SSD1306_BAUD_RATE_PRESCALER SPI_BaudRatePrescaler_4
|
||||
#include "ssd1306_spi.h"
|
||||
#include "ssd1306.h"
|
||||
|
||||
#define FIX_FFT_IMPLEMENTATION
|
||||
#include "fix_fft.h"
|
||||
|
||||
/* General note:
|
||||
*/
|
||||
|
||||
#define Q 256
|
||||
|
||||
#define TARGET_BIN 51
|
||||
|
||||
#define PWM_PERIOD (31-1) //For 27.0MHz, use 36MHz if quadrature -- It appears to be good for *244 in the table? WHY 26MHz???!?!!?
|
||||
|
||||
#define ADC_BUFFSIZE 512
|
||||
volatile uint16_t adc_buffer[ADC_BUFFSIZE];
|
||||
|
||||
void SetupADC()
|
||||
{
|
||||
// XXX TODO -look into PGA
|
||||
// XXX TODO - Look into tag-teaming the ADCs
|
||||
|
||||
// PA7 is analog input chl 7
|
||||
GPIOA->CFGLR &= ~(0xf<<(4*7)); // CNF = 00: Analog, MODE = 00: Input
|
||||
|
||||
// ADC CLK is chained off of APB2.
|
||||
|
||||
// Reset the ADC to init all regs
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_ADC1;
|
||||
|
||||
// ADCCLK = 12 MHz => RCC_ADCPRE divide by 4
|
||||
RCC->CFGR0 &= ~RCC_ADCPRE; // Clear out the bis in case they were set
|
||||
RCC->CFGR0 |= RCC_ADCPRE_DIV2; // Fastest possible (divide-by-2) NOTE: This is OUTSIDE the specified value in the datasheet.
|
||||
|
||||
// Set up single conversion on chl 7
|
||||
ADC1->RSQR1 = 0;
|
||||
ADC1->RSQR2 = 0;
|
||||
ADC1->RSQR3 = 7; // 0-9 for 8 ext inputs and two internals
|
||||
|
||||
// Not using injection group.
|
||||
|
||||
// Sampling time for channels. Careful: This has PID tuning implications.
|
||||
// Note that with 3 and 3,the full loop (and injection) runs at 138kHz.
|
||||
ADC1->SAMPTR2 = (0<<(3*7));
|
||||
|
||||
// Turn on ADC and set rule group to sw trig
|
||||
// 0 = Use TRGO event for Timer 1 to fire ADC rule.
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_EXTTRIG | ADC_DMA;
|
||||
|
||||
// Reset calibration
|
||||
ADC1->CTLR2 |= ADC_RSTCAL;
|
||||
while(ADC1->CTLR2 & ADC_RSTCAL);
|
||||
|
||||
// Calibrate ADC
|
||||
ADC1->CTLR2 |= ADC_CAL;
|
||||
while(ADC1->CTLR2 & ADC_CAL);
|
||||
|
||||
// ADC_SCAN: Allow scanning.
|
||||
ADC1->CTLR1 = /*ADC_Pga_64 | */ADC_SCAN;
|
||||
|
||||
|
||||
// Turn on DMA
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
//DMA1_Channel1 is for ADC
|
||||
DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR;
|
||||
DMA1_Channel1->MADDR = (uint32_t)adc_buffer;
|
||||
DMA1_Channel1->CNTR = ADC_BUFFSIZE;
|
||||
DMA1_Channel1->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_VeryHigh |
|
||||
DMA_MemoryDataSize_HalfWord |
|
||||
DMA_PeripheralDataSize_HalfWord |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Circular |
|
||||
DMA_DIR_PeripheralSRC;
|
||||
|
||||
// Turn on DMA channel 1
|
||||
DMA1_Channel1->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
// Enable continuous conversion and DMA
|
||||
ADC1->CTLR2 |= ADC_DMA; // | ADC_CONT;
|
||||
|
||||
// start conversion
|
||||
ADC1->CTLR2 |= ADC_SWSTART;// | ADC_CONT;
|
||||
|
||||
}
|
||||
|
||||
static void SetupTimer1()
|
||||
{
|
||||
// Enable Timer 1
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_TIM1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_TIM1;
|
||||
|
||||
TIM1->PSC = 0; // Prescalar to 0x0000 (so, 48MHz base clock)
|
||||
TIM1->ATRLR = PWM_PERIOD;
|
||||
|
||||
#ifdef PWM_OUTPUT
|
||||
// PA10 = T1CH3.
|
||||
GPIOA->CFGHR &= ~(0xf<<(4*2));
|
||||
GPIOA->CFGHR |= (GPIO_Speed_10MHz | GPIO_CNF_OUT_PP_AF)<<(4*2);
|
||||
|
||||
TIM1->CCER = TIM_CC3E | TIM_CC3P;
|
||||
TIM1->CHCTLR2 = TIM_OC3M_2 | TIM_OC3M_1;
|
||||
TIM1->CH3CVR = 5; // Actual duty cycle (Off to begin with)
|
||||
#endif
|
||||
|
||||
TIM1->CCER = TIM_CC1E;
|
||||
TIM1->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1;
|
||||
TIM1->CH1CVR = 1;
|
||||
|
||||
// Setup TRGO to trigger for ADC (NOTE: Not on the 203! TIM1_TRGO is only connected to injection)
|
||||
//TIM1->CTLR2 = TIM_MMS_1;
|
||||
|
||||
// Enable TIM1 outputs
|
||||
TIM1->BDTR = TIM_MOE;
|
||||
TIM1->CTLR1 = TIM_CEN;
|
||||
}
|
||||
|
||||
|
||||
void InnerLoop() __attribute__((noreturn));
|
||||
|
||||
|
||||
void InnerLoop()
|
||||
{
|
||||
//int i = 0;
|
||||
//int q = 0;
|
||||
int tpl = 0;
|
||||
|
||||
// Timer goes backwards when we are moving forwards.
|
||||
volatile uint16_t * adc_buffer_end = 0;
|
||||
volatile uint16_t * adc_buffer_top = adc_buffer + ADC_BUFFSIZE;
|
||||
volatile uint16_t * adc = adc_buffer;
|
||||
|
||||
int frcnt = 0;
|
||||
|
||||
int tstart = 0;
|
||||
|
||||
int16_t shadowbuff[Q+16];
|
||||
|
||||
int shadowplace = 0;
|
||||
#define SCALEUP 6
|
||||
#define SHADOWSTORE(X) shadowbuff[frcnt+X] = t;
|
||||
|
||||
while( 1 )
|
||||
{
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR; // Warning, sometimes this is == to the base, or == 0 (i.e. might be 256, if top is 255)
|
||||
|
||||
tpl += ADC_BUFFSIZE;
|
||||
tpl = (tpl & (ADC_BUFFSIZE-1));
|
||||
if( tpl == ADC_BUFFSIZE ) tpl = 0;
|
||||
|
||||
adc_buffer_end = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
//printf( "%3d %4d %d %04x\n", DMA1_Channel1->CNTR, TIM1->CNT, ADC1->RDATAR, ADC1->STATR );
|
||||
while( adc != adc_buffer_end )
|
||||
{
|
||||
|
||||
int32_t t = adc[0]; SHADOWSTORE(0);
|
||||
//i += t; q += t;
|
||||
t = adc[1]; SHADOWSTORE(1);
|
||||
//i -= t; q += t;
|
||||
t = adc[2]; SHADOWSTORE(2);
|
||||
//i -= t; q -= t;
|
||||
t = adc[3]; SHADOWSTORE(3);
|
||||
//i += t; q -= t;
|
||||
adc += 4;
|
||||
frcnt += 4;
|
||||
|
||||
if( adc == adc_buffer_top ) adc = adc_buffer;
|
||||
if( frcnt >= Q ) break;
|
||||
}
|
||||
|
||||
|
||||
if( frcnt >= Q )
|
||||
{
|
||||
|
||||
#if 0
|
||||
|
||||
#ifdef DUMPBUFF
|
||||
int j;
|
||||
for( j = 0; j < Q; j++ )
|
||||
printf( "%d,%d\n", j, shadowbuff[j] );
|
||||
#endif
|
||||
#ifdef QUADRATURE
|
||||
int ti = i>>3;
|
||||
int tq = q>>3;
|
||||
int is = (ti*ti + tq*tq)>>8;
|
||||
#else
|
||||
int is = i>>2;
|
||||
#endif
|
||||
int s = 1<<( ( 32 - __builtin_clz(is) )/2);
|
||||
s = (s + is/s)/2;
|
||||
|
||||
|
||||
#ifdef TIGHT_OUT
|
||||
printf( "%d\n", s );
|
||||
#elif defined( PWM_OUTPUT )
|
||||
int tv = (s>>PWM_OUTPUT) + (PWM_PERIOD/2);
|
||||
if( tv < 0 ) tv = 0;
|
||||
if( tv >= PWM_PERIOD ) tv = PWM_PERIOD-1;
|
||||
TIM1->CH3CVR = tv;
|
||||
#else
|
||||
|
||||
printf( "%8d I:%7d Q:%7d [%d %d %d %d] / %d\n",s, i ,q, adc_buffer[0], adc_buffer[1], adc_buffer[2], adc_buffer[3], (int)(SysTick->CNT - tstart) );
|
||||
#endif
|
||||
//printf( "%d\n", s );
|
||||
#endif
|
||||
int k;
|
||||
|
||||
// printf( "Data: " );
|
||||
for( k = 0; k < Q; k++ )
|
||||
{
|
||||
// printf( "%d, ",shadowbuff[k] );
|
||||
shadowbuff[k] = (shadowbuff[k]<<SCALEUP)-32768;
|
||||
}
|
||||
//printf( "\n" );
|
||||
|
||||
int osb = shadowbuff[0];
|
||||
int16_t FSQ[Q] = { 0 };
|
||||
for( k = 0; k < 128; k++ )
|
||||
{
|
||||
ssd1306_drawPixel( k, ((shadowbuff[k+128]-osb)>>(SCALEUP+1))+40, 1 );
|
||||
}
|
||||
|
||||
int16_t imag[Q] = { 0 };
|
||||
|
||||
int r =
|
||||
fix_fft(shadowbuff, imag, 8, 0);
|
||||
|
||||
//fix_fftr(shadowbuff, 7 /*1<<7 = 128 bins wide*/, 0);
|
||||
//fix_fft(shadowbuff, FSQ, 8 /*1<<7 = 128 bins wide*/, 0);
|
||||
|
||||
// printf( "FFT:
|
||||
// for( k = 0; k < 128; k++ )
|
||||
// {
|
||||
// }
|
||||
|
||||
int targbin = TARGET_BIN;
|
||||
int targv = 0;
|
||||
int maxbin = 0;
|
||||
int maxbinv = 0;
|
||||
|
||||
|
||||
for( k = 0; k < 128; k++ )
|
||||
{
|
||||
/*
|
||||
int s = shadowbuff[k] * shadowbuff[k] + FSQ[k]*FSQ[k];
|
||||
//if( s == 0 ) continue;
|
||||
int x = 1<<( ( 32 - __builtin_clz(s) )/2);
|
||||
x = (x + i/x)/2;
|
||||
x = (x + i/x)/2; //Not really needed.
|
||||
*/
|
||||
|
||||
// for real
|
||||
// int x = shadowbuff[(k>>1) | ((k&64)>>6)];
|
||||
// For faked imag
|
||||
|
||||
#if 0
|
||||
int s = shadowbuff[k] * shadowbuff[k] + shadowbuff[255-k]*shadowbuff[255-k];
|
||||
//if( s == 0 ) continue;
|
||||
int x = 1<<( ( 32 - __builtin_clz(s) )/2);
|
||||
x = (x + s/x)/2;
|
||||
x = (x + s/x)/2; //Not really needed.
|
||||
x = (x + s/x)/2; //Not really needed.
|
||||
|
||||
//x = shadowbuff[ k ];
|
||||
//x = s >> 8;
|
||||
|
||||
x = x >> 2;
|
||||
#endif
|
||||
|
||||
int s = shadowbuff[k] * shadowbuff[k] + imag[k]*imag[k];
|
||||
//if( s == 0 ) continue;
|
||||
int x = 1<<( ( 32 - __builtin_clz(s) )/2);
|
||||
x = (x + s/x)/2;
|
||||
x = (x + s/x)/2; //Not really needed.
|
||||
x = (x + s/x)/2; //Not really needed.
|
||||
|
||||
//x = shadowbuff[ k ];
|
||||
//x = s >> 8;
|
||||
|
||||
//x = x >> 2;
|
||||
if( x > maxbinv && k != 0) { maxbinv = x; maxbin = k; }
|
||||
if( k == targbin ) targv = x;
|
||||
|
||||
x++;
|
||||
if( x < 0 ) x = 0;
|
||||
if( x > 127 ) x = 127;
|
||||
if( x != 0 )
|
||||
ssd1306_drawFastVLine( k, 127-x, x, 1 );
|
||||
|
||||
}
|
||||
|
||||
static int tbhist[128];
|
||||
static int tbhead = 0;
|
||||
tbhist[tbhead++] = targv;
|
||||
if( tbhead == 128 ) tbhead = 0;
|
||||
|
||||
char cts[32];
|
||||
snprintf( cts, sizeof(cts), "%5d%5d@%d", osb, targv, targbin );
|
||||
ssd1306_drawstr( 0, 0, cts, 1 );
|
||||
snprintf( cts, sizeof(cts), "P:%d B%3d/%4d", PWM_PERIOD, maxbin, maxbinv );
|
||||
ssd1306_drawstr( 0, 8, cts, 1 );
|
||||
|
||||
for( k = 0; k < 128; k++ )
|
||||
{
|
||||
ssd1306_drawPixel( k, 105-tbhist[(tbhead-k+256)%128]/2, 1);
|
||||
}
|
||||
|
||||
memset( shadowbuff, 0, sizeof( shadowbuff ) );
|
||||
|
||||
ssd1306_refresh();
|
||||
ssd1306_setbuf(0);
|
||||
|
||||
frcnt = 0;
|
||||
// i = 0;
|
||||
// q = 0;
|
||||
tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR;
|
||||
adc = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
tstart = SysTick->CNT;
|
||||
}
|
||||
/*
|
||||
Delay_Us( 100 );
|
||||
int end = DMA1_Channel1->CNTR;
|
||||
int v0 = adc_buffer[0];
|
||||
int v1 = adc_buffer[1];
|
||||
int v2 = adc_buffer[2];
|
||||
int v3 = adc_buffer[3];
|
||||
printf( "%d %d %d %d %d\n", (uint8_t)(start-end), v0, v1, v2, v3 );
|
||||
*/
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
SysTick->CTLR = (1<<2) | 1; // HCLK
|
||||
Delay_Ms(100);
|
||||
|
||||
printf( "System On\n" );
|
||||
|
||||
RCC->CTLR |= RCC_HSEON;
|
||||
while( ! ( RCC->CTLR & RCC_HSERDY ) );
|
||||
|
||||
RCC->CFGR0 = (RCC->CFGR0 & ~RCC_SW) | RCC_SW_HSE;
|
||||
|
||||
RCC->CTLR &= ~RCC_PLLON;
|
||||
|
||||
// Switch PLL to HSE.
|
||||
RCC->CFGR0 |= RCC_PLLSRC;
|
||||
|
||||
// x18; 8MHz x 18 = 144 MHz
|
||||
RCC->CFGR0 &= ~RCC_PPRE2; // No divisor on APB1/2
|
||||
RCC->CFGR0 &= ~RCC_PPRE1;
|
||||
RCC->CFGR0 |= RCC_PLLMULL_0 | RCC_PLLMULL_1 | RCC_PLLMULL_2 | RCC_PLLMULL_3;
|
||||
|
||||
RCC->CTLR |= RCC_PLLON;
|
||||
|
||||
// Switch to PLL
|
||||
RCC->CFGR0 = (RCC->CFGR0 & ~RCC_SW) | RCC_SW_PLL;
|
||||
|
||||
// Disable HSI
|
||||
RCC->CTLR &= ~(RCC_HSION);
|
||||
|
||||
Delay_Ms(10);
|
||||
|
||||
|
||||
printf( "CTLR: %08x / CFGR0: %08x\n", (RCC->CTLR), (RCC->CFGR0) );
|
||||
RCC->AHBPCENR |= 3; //DMA2EN | DMA1EN
|
||||
RCC->APB2PCENR |= RCC_APB2Periph_TIM1 | RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | 0x07; // Enable all GPIO
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
|
||||
SetupADC();
|
||||
|
||||
printf( "Setting up OLED.\n" );
|
||||
//ssd1306_spi_setup();
|
||||
uint8_t ret = ssd1306_spi_init();
|
||||
ssd1306_init();
|
||||
ssd1306_setbuf(0);
|
||||
|
||||
#if 0
|
||||
int i = 0;
|
||||
int k = 0;
|
||||
int frame = 0;
|
||||
while( 1)
|
||||
{
|
||||
// ssd1306_drawLine( (frame)%128, (0)%128, (0)%128, (127-frame)%128, 1 );
|
||||
ssd1306_drawstr( frame%128, frame%128, "hello", 1 );
|
||||
|
||||
ssd1306_refresh();
|
||||
ssd1306_setbuf(0);
|
||||
frame++;
|
||||
}
|
||||
|
||||
while(1);
|
||||
#endif
|
||||
|
||||
#if 0
|
||||
// turn on the op-amp
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_EN;
|
||||
|
||||
// select op-amp pos pin: 0 = PA2, 1 = PD7
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_PSEL;
|
||||
|
||||
// select op-amp neg pin: 0 = PA1, 1 = PD0
|
||||
EXTEN->EXTEN_CTR |= EXTEN_OPA_NSEL;
|
||||
#endif
|
||||
|
||||
|
||||
printf( "ADC Setup\n" );
|
||||
|
||||
SetupTimer1();
|
||||
|
||||
printf( "Timer 1 setup\n" );
|
||||
|
||||
InnerLoop();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
#define FUNCONF_SYSTICK_USE_HCLK 1
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=adcgoertzel
|
||||
TARGET_MCU:=CH32V203G6U6
|
||||
TARGET_MCU_PACKAGE:=CH32V203G6U6
|
||||
CH32V003FUN:=../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_CFLAGS:=-Wno-unused-function -I../../lib -I../lib -I../ch32v003fun/examples_v20x/otg_device -I.
|
||||
|
||||
include ../ch32v003fun/ch32v003fun/ch32v003fun.mk
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
rm -rf rf_data_gen chirpbuff.dat chirpbuff.h chirpbuffinfo.h
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# How to use this
|
||||
|
||||
* Display on PB8/PB9 for SCL/SDA
|
||||
* Analog is on PA7
|
||||
|
||||
First, use FFT, then look in the middle for the highest bin @. This is the # of pixels from the left side of the screen you are.
|
||||
|
||||
Then edit ttest.c,
|
||||
|
||||
```
|
||||
g_goertzel_omega_per_sample = (47.0/256) * 3.1415926535*2.0*65536;
|
||||
```
|
||||
|
||||
where 47.0 in this case is the bin # from the FFT.
|
||||
|
||||
Change this, `make test`
|
||||
|
||||
Then copy the values:
|
||||
const int32_t g_goertzel_omega_per_sample = 75599;
|
||||
const int32_t g_goertzel_coefficient = 870257651;
|
||||
const int32_t g_goertzel_coefficient_s = 1963246708;
|
||||
|
||||
into the top of adcgoertzel.c
|
||||
|
||||
|
||||
TODO: TODO: Test HTML values.
|
||||
|
||||
TODO: TODO: g_goertzel_omega_per_sample lokos WRONG.
|
||||
|
||||
|
||||
Extra notes:
|
||||
.87996033 = 880 AM, why?
|
||||
@@ -0,0 +1,863 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
**/
|
||||
|
||||
// SETUP INSTRUCTIONS:
|
||||
// (1) `make` in the optionbytes folder to configure `RESET` correctly.
|
||||
// (2) Create a tone (if using the funprog, ../ch32v003fun/minichlink/minichlink -X ECLK 1:235:189:9:3 for 27.48387097MHz
|
||||
// (2) or, for 24.387096762MHz - ../ch32v003fun/minichlink/minichlink -X ECLK 1:150:49:8:3
|
||||
/* More notes
|
||||
* Minimum sample time with DMA = fCPU / 28 (5.14MHz)
|
||||
*/
|
||||
|
||||
// TODO:
|
||||
// 1: Cleanup some code.
|
||||
// 2: Leverage other ADC.
|
||||
// 3:
|
||||
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
|
||||
|
||||
// Channel for ADC
|
||||
#define CHANNEL 0
|
||||
|
||||
// For I2C, output will be on PB8/PB9 SCL/SDA
|
||||
//#define ENABLE_OLED
|
||||
//#define PWM_OUTPUT
|
||||
int g_volume_pwm = 127; // 0 - 127 (100%) (but you can go over 100) (For when using PWM)
|
||||
#define ENABLE_OLED_SCOPE
|
||||
//#define PROFILING_PIN PC8
|
||||
|
||||
#define SAMPLETIME 1 // 0: 1.5 cycles; 1: 7.5 cycles; 2: 13.5 cycles; (0 would go fastest and is important in single-ADC mode, but 1 seems slightly better in 2-ADC mode)
|
||||
|
||||
#ifdef ENABLE_OLED_SCOPE
|
||||
#define SH1107_128x128
|
||||
#define SSD1306_RST_PIN PA3
|
||||
#define SSD1306_CS_PIN PA4
|
||||
#define SSD1306_DC_PIN PA6
|
||||
#define SSD1306_MOSI_PIN PA7
|
||||
#define SSD1306_SCK_PIN PA5
|
||||
#define SSD1306_BAUD_RATE_PRESCALER SPI_BaudRatePrescaler_4
|
||||
#include "ssd1306_spi.h"
|
||||
#include "ssd1306.h"
|
||||
#endif
|
||||
|
||||
#ifdef ENABLE_OLED
|
||||
#define SH1107_128x128
|
||||
#define SSD1306_REMAP_I2C
|
||||
//#define SSD1306_I2C_IRQ
|
||||
#include "ssd1306_i2c.h"
|
||||
#include "ssd1306.h"
|
||||
#endif
|
||||
|
||||
#if defined( ENABLE_OLED ) && defined( ENABLE_OLED_SCOPE )
|
||||
#error Cant be SPI and I2C OLED
|
||||
#endif
|
||||
|
||||
|
||||
#include "./usb_config.h"
|
||||
#include "../ch32v003fun/examples_v20x/otg_device/otgusb.h"
|
||||
|
||||
// Bigger buffer decreases chance of fall-through, but increases the size of each operation.
|
||||
#define ADC_BUFFSIZE 512
|
||||
|
||||
volatile uint16_t adc_buffer[ADC_BUFFSIZE];
|
||||
|
||||
int32_t g_goertzel_phasor_r = 32768;
|
||||
int32_t g_goertzel_phasor_i = 0;
|
||||
int32_t g_attenuation_pow2 = 4;
|
||||
|
||||
#if 1
|
||||
// Very basic setup, for tuning to 880AM
|
||||
int g_pwm_period = (60-1);
|
||||
int g_exactcompute = (1);
|
||||
int g_goertzel_buffer = (1024);
|
||||
int32_t g_goertzel_omega_per_sample = 873460290; // 0.183333 of whole per step / -8.720000MHz
|
||||
int32_t g_goertzel_coefficient = 873460290;
|
||||
int32_t g_goertzel_coefficient_s = 1961823932;
|
||||
int32_t g_goertzel_advance_r = -3425;
|
||||
int32_t g_goertzel_advance_i = 32588;
|
||||
#endif
|
||||
|
||||
int intensity_average = 1;
|
||||
|
||||
#define LOG_GOERTZEL_LIST 512
|
||||
int32_t qibaselogs[LOG_GOERTZEL_LIST];
|
||||
volatile int qibaselogs_head;
|
||||
|
||||
void SetupADC()
|
||||
{
|
||||
// XXX TODO -look into PGA
|
||||
// XXX TODO - Look into tag-teaming the ADCs
|
||||
|
||||
// PDA is analog input chl CHANNEL
|
||||
GPIOA->CFGLR &= ~(0xf<<(4*CHANNEL)); // CNF = 00: Analog, MODE = 00: Input
|
||||
|
||||
// ADC CLK is chained off of APB2.
|
||||
|
||||
// Reset the ADC to init all regs
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2;
|
||||
RCC->APB2PRSTR &= ~( RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 );
|
||||
|
||||
// ADCCLK = 12 MHz => RCC_ADCPRE divide by 4
|
||||
RCC->CFGR0 &= ~RCC_ADCPRE; // Clear out the bis in case they were set
|
||||
RCC->CFGR0 |= RCC_ADCPRE_DIV2; // Fastest possible (divide-by-2) NOTE: This is OUTSIDE the specified value in the datasheet.
|
||||
|
||||
// Set up single conversion on chl 7
|
||||
ADC1->RSQR3 = CHANNEL; // 0-9 for 8 ext inputs and two internals Set to 7 for PA7
|
||||
ADC2->RSQR3 = CHANNEL; // 0-9 for 8 ext inputs and two internals Set to 7 for PA7
|
||||
|
||||
ADC1->ISQR = CHANNEL; // Mirror in case we switch to injection mode.
|
||||
ADC2->ISQR = CHANNEL;
|
||||
|
||||
// Not using injection group.
|
||||
|
||||
// Sampling time for channels. Careful: This has PID tuning implications.
|
||||
// Note that with 3 and 3,the full loop (and injection) runs at 138kHz.
|
||||
ADC1->SAMPTR2 = (SAMPLETIME<<(3*CHANNEL)); // (3*channel)
|
||||
ADC2->SAMPTR2 = (SAMPLETIME<<(3*CHANNEL)); // (3*channel)
|
||||
|
||||
// Turn on ADC and set rule group to sw trig
|
||||
// 0 = Use TRGO event for Timer 1 to fire ADC rule.
|
||||
ADC1->CTLR2 = ADC_ADON | ADC_EXTTRIG | ADC_DMA;
|
||||
ADC2->CTLR2 = ADC_ADON | ADC_EXTTRIG | ADC_EXTSEL_1;// | ADC_DMA;
|
||||
// For EXTTRIG, EXTSEL (none) = 0 = TIM1CC1 /
|
||||
// For JEXTTRIG, EXTSEL = 0 = TIM1 TRGO (Or ADC_JEXTSEL_0 => CH4)
|
||||
|
||||
// Reset calibration
|
||||
ADC1->CTLR2 |= ADC_RSTCAL;
|
||||
ADC2->CTLR2 |= ADC_RSTCAL;
|
||||
while(ADC1->CTLR2 & ADC_RSTCAL);
|
||||
while(ADC2->CTLR2 & ADC_RSTCAL);
|
||||
|
||||
// Calibrate ADC
|
||||
ADC1->CTLR2 |= ADC_CAL;
|
||||
ADC2->CTLR2 |= ADC_CAL;
|
||||
while(ADC1->CTLR2 & ADC_CAL);
|
||||
while(ADC2->CTLR2 & ADC_CAL);
|
||||
|
||||
// ADC_SCAN: Allow scanning.
|
||||
ADC2->CTLR1 = ADC_SCAN;
|
||||
ADC1->CTLR1 =
|
||||
//ADC_DUALMOD_0 | ADC_DUALMOD_3 | // Alternate Trigger Mode (Can't use with DMA)
|
||||
ADC_SCAN;
|
||||
//ADC_Pga_16 | ADC_BUFEN ;
|
||||
//ADC_Pga_64 | ADC_BUFEN;
|
||||
|
||||
// Turn on DMA
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
//DMA1_Channel1 is for ADC
|
||||
DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR;
|
||||
DMA1_Channel1->MADDR = (uint32_t)adc_buffer;
|
||||
DMA1_Channel1->CNTR = ADC_BUFFSIZE/2;
|
||||
DMA1_Channel1->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_VeryHigh |
|
||||
DMA_MemoryDataSize_Word |
|
||||
DMA_PeripheralDataSize_Word |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Circular |
|
||||
DMA_DIR_PeripheralSRC;
|
||||
|
||||
NVIC_EnableIRQ( DMA1_Channel1_IRQn );
|
||||
DMA1_Channel1->CFGR |= DMA_CFGR1_EN | DMA_IT_TC | DMA_IT_HT; // Transmission Complete + Half Empty Interrupts.
|
||||
|
||||
// Enable continuous conversion and DMA
|
||||
ADC1->CTLR2 |= ADC_DMA; // | ADC_CONT;
|
||||
}
|
||||
|
||||
static void SetupTimer1()
|
||||
{
|
||||
// Enable Timer 1
|
||||
RCC->APB2PRSTR |= RCC_APB2Periph_TIM1;
|
||||
RCC->APB2PRSTR &= ~RCC_APB2Periph_TIM1;
|
||||
|
||||
TIM1->PSC = 0; // Prescalar to 0x0000 (so, 48MHz base clock)
|
||||
TIM1->ATRLR = g_pwm_period;
|
||||
|
||||
#ifdef PWM_OUTPUT
|
||||
// PA9 = T1CH2.
|
||||
funPinMode( PA9, GPIO_CFGLR_OUT_2Mhz_AF_PP );
|
||||
|
||||
TIM1->CCER = TIM_CC2E | TIM_CC2P;
|
||||
TIM1->CHCTLR1 |= TIM_OC2M_2 | TIM_OC2M_1 | TIM_OC2FE;
|
||||
TIM1->CH2CVR = 5; // Set duty cycle somewhere random.
|
||||
|
||||
// Enable TIM1 outputs
|
||||
TIM1->BDTR |= 0xc000;//TIM_MOE;
|
||||
#endif
|
||||
|
||||
TIM1->CCER |= TIM_CC1E | TIM_CC4E | TIM_CC3E;
|
||||
TIM1->CHCTLR1 |= TIM_OC1M_2 | TIM_OC1M_1;
|
||||
TIM1->CHCTLR2 |= TIM_OC3M_2 | TIM_OC3M_1 | TIM_OC4M_2 | TIM_OC4M_1;
|
||||
TIM1->CH1CVR = 1; // In case we are using rule triggering
|
||||
TIM1->CH3CVR = 1; // In case we are using rule (alternate) triggering
|
||||
TIM1->CH4CVR = 1; // In case we are using injection triggering
|
||||
|
||||
// Setup TRGO to trigger for ADC injection group
|
||||
TIM1->CTLR2 = TIM_MMS_1;
|
||||
|
||||
// Enable TIM1 outputs
|
||||
TIM1->BDTR = TIM_MOE;
|
||||
TIM1->CTLR1 = TIM_CEN;
|
||||
}
|
||||
|
||||
#ifdef ENABLE_OLED_SCOPE
|
||||
|
||||
#ifdef PLOTGUARD
|
||||
// Command-mode, Set X, Disable Timer, Set Y, Enable Timer
|
||||
// There doesn't seem to be a way of truly pausing the scanout.
|
||||
// GENERAL NOTE: This doesn't actually seem to help reduce streaking.
|
||||
uint8_t cmdxy[] = { 0x00, 0xd3, 0x30, 0xd5, 0xff, 0xdc, 0x30, 0xd5, 0xf0 };
|
||||
#else
|
||||
// Only set xy plot, and make sure clock is cranked.
|
||||
uint8_t cmdxy[] = { 0x00, 0xd3, 0x30, 0xdc, 0x30, 0xd5, 0xf0 };
|
||||
#endif
|
||||
|
||||
void config_turbo_scope()
|
||||
{
|
||||
DMA1_Channel3->PADDR = (uint32_t)&SPI1->DATAR;
|
||||
DMA1_Channel3->MADDR = (uint32_t)cmdxy;
|
||||
DMA1_Channel3->CNTR = sizeof(cmdxy);
|
||||
DMA1_Channel3->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_Low |
|
||||
DMA_MemoryDataSize_Byte |
|
||||
DMA_PeripheralDataSize_Byte |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Normal |
|
||||
DMA_DIR_PeripheralDST;
|
||||
|
||||
// Turn on DMA channel 3 (For SPI output)
|
||||
DMA1_Channel3->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
// All display controls from here on out are made using DC = 0.
|
||||
funDigitalWrite( SSD1306_DC_PIN, FUN_LOW );
|
||||
|
||||
SPI1->CTLR2 |= SPI_CTLR2_TXDMAEN;
|
||||
}
|
||||
|
||||
static void PlotPoint( int x, int y )
|
||||
{
|
||||
funDigitalWrite( SSD1306_CS_PIN, FUN_HIGH );
|
||||
#ifdef PLOTGUARD
|
||||
cmdxy[2] = x; cmdxy[6] = y;
|
||||
#else
|
||||
cmdxy[2] = x; cmdxy[4] = y;
|
||||
#endif
|
||||
DMA1_Channel3->CNTR = sizeof(cmdxy);
|
||||
funDigitalWrite( SSD1306_CS_PIN, FUN_LOW );
|
||||
DMA1_Channel3->CFGR |= DMA_CFGR1_EN;
|
||||
}
|
||||
#endif
|
||||
|
||||
void InnerLoop() __attribute__((noreturn));
|
||||
|
||||
|
||||
uint32_t tc;
|
||||
|
||||
|
||||
volatile uint16_t * adc_tail = adc_buffer;
|
||||
|
||||
uint32_t g_goertzel_samples;
|
||||
uint32_t g_goertzel_outs;
|
||||
int32_t g_goertzel, g_goertzelp, g_goertzelp2;
|
||||
int32_t g_goertzelp_store, g_goertzelp2_store;
|
||||
|
||||
int32_t g_laststart = 0;
|
||||
int32_t g_lastper;
|
||||
int32_t g_lastlen;
|
||||
uint32_t g_accumulate_over_window;
|
||||
|
||||
void DMA1_Channel1_IRQHandler( void ) __attribute__((interrupt));
|
||||
void DMA1_Channel1_IRQHandler( void )
|
||||
{
|
||||
int32_t start = SysTick->CNT;
|
||||
#ifdef PROFILING_PIN
|
||||
funDigitalWrite( PROFILING_PIN, 1 );
|
||||
#endif
|
||||
|
||||
// Timer goes backwards when we are moving forwards.
|
||||
volatile uint16_t * adc_buffer_end = 0;
|
||||
volatile uint16_t * adc_buffer_top = adc_buffer + ADC_BUFFSIZE;
|
||||
|
||||
int32_t goertzel_coefficient = g_goertzel_coefficient;
|
||||
int32_t goertzelp2 = g_goertzelp2;
|
||||
int32_t goertzelp = g_goertzelp;
|
||||
int32_t goertzel = g_goertzel;
|
||||
int32_t accumulate_over_window = g_accumulate_over_window;
|
||||
|
||||
uint32_t goertzel_samples = g_goertzel_samples;
|
||||
// Backup flags.
|
||||
volatile int intfr = DMA1->INTFR;
|
||||
|
||||
do
|
||||
{
|
||||
// Clear all possible flags.
|
||||
DMA1->INTFCR = DMA1_IT_GL1;
|
||||
|
||||
int tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR*2;
|
||||
// Warning, sometimes this is DMA1_Channel1->CNTR == to the base, or == 0 (i.e. might be 256, if top is 255)
|
||||
|
||||
tpl += ADC_BUFFSIZE;
|
||||
tpl = (tpl & (ADC_BUFFSIZE-1));
|
||||
if( tpl == ADC_BUFFSIZE ) tpl = 0;
|
||||
|
||||
adc_buffer_end = adc_buffer + ( ( tpl / 4) * 4 );
|
||||
|
||||
#define INFADC 2
|
||||
// Add a tiny bias to the ADC to help keep goertz in range.
|
||||
static int adc_offset = (-2048) << INFADC;
|
||||
|
||||
while( adc_tail != adc_buffer_end )
|
||||
{
|
||||
|
||||
uint32_t t; // 1/2 of 4096, to try to keep our numbers reasonable.
|
||||
|
||||
// Here is where the magic happens.
|
||||
|
||||
#if 1
|
||||
// Also, this is the current limiting factor for the maximum samplerate.
|
||||
// We can't go above 7.2MSPS and keep up here when main CPU is @ 144MHz.
|
||||
|
||||
#define XSTR(x) #x
|
||||
#define GOERTZELLOOP(idx) \
|
||||
asm volatile("\n\
|
||||
lhu %[adcin]," XSTR(idx) "(%[adc_tail]) \n\
|
||||
slli %[adcin],%[adcin],%[iadc] /*INFADC = 2*/ \n\
|
||||
add %[adcin],%[adcin],%[adcoffset] /*adcin += adcoffset*/ \n\
|
||||
add %[accumulate_over_window], %[adcin], %[accumulate_over_window]\n \
|
||||
addi %[goertzelp2],%[goertzelp],0 /*goertzelp2 = goertzelp*/ \n\
|
||||
addi %[goertzelp], %[goertzel],0 /*goertzelp = goertzel*/ \n\
|
||||
slli %[goertzel], %[goertzelp], 2 /*prescaling up goertzelp*/\n\
|
||||
mulh %[goertzel], %[goertzel_coefficient], %[goertzel]\n\
|
||||
sub %[adcin],%[adcin],%[goertzelp2] /*adcin -= goertzelp2*/ \n\
|
||||
add %[goertzel], %[goertzel], %[adcin] /* mulh = signed * signed + adc */ \n"\
|
||||
: [goertzel]"+r"(goertzel), [goertzelp]"+r"(goertzelp), [goertzelp2]"+r"(goertzelp2), [adcin]"+r"(t), [accumulate_over_window]"+r"(accumulate_over_window) : \
|
||||
[adc_tail]"r"(adc_tail), [adcoffset]"r"(adc_offset), [goertzel_coefficient]"r"(goertzel_coefficient), [iadc]"i"(INFADC) );
|
||||
|
||||
GOERTZELLOOP(0);
|
||||
GOERTZELLOOP(2);
|
||||
GOERTZELLOOP(4);
|
||||
GOERTZELLOOP(6);
|
||||
#else
|
||||
t = ((adc_tail[0])<<INFADC)+adc_offset;
|
||||
goertzelp2 = goertzelp;
|
||||
goertzelp = goertzel;
|
||||
goertzel = t + ( ( (((int32_t)(goertzel_coefficient))) * ((((int64_t)goertzelp)<<2)) ) >> 32 ) - goertzelp2;
|
||||
|
||||
t = ((adc_tail[1])<<INFADC)+adc_offset;
|
||||
goertzelp2 = goertzelp;
|
||||
goertzelp = goertzel;
|
||||
goertzel = t + ( ( (((int32_t)(goertzel_coefficient))) * ((((int64_t)goertzelp)<<2)) ) >> 32 ) - goertzelp2;
|
||||
|
||||
t = ((adc_tail[2])<<INFADC)+adc_offset;
|
||||
goertzelp2 = goertzelp;
|
||||
goertzelp = goertzel;
|
||||
goertzel = t + ( ( (((int32_t)(goertzel_coefficient))) * ((((int64_t)goertzelp)<<2)) ) >> 32 ) - goertzelp2;
|
||||
|
||||
t = ((adc_tail[3])<<INFADC)+adc_offset;
|
||||
goertzelp2 = goertzelp;
|
||||
goertzelp = goertzel;
|
||||
goertzel = t + ( ( (((int32_t)(goertzel_coefficient))) * ((((int64_t)goertzelp)<<2)) ) >> 32 ) - goertzelp2;
|
||||
#endif
|
||||
|
||||
adc_tail+=4;
|
||||
goertzel_samples+=4;
|
||||
if( adc_tail == adc_buffer_top ) adc_tail = adc_buffer;
|
||||
if( goertzel_samples == g_goertzel_buffer )
|
||||
{
|
||||
#ifdef PROFILING_PIN
|
||||
funDigitalWrite( PROFILING_PIN, 0 );
|
||||
#endif
|
||||
|
||||
g_goertzelp_store = goertzel;
|
||||
g_goertzelp2_store = goertzelp;
|
||||
|
||||
int32_t zp = g_goertzelp_store;
|
||||
int32_t zp2 = g_goertzelp2_store;
|
||||
int32_t rr = (((int64_t)(g_goertzel_coefficient ) * (int64_t)zp<<1)>>(32+g_attenuation_pow2)) - (zp2>>g_attenuation_pow2);
|
||||
int32_t ri = (((int64_t)(g_goertzel_coefficient_s) * (int64_t)zp<<1)>>(32+g_attenuation_pow2));
|
||||
|
||||
// Advanced the current goertzel advance
|
||||
// phasor = phasor * advance;
|
||||
// real = real * real - imag * imag;
|
||||
// imag = real * imag + real * imag;
|
||||
// Sometimes you would bias the output here so that when truncating down you don't perpetually decay.
|
||||
// But experimentally, it didn't make a difference.
|
||||
int32_t temp = (g_goertzel_phasor_r * g_goertzel_advance_i + g_goertzel_phasor_i * g_goertzel_advance_r) >> 15;
|
||||
g_goertzel_phasor_r = (g_goertzel_phasor_r * g_goertzel_advance_r - g_goertzel_phasor_i * g_goertzel_advance_i) >> 15;
|
||||
g_goertzel_phasor_i = temp;
|
||||
|
||||
// Fixup phasor over time to prevent it from dacaying.
|
||||
#define ABS(x) (((x)<0)?-(x):(x))
|
||||
int s_phasor = g_goertzel_phasor_r * g_goertzel_phasor_r + g_goertzel_phasor_i * g_goertzel_phasor_i;
|
||||
int intensity_phasor = (ABS(g_goertzel_phasor_r) + ABS(g_goertzel_phasor_i)) * 26100 / 32768 + 1; // Found experimentally (Also try to avoid divide-by-zero.
|
||||
intensity_phasor = (intensity_phasor + s_phasor/intensity_phasor)/2;
|
||||
intensity_phasor = (intensity_phasor + s_phasor/intensity_phasor)/2;
|
||||
if( intensity_phasor < 32760 )
|
||||
{
|
||||
// It is decaying, this is equivelent to f = f * 1.000244141
|
||||
g_goertzel_phasor_r += g_goertzel_phasor_r >> 12;
|
||||
g_goertzel_phasor_i += g_goertzel_phasor_i >> 12;
|
||||
}
|
||||
|
||||
// Now, rotate rr, ri by that phasor.
|
||||
// To get it in line >> 15, but we also want to divide by 8 (>>3) because that makes the rest of the math easier.
|
||||
temp = (g_goertzel_phasor_r * ri + g_goertzel_phasor_i * rr) >> (15);
|
||||
rr = (g_goertzel_phasor_r * rr - g_goertzel_phasor_i * ri) >> (15);
|
||||
ri = temp;
|
||||
|
||||
// rr, ri are now in the correct frame of reference. Continue computing.
|
||||
|
||||
qibaselogs[qibaselogs_head] = ((uint16_t)rr) | (((uint16_t)ri)<<16);
|
||||
qibaselogs_head = ( qibaselogs_head + 1 ) & ((LOG_GOERTZEL_LIST)-1);
|
||||
|
||||
int s = rr * rr + ri * ri;
|
||||
//int intensity = 1<<( ( 32 - __builtin_clz(s) )/2);
|
||||
#define ABS(x) (((x)<0)?-(x):(x))
|
||||
int intensity = (ABS(rr) + ABS(ri)) * 26100 / 32768; // Found experimentally (Also try to avoid divide-by-zero.
|
||||
//if( intensity == 0 )
|
||||
// intensity = 1;
|
||||
intensity++;
|
||||
intensity = (intensity + s/intensity)/2;
|
||||
intensity = (intensity + s/intensity)/2;
|
||||
|
||||
// intensity = rr * rr + ri * ri
|
||||
|
||||
// This performs a low-pass IIR without exploding intensity_average.
|
||||
intensity_average = intensity_average - (intensity_average>>12) + (intensity>>6);
|
||||
if( ((int32_t)intensity_average) >= 1<<23 ) intensity_average = (1<<23)-1;
|
||||
if( ((int32_t)intensity_average) < 2048 ) intensity_average = 2048;
|
||||
|
||||
#ifdef PWM_OUTPUT
|
||||
intensity = intensity * g_volume_pwm * g_pwm_period / (intensity_average>>(10-12));
|
||||
if( intensity >= g_pwm_period-1 ) intensity = g_pwm_period-2;
|
||||
if( intensity < 1 ) intensity = 1;
|
||||
TIM1->CH2CVR = intensity; // Actual duty cycle (Off to begin with)
|
||||
#endif
|
||||
|
||||
g_goertzel_outs++;
|
||||
goertzel = 0;
|
||||
goertzelp = 0;
|
||||
goertzel_samples = 0;
|
||||
|
||||
// Try to improve bias.
|
||||
adc_offset -= accumulate_over_window / g_goertzel_buffer;
|
||||
accumulate_over_window = 0;
|
||||
|
||||
#ifdef ENABLE_OLED_SCOPE
|
||||
int rrplot = rr * 1536 / (intensity_average);
|
||||
int riplot = ri * 1536 / (intensity_average);
|
||||
rrplot += 64;
|
||||
riplot += 64;
|
||||
if( rrplot < 1 ) rrplot = 1;
|
||||
if( riplot < 1 ) riplot = 1;
|
||||
if( rrplot > 126 ) rrplot = 126;
|
||||
if( riplot > 126 ) riplot = 126;
|
||||
PlotPoint( rrplot, riplot );
|
||||
#endif
|
||||
|
||||
#ifdef PROFILING_PIN
|
||||
funDigitalWrite( PROFILING_PIN, 1 );
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
intfr = DMA1->INTFR;
|
||||
} while( intfr & DMA1_IT_GL1 );
|
||||
|
||||
g_goertzelp2 = goertzelp2;
|
||||
g_goertzelp = goertzelp;
|
||||
g_goertzel = goertzel;
|
||||
g_goertzel_samples = goertzel_samples;
|
||||
g_accumulate_over_window = accumulate_over_window;
|
||||
|
||||
#ifdef PROFILING_PIN
|
||||
funDigitalWrite( PROFILING_PIN, 0 ); // For profiling
|
||||
#endif
|
||||
int32_t end = SysTick->CNT;
|
||||
g_lastper = start - g_laststart;
|
||||
g_laststart = start;
|
||||
g_lastlen = end - start;
|
||||
}
|
||||
|
||||
static inline uint32_t gets2()
|
||||
{
|
||||
uint32_t ret;
|
||||
asm volatile( "mv %[ret], s2" : [ret]"=&r"(ret) );
|
||||
return ret;
|
||||
}
|
||||
|
||||
uint8_t i2c_send_buffer[16];
|
||||
void setup_i2c_dma(void)
|
||||
{
|
||||
// Turn on DMA
|
||||
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
|
||||
|
||||
//DMA1_Channel6 is for I2C1TX
|
||||
DMA1_Channel6->PADDR = (uint32_t)&I2C1->DATAR;
|
||||
DMA1_Channel6->MADDR = (uint32_t)&i2c_send_buffer;
|
||||
DMA1_Channel6->CNTR = 0;
|
||||
DMA1_Channel6->CFGR =
|
||||
DMA_M2M_Disable |
|
||||
DMA_Priority_Low |
|
||||
DMA_MemoryDataSize_Byte |
|
||||
DMA_PeripheralDataSize_Byte |
|
||||
DMA_MemoryInc_Enable |
|
||||
DMA_Mode_Normal |
|
||||
DMA_DIR_PeripheralDST |
|
||||
0;
|
||||
I2C1->CTLR2 = I2C_CTLR2_DMAEN | 0b111100;
|
||||
|
||||
DMA1_Channel6->CFGR |= DMA_CFGR1_EN;
|
||||
|
||||
NVIC_DisableIRQ(I2C1_EV_IRQn);
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
SysTick->CTLR = (1<<2) | 1; // HCLK
|
||||
Delay_Ms(100);
|
||||
|
||||
RCC->CTLR |= RCC_HSEON;
|
||||
while( ! ( RCC->CTLR & RCC_HSERDY ) );
|
||||
|
||||
RCC->CFGR0 = (RCC->CFGR0 & ~RCC_SW) | RCC_SW_HSE;
|
||||
|
||||
RCC->CTLR &= ~RCC_PLLON;
|
||||
|
||||
// Switch PLL to HSE.
|
||||
RCC->CFGR0 |= RCC_PLLSRC;
|
||||
|
||||
// x18; 8MHz x 18 = 144 MHz
|
||||
RCC->CFGR0 &= ~RCC_PPRE2; // No divisor on APB1/2
|
||||
RCC->CFGR0 &= ~RCC_PPRE1;
|
||||
RCC->CFGR0 |= RCC_PLLMULL_0 | RCC_PLLMULL_1 | RCC_PLLMULL_2 | RCC_PLLMULL_3;
|
||||
|
||||
RCC->CTLR |= RCC_PLLON;
|
||||
|
||||
// Switch to PLL
|
||||
RCC->CFGR0 = (RCC->CFGR0 & ~RCC_SW) | RCC_SW_PLL;
|
||||
|
||||
// Disable HSI
|
||||
RCC->CTLR &= ~(RCC_HSION);
|
||||
|
||||
Delay_Ms(10);
|
||||
|
||||
|
||||
//printf( "CTLR: %08x / CFGR0: %08x\n", (RCC->CTLR), (RCC->CFGR0) );
|
||||
RCC->AHBPCENR |= 3; //DMA2EN | DMA1EN
|
||||
RCC->APB2PCENR |= RCC_APB2Periph_TIM1 | RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | 0x07 | RCC_APB2Periph_GPIOA; // Enable all GPIO
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
|
||||
SetupADC();
|
||||
|
||||
#if defined( ENABLE_OLED )
|
||||
ssd1306_i2c_setup();
|
||||
ssd1306_i2c_init();
|
||||
|
||||
if( ssd1306_init() )
|
||||
printf( "Failed to initialize OLED\n" );
|
||||
else
|
||||
printf( "Initialized OLED\n" );
|
||||
|
||||
ssd1306_setbuf(1);
|
||||
ssd1306_refresh();
|
||||
#endif
|
||||
|
||||
#ifdef ENABLE_OLED_SCOPE
|
||||
int i;
|
||||
|
||||
ssd1306_spi_init();
|
||||
ssd1306_rst();
|
||||
|
||||
if( ssd1306_init() )
|
||||
printf( "Failed to initialize OLED\n" );
|
||||
else
|
||||
printf( "Initialized OLED\n" );
|
||||
|
||||
ssd1306_setbuf(0);
|
||||
|
||||
// Setup a diagonal to allow for vector mode.
|
||||
for( i = 0; i < 128; i++ )
|
||||
{
|
||||
ssd1306_drawPixel( i, i, 1 );
|
||||
//ssd1306_drawPixel( i+1, i, 1 );
|
||||
}
|
||||
|
||||
// Not sure why, need to do it a few times to make it stick?
|
||||
ssd1306_refresh();
|
||||
ssd1306_refresh();
|
||||
|
||||
|
||||
uint8_t force_two_row_mode[] = {
|
||||
0xa8, 0, // Set MUX ratio (Actually # of lines to scan) (But it's this + 1) You can make this 1 for wider.
|
||||
};
|
||||
ssd1306_pkt_send(force_two_row_mode, sizeof( force_two_row_mode ) , 1);
|
||||
|
||||
uint8_t force_max_speed[] = {
|
||||
0xd5, 0xf0
|
||||
};
|
||||
ssd1306_pkt_send(force_max_speed, sizeof( force_max_speed ) , 1);
|
||||
|
||||
config_turbo_scope();
|
||||
#if 0 // Test streaking
|
||||
int rframe = 0;
|
||||
while(1)
|
||||
{
|
||||
PlotPoint( rframe & 0xff, rframe>>8 );
|
||||
rframe++;
|
||||
//Delay_Ms(1);
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef PROFILING_PIN
|
||||
funPinMode( PROFILING_PIN, GPIO_CFGLR_OUT_50Mhz_PP );
|
||||
#endif
|
||||
|
||||
SetupTimer1();
|
||||
|
||||
USBOTGSetup();
|
||||
|
||||
|
||||
while(1){
|
||||
#if 0
|
||||
// To draw a sinewave...
|
||||
int adcz = adc_buffer[0];
|
||||
for( k = 0; k < 128; k++ )
|
||||
{
|
||||
int y = adc_buffer[k]-adcz + 64;
|
||||
if( y < 0 ) y = 0;
|
||||
if( y > 127 ) y = 127;
|
||||
ssd1306_drawPixel( k, y, 1 );
|
||||
}
|
||||
#endif
|
||||
|
||||
// Only display half of the list so the other half could
|
||||
// be updated by the ISR.
|
||||
|
||||
#ifdef ENABLE_OLED
|
||||
int pxa = 0;
|
||||
int glread = qibaselogs_head;
|
||||
|
||||
for( pxa = 0; pxa < LOG_GOERTZEL_LIST; pxa++ )
|
||||
{
|
||||
uint32_t combiq = qibaselogs[glread];
|
||||
glread = ( glread + 1 ) & ( LOG_GOERTZEL_LIST -1 );
|
||||
|
||||
int16_t rr = combiq & 0xffff;
|
||||
int16_t ri = combiq >> 16;
|
||||
|
||||
rr = rr * 512 / (intensity_average);
|
||||
ri = ri * 512 / (intensity_average);
|
||||
|
||||
rr += 64;
|
||||
ri += 64;
|
||||
|
||||
if( rr < 0 ) rr = 0;
|
||||
if( ri < 0 ) ri = 0;
|
||||
if( rr > 127 ) rr = 127;
|
||||
if( ri > 127 ) ri = 127;
|
||||
|
||||
ssd1306_drawPixel( rr, ri, 1 );
|
||||
}
|
||||
|
||||
ssd1306_refresh();
|
||||
|
||||
ssd1306_setbuf(0);
|
||||
#endif
|
||||
|
||||
// Do nothing.
|
||||
Delay_Ms(17);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
uint8_t scratchpad[512];
|
||||
int g_isConfigurePacket = 0;
|
||||
|
||||
int HandleHidUserSetReportSetup( struct _USBState * ctx, tusb_control_request_t * req )
|
||||
{
|
||||
int id = req->wValue & 0xff;
|
||||
g_isConfigurePacket = 0;
|
||||
if( id == 0xaa && req->wLength <= sizeof( scratchpad ) )
|
||||
{
|
||||
ctx->pCtrlPayloadPtr = scratchpad;
|
||||
return req->wLength;
|
||||
}
|
||||
else if( id == 0xac && req->wLength <= sizeof( scratchpad ) )
|
||||
{
|
||||
g_isConfigurePacket = 1;
|
||||
ctx->pCtrlPayloadPtr = scratchpad;
|
||||
return req->wLength;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int HandleHidUserGetReportSetup( struct _USBState * ctx, tusb_control_request_t * req )
|
||||
{
|
||||
int id = req->wValue & 0xff;
|
||||
if( id == 0xaa )
|
||||
{
|
||||
ctx->pCtrlPayloadPtr = scratchpad;
|
||||
return 255;
|
||||
}
|
||||
else if( id == 0xac )
|
||||
{
|
||||
g_isConfigurePacket = 1;
|
||||
ctx->pCtrlPayloadPtr = scratchpad;
|
||||
return 63;
|
||||
}
|
||||
else if( id == 0xad )
|
||||
{
|
||||
static int last_baselog;
|
||||
|
||||
int samps_to_send = (qibaselogs_head - last_baselog + LOG_GOERTZEL_LIST * 2 - 1) & (LOG_GOERTZEL_LIST-1);
|
||||
if( samps_to_send > 120 ) samps_to_send = 120;
|
||||
|
||||
int intensity_send = intensity_average;
|
||||
|
||||
if( intensity_send >= (1<<24) )
|
||||
intensity_send = (1<<24)-1;
|
||||
((uint32_t*)scratchpad)[0] = (((uint32_t)intensity_send)<<8) | samps_to_send;
|
||||
((uint32_t*)scratchpad)[1] = (g_lastper<<16) | g_lastlen;
|
||||
((uint32_t*)scratchpad)[2] = (0<<16) | (((g_pwm_period+1)*g_goertzel_buffer)); //LSW = 144MHz / X
|
||||
|
||||
((uint32_t*)scratchpad)[3] = SysTick->CNT;
|
||||
((uint32_t*)scratchpad)[4] = *((uint32_t*)adc_buffer);
|
||||
|
||||
int i;
|
||||
for( i = 5; i < samps_to_send + 5; i++ )
|
||||
{
|
||||
last_baselog = (last_baselog+1)&(LOG_GOERTZEL_LIST-1);
|
||||
((uint32_t*)(scratchpad))[i] = ((int32_t*)qibaselogs)[last_baselog];
|
||||
}
|
||||
|
||||
for( ; i < 128; i++ )
|
||||
((uint32_t*)(scratchpad))[i] = 0;
|
||||
|
||||
|
||||
ctx->pCtrlPayloadPtr = scratchpad;
|
||||
return 510;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void HandleHidUserReportDataOut( struct _USBState * ctx, uint8_t * data, int len )
|
||||
{
|
||||
}
|
||||
|
||||
int HandleHidUserReportDataIn( struct _USBState * ctx, uint8_t * data, int len )
|
||||
{
|
||||
// printf( "IN %d %d %08x %08x\n", len, ctx->USBFS_SetupReqLen, data, FSUSBCTX.ENDPOINTS[0] );
|
||||
// memset( data, 0xcc, len );
|
||||
return len;
|
||||
}
|
||||
|
||||
void HandleHidUserReportOutComplete( struct _USBState * ctx )
|
||||
{
|
||||
if( g_isConfigurePacket )
|
||||
{
|
||||
|
||||
uint32_t * configs = (uint32_t*)scratchpad;
|
||||
// Note: configs[0] == 0xac (command type)
|
||||
|
||||
//printf( "Is Configure Packet %08x\n", configs[1] );
|
||||
|
||||
int numconfigs = configs[1];
|
||||
if( numconfigs > 0) g_pwm_period = configs[2];
|
||||
if( numconfigs > 1) g_goertzel_buffer = configs[3];
|
||||
if( numconfigs > 2) g_goertzel_omega_per_sample = configs[4]; // 0.816667 of whole per step / 0.880000MHz
|
||||
if( numconfigs > 3) g_goertzel_coefficient = configs[5];
|
||||
if( numconfigs > 4) g_goertzel_coefficient_s = configs[6];
|
||||
if( numconfigs > 5) g_exactcompute = configs[7];
|
||||
if( numconfigs > 6) g_goertzel_advance_r = configs[8];
|
||||
if( numconfigs > 7) g_goertzel_advance_i = configs[9];
|
||||
if( numconfigs > 8)
|
||||
{
|
||||
int adc_buffer = configs[10];
|
||||
if( adc_buffer )
|
||||
{
|
||||
// Consider using PGA.
|
||||
//ADC_Pga_16 | ADC_SCAN | ADC_BUFEN ;
|
||||
//ADC_Pga_64 | ADC_SCAN;
|
||||
ADC1->CTLR1 |= ADC_BUFEN;// | ADC_Pga_4; // Adding PGA causes wild oscillation.
|
||||
ADC1->CTLR2 |= ADC_BUFEN;// | ADC_Pga_4;
|
||||
}
|
||||
else
|
||||
{
|
||||
ADC1->CTLR1 &= (~ADC_BUFEN);
|
||||
ADC2->CTLR1 &= (~ADC_BUFEN);
|
||||
}
|
||||
}
|
||||
if( numconfigs > 9) g_attenuation_pow2 = configs[11];
|
||||
|
||||
// Need to reset so we don't blast by.
|
||||
g_goertzel_samples = 0;
|
||||
TIM1->ATRLR = g_pwm_period;
|
||||
|
||||
TIM1->CH1CVR = 1;
|
||||
TIM1->CH3CVR = TIM1->ATRLR/2+1;
|
||||
|
||||
|
||||
g_isConfigurePacket = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
#define FUNCONF_SYSTICK_USE_HCLK 1
|
||||
#define FUNCONF_ENABLE_HPE 0
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
all : test floattest phasor_rotation_test
|
||||
|
||||
phasor_rotation_testt : phasor_rotation_test.c
|
||||
gcc -o $@ $^ -lm -g
|
||||
|
||||
phasor_rotation_test : phasor_rotation_testt
|
||||
./phasor_rotation_testt
|
||||
|
||||
floattest : floattestt
|
||||
./floattestt
|
||||
|
||||
floattestt : floattestt.c
|
||||
gcc -o $@ $^ -lm -g
|
||||
|
||||
|
||||
test : ttest
|
||||
./ttest
|
||||
|
||||
ttest : ttest.c
|
||||
gcc -o $@ $^ -lm -g
|
||||
|
||||
clean :
|
||||
rm -rf *.o ttest *~ floattestt
|
||||
Binary file not shown.
@@ -0,0 +1,44 @@
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
const float omegaPerSample = 3.1415926*2.0 / 128; // pi / 200
|
||||
|
||||
// Only divide by 128 to show two cycles.
|
||||
|
||||
const int numSamples = 256; // enough to go from 0 to 2pi
|
||||
|
||||
float phase = 0;
|
||||
//for( float phase = 0; phase < 3.1415926*2.0; phase += 0.01 )
|
||||
{
|
||||
float coeff = 2 * cos( omegaPerSample );
|
||||
int i;
|
||||
|
||||
// TRICKY: When you want a sinewave, initialize with omegaPerSample. This
|
||||
// is crucial. The initial state will have massive consequences.
|
||||
float sprev = omegaPerSample;
|
||||
float sprev2 = 0;
|
||||
for( i = 0; i < numSamples; i++ )
|
||||
{
|
||||
// If you wanted to do a DFT, set SAMPLE to your incoming sample.
|
||||
float SAMPLE = 65536 * sin( phase + i * omegaPerSample );
|
||||
|
||||
// Here is where the magic happens.
|
||||
float s = SAMPLE + coeff * sprev - sprev2;
|
||||
sprev2 = sprev;
|
||||
sprev = s;
|
||||
|
||||
// For DFT, your power will be:
|
||||
float power = sprev*sprev + sprev2*sprev2 - (coeff * sprev * sprev2);
|
||||
//printf( "Power: %f\n", power );
|
||||
|
||||
float coeff_s = 2 * sin( omegaPerSample );
|
||||
double rR = 0.5 * coeff * sprev - sprev2;
|
||||
double rI = 0.5 * coeff_s * sprev;
|
||||
printf( "%d,%f,%f\n", i, rR, rI);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,43 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
int phasor_r = 32768;
|
||||
int phasor_i = 0;
|
||||
double phasor = 0;
|
||||
|
||||
double omega = 0.1;
|
||||
int omega_r = cos( omega ) * 32768;
|
||||
int omega_i = sin( omega ) * 32768;
|
||||
|
||||
int i;
|
||||
for( i = 0; i < 10000; i++ )
|
||||
{
|
||||
|
||||
int32_t temp = (phasor_r * omega_i + phasor_i * omega_r ) >> 15;
|
||||
phasor_r = (phasor_r * omega_r - phasor_i * omega_i ) >> 15;
|
||||
phasor_i = temp;
|
||||
phasor += omega;
|
||||
|
||||
|
||||
// Approximate sqrt(x*x+y*y)
|
||||
#define ABS(x) (((x)<0)?-(x):(x))
|
||||
int s = phasor_r * phasor_r + phasor_i * phasor_i;
|
||||
int intensity = (ABS(phasor_r) + ABS(phasor_i)) * 26100 / 32768 + 1; // Found experimentally (Also try to avoid divide-by-zero.
|
||||
intensity = (intensity + s/intensity)/2;
|
||||
intensity = (intensity + s/intensity)/2;
|
||||
|
||||
if( intensity < 32763 )
|
||||
{
|
||||
phasor_r += phasor_r >> 12;
|
||||
phasor_i += phasor_i >> 12;
|
||||
}
|
||||
|
||||
double fA = atan2( phasor_i, phasor_r );
|
||||
printf( "%6d %6d / %6d %6d / %d / %f %f %f\n", omega_r, omega_i, phasor_r, phasor_i, intensity, fA, phasor, fA-phasor );
|
||||
if( phasor >= 3.141592653589 ) phasor -= 3.141592653589*2;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
|
||||
uint32_t g_goertzel_omega_per_sample;
|
||||
int32_t g_goertzel_coefficient;
|
||||
int32_t g_goertzel_coefficient_s;
|
||||
uint32_t g_goertzel_samples;
|
||||
uint32_t g_goertzel_outs;
|
||||
int32_t g_goertzelp, g_goertzelp2;
|
||||
int32_t g_goertzelp_store, g_goertzelp2_store;
|
||||
|
||||
int main()
|
||||
{
|
||||
//XXX XXX NOTE If you are computing the coefficients, you can plug the value in here.
|
||||
// You can get this number from calculator.html. I've had better luck with "inverse goertzel" numbers.
|
||||
g_goertzel_omega_per_sample = (47.0/256) * 3.1415926535*2.0*(1<<29);
|
||||
g_goertzel_coefficient = 2 * cos( g_goertzel_omega_per_sample / (double)(1<<29) ) * (1<<30);
|
||||
g_goertzel_coefficient_s = 2 * sin( g_goertzel_omega_per_sample / (double)(1<<29) ) * (1<<30);
|
||||
|
||||
|
||||
const double AomegaPerSample = g_goertzel_omega_per_sample/(double)(1<<29);
|
||||
const int AnumSamples = 256; // enough to go from 0 to 2pi
|
||||
double Acoeff = 2 * cos( AomegaPerSample ) * 65536;
|
||||
double Acoeff_s = 2 * sin( AomegaPerSample ) * 65536;
|
||||
double Asprev = AomegaPerSample * 65536;
|
||||
double Asprev2 = 0;
|
||||
|
||||
printf( "%d / %d / %d %f / %f / %f\n", g_goertzel_omega_per_sample, g_goertzel_coefficient, g_goertzel_coefficient_s, Acoeff, Acoeff_s, AomegaPerSample );
|
||||
|
||||
|
||||
g_goertzelp = g_goertzel_omega_per_sample>>(29-16);
|
||||
|
||||
int32_t goertzel_coefficient = g_goertzel_coefficient;
|
||||
int32_t goertzelp2 = g_goertzelp2;
|
||||
int32_t goertzelp = g_goertzelp;
|
||||
uint32_t goertzel_samples = g_goertzel_samples;
|
||||
|
||||
uint32_t adc_tail;
|
||||
|
||||
double As;
|
||||
|
||||
int js = 0;
|
||||
for( js = 0; js < 260/4; js++ )
|
||||
{
|
||||
int32_t t; // 1/2 of 4096, to try to keep our numbers reasonable.
|
||||
|
||||
// Here is where the magic happens.
|
||||
int32_t goertzel;
|
||||
|
||||
#define ITERATION(x) \
|
||||
t = sin( AomegaPerSample * (x+js*4) ) * 16384*0; \
|
||||
\
|
||||
/* Fixed */ \
|
||||
goertzelp2 = goertzelp; \
|
||||
goertzelp = goertzel; \
|
||||
goertzel = t + ( ( (((int32_t)(goertzel_coefficient))) * ((((int64_t)goertzelp)<<2)) ) >> 32 ) - goertzelp2; \
|
||||
\
|
||||
/* Float */ \
|
||||
Asprev2 = Asprev; \
|
||||
Asprev = As; \
|
||||
As = t + ( Acoeff * Asprev ) / 65536.0 - Asprev2; \
|
||||
\
|
||||
/*printf( "%d,%d,%d,%d\n", ( ( (int64_t)(goertzel_coefficient) * (int64_t)goertzelp ) >> 32 ) , goertzel_coefficient, goertzelp, goertzelp2 ); */ \
|
||||
\
|
||||
{\
|
||||
int32_t rr = (((int64_t)(g_goertzel_coefficient ) * (int64_t)goertzelp<<1)>>32) - (goertzelp2); \
|
||||
int32_t ri = (((int64_t)(g_goertzel_coefficient_s) * (int64_t)goertzelp<<1)>>32); \
|
||||
/*printf( "%3d %10d %10d %10d %10d / %9d %9d %9d * ", js*4+x, rr, ri, goertzelp, goertzelp2, goertzel_coefficient, g_goertzel_omega_per_sample, t );*/ \
|
||||
/*printf( "%4d %10d %10d (%10d %10d) ", js*4+x, goertzelp, goertzelp2, goertzel_coefficient, g_goertzel_coefficient_s );*/ \
|
||||
printf( "%4d %10d %10d (%10d %10d) ", js*4+x, goertzelp, goertzelp2, rr, ri ); \
|
||||
\
|
||||
float Apower = Asprev*Asprev + Asprev2*Asprev2 - (Acoeff * Asprev * Asprev2); \
|
||||
double ArR = 0.5 * Acoeff * Asprev / 65536 - Asprev2; \
|
||||
double ArI = 0.5 * Acoeff_s * Asprev / 65536; \
|
||||
/*printf( "%14.3f, %14.3f (%14.3f %14.3f)\n", Asprev, Asprev2, Acoeff,Acoeff_s );*/ \
|
||||
printf( "%14.3f, %14.3f (%14.3f %14.3f %f)\n", Asprev, Asprev2, ArR, ArI, sqrt( ArR*ArR +ArI*ArI ) ); \
|
||||
}
|
||||
|
||||
|
||||
ITERATION( 0 );
|
||||
ITERATION( 1 );
|
||||
ITERATION( 2 );
|
||||
ITERATION( 3 );
|
||||
|
||||
adc_tail+=4;
|
||||
goertzel_samples+=4;
|
||||
// if( adc_tail == adc_buffer_top ) adc_tail = adc_buffer;
|
||||
|
||||
/* if( goertzel_samples == 128 )
|
||||
{
|
||||
g_goertzelp_store = goertzelp;
|
||||
g_goertzelp2_store = goertzelp2;
|
||||
|
||||
goertzelp = 0;
|
||||
goertzelp2 = 0;
|
||||
|
||||
g_goertzel_outs++;
|
||||
goertzel_samples = 0;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
g_goertzelp2 = goertzelp2;
|
||||
g_goertzelp = goertzelp;
|
||||
g_goertzel_samples = goertzel_samples;
|
||||
|
||||
printf( "Constants:\nconst int32_t g_goertzel_omega_per_sample = %d;\nconst int32_t g_goertzel_coefficient = %d;\nconst int32_t g_goertzel_coefficient_s = %d;\n", g_goertzel_omega_per_sample, g_goertzel_coefficient, g_goertzel_coefficient_s );
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
#ifndef _USB_CONFIG_H
|
||||
#define _USB_CONFIG_H
|
||||
|
||||
#include "funconfig.h"
|
||||
#include "ch32v003fun.h"
|
||||
|
||||
#define FUSB_CONFIG_EPS 2 // Include EP0 in this count
|
||||
#define FUSB_SUPPORTS_SLEEP 0
|
||||
#define FUSB_HID_INTERFACES 1
|
||||
#define FUSB_CURSED_TURBO_DMA 0 // Hacky, but seems fine, shaves 2.5us off filling 64-byte buffers.
|
||||
#define FUSB_HID_USER_REPORTS 1
|
||||
#define FUSB_IO_PROFILE 1
|
||||
#define FUSB_USE_HPE FUNCONF_ENABLE_HPE
|
||||
|
||||
#include "usb_defines.h"
|
||||
|
||||
//Taken from http://www.usbmadesimple.co.uk/ums_ms_desc_dev.htm
|
||||
static const uint8_t device_descriptor[] = {
|
||||
18, //Length
|
||||
1, //Type (Device)
|
||||
0x00, 0x02, //Spec
|
||||
0x0, //Device Class
|
||||
0x0, //Device Subclass
|
||||
0x0, //Device Protocol (000 = use config descriptor)
|
||||
64, //Max packet size for EP0 (This has to be 8 because of the USB Low-Speed Standard)
|
||||
0x09, 0x12, //ID Vendor
|
||||
0x35, 0xd0, //ID Product
|
||||
0x03, 0x00, //ID Rev
|
||||
1, //Manufacturer string
|
||||
2, //Product string
|
||||
3, //Serial string
|
||||
1, //Max number of configurations
|
||||
};
|
||||
|
||||
static const uint8_t HIDAPIRepDesc[ ] =
|
||||
{
|
||||
HID_USAGE_PAGE ( 0xff ), // Vendor-defined page.
|
||||
HID_USAGE ( 0x00 ),
|
||||
HID_REPORT_SIZE ( 8 ),
|
||||
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),
|
||||
HID_REPORT_COUNT ( 254 ),
|
||||
HID_REPORT_ID ( 0xaa )
|
||||
HID_USAGE ( 0x01 ),
|
||||
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,
|
||||
HID_REPORT_COUNT ( 63 ), // For use with `hidapitester --vidpid 1209/D003 --open --read-feature 171`
|
||||
HID_REPORT_ID ( 0xab )
|
||||
HID_USAGE ( 0x01 ),
|
||||
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,
|
||||
HID_REPORT_COUNT ( 63 ), // For configuring the setup.
|
||||
HID_REPORT_ID ( 0xac )
|
||||
HID_USAGE ( 0x01 ),
|
||||
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,
|
||||
HID_REPORT_COUNT_N ( 510,2 ), // For receiving IQ data on host.
|
||||
HID_REPORT_ID ( 0xad )
|
||||
HID_USAGE ( 0x01 ),
|
||||
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,
|
||||
HID_COLLECTION_END,
|
||||
};
|
||||
|
||||
/* Configuration Descriptor Set */
|
||||
static const uint8_t config_descriptor[ ] =
|
||||
{
|
||||
/* Configuration Descriptor */
|
||||
0x09, // bLength
|
||||
0x02, // bDescriptorType
|
||||
0x22, 0x00, // wTotalLength
|
||||
0x01, // bNumInterfaces (3)
|
||||
0x01, // bConfigurationValue
|
||||
0x00, // iConfiguration
|
||||
0xA0, // bmAttributes: Bus Powered; Remote Wakeup
|
||||
0x32, // MaxPower: 100mA
|
||||
|
||||
/* Interface Descriptor (Special) */
|
||||
0x09, // bLength
|
||||
0x04, // bDescriptorType
|
||||
0x00, // bInterfaceNumber
|
||||
0x01, // bAlternateSetting
|
||||
0x01, // bNumEndpoints
|
||||
0x03, // bInterfaceClass
|
||||
0x00, // bInterfaceSubClass
|
||||
0xff, // bInterfaceProtocol: OTher
|
||||
0x00, // iInterface
|
||||
|
||||
/* HID Descriptor (Special) */
|
||||
0x09, // bLength
|
||||
0x21, // bDescriptorType
|
||||
0x10, 0x01, // bcdHID
|
||||
0x00, // bCountryCode
|
||||
0x01, // bNumDescriptors
|
||||
0x22, // bDescriptorType
|
||||
sizeof(HIDAPIRepDesc), 0x00, // wDescriptorLength
|
||||
|
||||
/* Endpoint Descriptor (Special) */
|
||||
0x07, // bLength
|
||||
0x05, // bDescriptorType
|
||||
0x81, // bEndpointAddress: IN Endpoint 1
|
||||
0x03, // bmAttributes
|
||||
0x08, 0x00, // wMaxPacketSize
|
||||
0xff, // bInterval: slow.
|
||||
};
|
||||
|
||||
|
||||
|
||||
#define STR_MANUFACTURER u"CNLohr"
|
||||
#define STR_PRODUCT u"lolra ch32v203 goertzel test"
|
||||
#define STR_SERIAL u"CUSTOMDEVICE000"
|
||||
|
||||
struct usb_string_descriptor_struct {
|
||||
uint8_t bLength;
|
||||
uint8_t bDescriptorType;
|
||||
uint16_t wString[];
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string0 __attribute__((section(".rodata"))) = {
|
||||
4,
|
||||
3,
|
||||
{0x0409}
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string1 __attribute__((section(".rodata"))) = {
|
||||
sizeof(STR_MANUFACTURER),
|
||||
3,
|
||||
STR_MANUFACTURER
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string2 __attribute__((section(".rodata"))) = {
|
||||
sizeof(STR_PRODUCT),
|
||||
3,
|
||||
STR_PRODUCT
|
||||
};
|
||||
const static struct usb_string_descriptor_struct string3 __attribute__((section(".rodata"))) = {
|
||||
sizeof(STR_SERIAL),
|
||||
3,
|
||||
STR_SERIAL
|
||||
};
|
||||
|
||||
// This table defines which descriptor data is sent for each specific
|
||||
// request from the host (in wValue and wIndex).
|
||||
const static struct descriptor_list_struct {
|
||||
uint32_t lIndexValue;
|
||||
const uint8_t *addr;
|
||||
uint8_t length;
|
||||
} descriptor_list[] = {
|
||||
{0x00000100, device_descriptor, sizeof(device_descriptor)},
|
||||
{0x00000200, config_descriptor, sizeof(config_descriptor)},
|
||||
// interface number // 2200 for hid descriptors.
|
||||
{0x00002200, HIDAPIRepDesc, sizeof(HIDAPIRepDesc)},
|
||||
|
||||
{0x00002100, config_descriptor + 18, 9 }, // Not sure why, this seems to be useful for Windows + Android.
|
||||
|
||||
{0x00000300, (const uint8_t *)&string0, 4},
|
||||
{0x04090301, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)},
|
||||
{0x04090302, (const uint8_t *)&string2, sizeof(STR_PRODUCT)},
|
||||
{0x04090303, (const uint8_t *)&string3, sizeof(STR_SERIAL)}
|
||||
};
|
||||
#define DESCRIPTOR_LIST_ENTRIES ((sizeof(descriptor_list))/(sizeof(struct descriptor_list_struct)) )
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -2,6 +2,7 @@ all : flash
|
||||
|
||||
TARGET:=loratest
|
||||
TARGET_MCU:=CH32V203
|
||||
TARGET_MCU_PACKAGE:=C8
|
||||
CH32V003FUN:=../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_ELF_DEPENDENCIES:=chirpbuff.h
|
||||
@@ -0,0 +1,13 @@
|
||||
all : flash
|
||||
|
||||
TARGET:=ch32v203tx
|
||||
TARGET_MCU:=CH32V203
|
||||
CH32V003FUN:=../ch32v003fun/ch32v003fun
|
||||
|
||||
EXTRA_CFLAGS:=-Wno-unused-function -I../../lib
|
||||
|
||||
include $(CH32V003FUN)/ch32v003fun.mk
|
||||
|
||||
flash : cv_flash
|
||||
clean : cv_clean
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// This file is under the standard MIT license, CC0 or Public domain. you choose.
|
||||
// CNLohr <>< 2024
|
||||
// It just does a normal PWM output from a ch32v203
|
||||
|
||||
#include "ch32v003fun.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#define LEDPIN PD6
|
||||
|
||||
int main()
|
||||
{
|
||||
SystemInit();
|
||||
|
||||
Delay_Ms( 100 );
|
||||
|
||||
|
||||
funGpioInitAll();
|
||||
RCC->APB1PCENR |= RCC_APB1Periph_TIM2;
|
||||
// PD4 = T2C1 on 003, PA0 on the 203.
|
||||
funPinMode( PA0, GPIO_CFGLR_OUT_50Mhz_AF_PP );
|
||||
funPinMode( PA1, GPIO_CFGLR_OUT_50Mhz_AF_PP );
|
||||
funPinMode( LEDPIN, GPIO_CFGLR_OUT_50Mhz_PP );
|
||||
|
||||
// Reset TIM2 to init all regs
|
||||
RCC->APB1PRSTR |= RCC_APB1Periph_TIM2;
|
||||
RCC->APB1PRSTR &= ~RCC_APB1Periph_TIM2;
|
||||
|
||||
TIM2->PSC = 0x0000; // Prescalar
|
||||
TIM2->ATRLR = 4; // loop = fclk / (atrlr+1)
|
||||
TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE | TIM_OC1FE;
|
||||
TIM2->CTLR1 = TIM_ARPE;
|
||||
TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NE;
|
||||
TIM2->SWEVGR = TIM_UG;
|
||||
|
||||
// Enable TIM2
|
||||
TIM2->CTLR1 |= TIM_CEN;
|
||||
TIM2->CH1CVR = TIM2->ATRLR/2+1;
|
||||
|
||||
printf( "Setup\n" );
|
||||
while(1)
|
||||
{
|
||||
TIM2->CH1CVR = 2;
|
||||
TIM2->CCER = TIM_CC1E | TIM_CC1P;
|
||||
funDigitalWrite( LEDPIN, 1 );
|
||||
Delay_Us( 20000 );
|
||||
TIM2->CCER = TIM_CC1E;
|
||||
TIM2->CH1CVR = 2;
|
||||
funDigitalWrite( LEDPIN, 0 );
|
||||
Delay_Us( 20000 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef _FUNCONFIG_H
|
||||
#define _FUNCONFIG_H
|
||||
|
||||
#define FUNCONF_USE_DEBUGPRINTF 1
|
||||
#define FUNCONF_USE_UARTPRINTF 0
|
||||
#define FUNCONF_USE_HSE 1
|
||||
|
||||
#endif
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
# The "calculator" tools
|
||||
|
||||
Including the host side code for the ch32v203 goertzel tuner.
|
||||
|
||||
The font used, AudioLink is from https://audiolink.dev/ by Llealloo and are "(PUBLIC DOMAIN / free to use)" (as of 6/22/2024)
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
/*
|
||||
Copyright (c) 2024 by Brett Schwickerath (https://codepen.io/schwiiiii/pen/wvVqLmX)
|
||||
Modified
|
||||
Copyright (c) 2024 by cnlohr
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
||||
software and associated documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without limitation the rights to use, copy,
|
||||
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
and to permit persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
@font-face {
|
||||
font-family: 'AudioLink';
|
||||
src: url('AudioLinkMono-Bold.ttf') format('truetype')
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--gl: radial-gradient(circle 1px at 0px 0px, var(--light) 1px, transparent 0);
|
||||
--gd: radial-gradient(circle 1px at 0px 0px, var(--dark) 1px, transparent 0);
|
||||
--dark: #111;
|
||||
--light: #eee;
|
||||
--bg-0: var(--dark);
|
||||
--bg-1: var(--gl) 0px 0px / 4px 4px, var(--dark);
|
||||
--bg-2: var(--gl) 0px 0px / 4px 4px, var(--gl) 2px 2px / 4px 4px, var(--dark);
|
||||
--bg-3: var(--gl) 0px 0px / 2px 2px, var(--dark);
|
||||
--bg-4: var(--gl) 0px 0px / 2px 2px, var(--gl) 1px 1px / 2px 2px, var(--dark);
|
||||
--bg-5: var(--gd) 0px 0px / 2px 2px, var(--light);
|
||||
--bg-6: var(--gd) 0px 0px / 4px 4px, var(--gd) 2px 2px / 4px 4px, var(--light);
|
||||
--bg-7: var(--gd) 0px 0px / 4px 4px, var(--light);
|
||||
--bg-8: var(--light);
|
||||
|
||||
--l-shadow:
|
||||
-1px -1px 0 var(--dark),
|
||||
0 -1px 0 var(--dark),
|
||||
1px -1px 0 var(--dark),
|
||||
1px 0 0 var(--dark),
|
||||
1px 1px 0 var(--dark),
|
||||
0 1px 0 var(--dark),
|
||||
-1px 1px 0 var(--dark),
|
||||
-1px 0 0 var(--dark);
|
||||
|
||||
--d-shadow:
|
||||
-1px -1px 0 var(--light),
|
||||
0 -1px 0 var(--light),
|
||||
1px -1px 0 var(--light),
|
||||
1px 0 0 var(--light),
|
||||
1px 1px 0 var(--light),
|
||||
0 1px 0 var(--light),
|
||||
-1px 1px 0 var(--light),
|
||||
-1px 0 0 var(--light);
|
||||
|
||||
--drop-shadow:
|
||||
drop-shadow(-1px -1px 0 var(--light))
|
||||
drop-shadow(0 -1px 0 var(--light))
|
||||
drop-shadow(1px -1px 0 var(--light))
|
||||
drop-shadow(1px 0 0 var(--light))
|
||||
drop-shadow(1px 1px 0 var(--light))
|
||||
drop-shadow(0 1px 0 var(--light))
|
||||
drop-shadow(-1px 1px 0 var(--light))
|
||||
drop-shadow(-1px 0 0 var(--light));
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
font-family: "AudioLink", monospace;
|
||||
text-rendering: optimizeSpeed;
|
||||
font-size: inherit;
|
||||
color: light-dark(var(--dark), var(--light));
|
||||
}
|
||||
|
||||
html {
|
||||
/*font-size: 1vmin;*/
|
||||
/* animation:
|
||||
adjust-light 17s linear infinite both,
|
||||
adjust-dark 11s linear infinite both; */
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/*
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
*/
|
||||
gap: 4rem;
|
||||
background: var(--dark);
|
||||
}
|
||||
|
||||
.shades {
|
||||
display: inline-flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.shade {
|
||||
height: calc(80rem / 9);
|
||||
width: calc(80rem / 9);
|
||||
border-radius: 50%;
|
||||
border: 3px solid var(--light);
|
||||
|
||||
&:nth-child(1) { background: var(--bg-0); }
|
||||
&:nth-child(2) { background: var(--bg-1); }
|
||||
&:nth-child(3) { background: var(--bg-2); }
|
||||
&:nth-child(4) { background: var(--bg-3); }
|
||||
&:nth-child(5) { background: var(--bg-4); }
|
||||
&:nth-child(6) { background: var(--bg-5); }
|
||||
&:nth-child(7) { background: var(--bg-6); }
|
||||
&:nth-child(8) { background: var(--bg-7); }
|
||||
&:nth-child(9) { background: var(--bg-8); }
|
||||
}
|
||||
|
||||
form {
|
||||
font-size: 2rem;
|
||||
background: var(--bg-4);
|
||||
padding: 2rem;
|
||||
border-radius: 2rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
border: 3px var(--light) solid;
|
||||
}
|
||||
|
||||
label {
|
||||
background: var(--bg-1);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: .5rem;
|
||||
padding: 1rem;
|
||||
border-radius: 1rem;
|
||||
text-shadow: var(--l-shadow);
|
||||
border: 1px var(--light) solid;
|
||||
color: var(--light);
|
||||
}
|
||||
|
||||
|
||||
input::-webkit-outer-spin-button,
|
||||
input::-webkit-inner-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
/*.scrollwheel_tune{*/
|
||||
input[type=number] {
|
||||
background: var(--bg-0);
|
||||
outline: 0;
|
||||
-moz-appearance:textfield; /* Firefox */
|
||||
padding-top: 1rem;
|
||||
padding-bottom: 1rem;
|
||||
padding-left: 1.1rem;
|
||||
padding-right: 1.0rem;
|
||||
text-shadow: var(--l-shadow);
|
||||
border: 1px var(--light) solid;
|
||||
animation: dark-to-light 200ms ease-out forwards;
|
||||
transition: 200ms ease-out;
|
||||
border-radius: 1.5rem;
|
||||
&:hover {
|
||||
animation: light-to-dark 200ms linear forwards;
|
||||
color: var(--dark);
|
||||
text-shadow: var(--d-shadow);
|
||||
}
|
||||
}
|
||||
|
||||
textarea,input:not([type='number']) {
|
||||
background: var(--bg-0);
|
||||
border: 0;
|
||||
overflow:hidden;
|
||||
outline: 0;
|
||||
border-radius: .8rem;
|
||||
padding: .5rem;
|
||||
padding-bottom:.3rem;
|
||||
text-shadow: var(--l-shadow);
|
||||
border: 1px var(--light) solid;
|
||||
animation: dark-to-light 200ms ease-out forwards;
|
||||
transition: 200ms ease-out;
|
||||
|
||||
&:hover {
|
||||
animation: light-to-dark 200ms linear forwards;
|
||||
color: var(--dark);
|
||||
text-shadow: var(--d-shadow);
|
||||
}
|
||||
}
|
||||
|
||||
button,input[type=submit] {
|
||||
background: var(--bg-0);
|
||||
border: 0;
|
||||
outline: 0;
|
||||
border-radius: 2rem;
|
||||
padding: .7rem;
|
||||
font-weight: bold;
|
||||
text-shadow: var(--l-shadow);
|
||||
cursor: pointer;
|
||||
border: 1px var(--light) solid;
|
||||
color: var(--light);
|
||||
animation: dark-to-light 200ms ease-out forwards;
|
||||
transition: 200ms ease-out;
|
||||
|
||||
&:hover {
|
||||
animation: light-to-dark 200ms linear forwards;
|
||||
color: var(--dark);
|
||||
text-shadow: var(--d-shadow);
|
||||
}
|
||||
}
|
||||
|
||||
.cube-wrapper {
|
||||
--size: 8rem;
|
||||
margin-top: 2rem;
|
||||
perspective: 200px;
|
||||
perspective-origin: 50% 0%;
|
||||
filter: var(--drop-shadow);
|
||||
}
|
||||
|
||||
.cube {
|
||||
height: var(--size);
|
||||
width: var(--size);
|
||||
position: relative;
|
||||
transform-style: preserve-3d;
|
||||
transform-origin: 50% 50% calc(var(--size) * .5);
|
||||
animation: rotate 10s linear infinite;
|
||||
}
|
||||
|
||||
.face {
|
||||
position: absolute;
|
||||
height: var(--size);
|
||||
width: var(--size);
|
||||
transform-style: preserve-3d;
|
||||
transform-origin: 50% 50% calc(var(--size) * .5);
|
||||
|
||||
&:nth-child(1) { transform: rotateY(90deg); background: var(--bg-2); }
|
||||
&:nth-child(2) { transform: rotateY(180deg); background: var(--bg-3) }
|
||||
&:nth-child(3) { transform: rotateY(-90deg); background: var(--bg-4) }
|
||||
&:nth-child(4) { transform: rotateX(90deg); background: var(--bg-5) }
|
||||
&:nth-child(5) { transform: rotateX(-90deg); background: var(--bg-6) }
|
||||
&:nth-child(6) { background: var(--bg-7) }
|
||||
}
|
||||
|
||||
@keyframes light-to-dark {
|
||||
0% { background: var(--bg-0); }
|
||||
12.5% { background: var(--bg-1); }
|
||||
25% { background: var(--bg-2); }
|
||||
37.5% { background: var(--bg-3); }
|
||||
50% { background: var(--bg-4); }
|
||||
62.5% { background: var(--bg-5); }
|
||||
75% { background: var(--bg-6); }
|
||||
87.5% { background: var(--bg-7); }
|
||||
100% { background: var(--bg-8); }
|
||||
}
|
||||
|
||||
@keyframes dark-to-light {
|
||||
0% { background: var(--bg-8); }
|
||||
12.5% { background: var(--bg-7); }
|
||||
25% { background: var(--bg-6); }
|
||||
37.5% { background: var(--bg-5); }
|
||||
50% { background: var(--bg-4); }
|
||||
62.5% { background: var(--bg-3); }
|
||||
75% { background: var(--bg-2); }
|
||||
87.5% { background: var(--bg-1); }
|
||||
100% { background: var(--bg-0); }
|
||||
}
|
||||
|
||||
@keyframes rotate {
|
||||
from { transform: rotateY(0) rotateX(1turn) rotateZ(0) }
|
||||
to { transform: rotateY(1turn) rotateX(0) rotateZ(1turn) }
|
||||
}
|
||||
|
||||
@keyframes adjust-dark {
|
||||
0% { --dark: hsl(0turn, 100%, 80%); }
|
||||
10% { --dark: hsl(.1turn, 100%, 80%); }
|
||||
20% { --dark: hsl(.2turn, 100%, 80%); }
|
||||
30% { --dark: hsl(.3turn, 100%, 80%); }
|
||||
40% { --dark: hsl(.4turn, 100%, 80%); }
|
||||
50% { --dark: hsl(.5turn, 100%, 80%); }
|
||||
60% { --dark: hsl(.6turn, 100%, 80%); }
|
||||
70% { --dark: hsl(.7turn, 100%, 80%); }
|
||||
80% { --dark: hsl(.8turn, 100%, 80%); }
|
||||
90% { --dark: hsl(.9turn, 100%, 80%); }
|
||||
100% { --dark: hsl(1turn, 100%, 80%); }
|
||||
}
|
||||
|
||||
@keyframes adjust-light {
|
||||
0% { --light: hsl(0turn, 100%, 20%); }
|
||||
10% { --light: hsl(.1turn, 100%, 20%); }
|
||||
20% { --light: hsl(.2turn, 100%, 20%); }
|
||||
30% { --light: hsl(.3turn, 100%, 20%); }
|
||||
40% { --light: hsl(.4turn, 100%, 20%); }
|
||||
50% { --light: hsl(.5turn, 100%, 20%); }
|
||||
60% { --light: hsl(.6turn, 100%, 20%); }
|
||||
70% { --light: hsl(.7turn, 100%, 20%); }
|
||||
80% { --light: hsl(.8turn, 100%, 20%); }
|
||||
90% { --light: hsl(.9turn, 100%, 20%); }
|
||||
100% { --light: hsl(1turn, 100%, 20%); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<!-- This file is under the regular MIT license.
|
||||
|
||||
Copyright 2024 Charles Lohr (cnlohr)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-->
|
||||
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<LINK rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
|
||||
<link rel="stylesheet" type="text/css" href="calculator.css" />
|
||||
<META charset="UTF-8"/>
|
||||
<SCRIPT src=webhidcontrol.js></SCRIPT>
|
||||
<SCRIPT>
|
||||
var darkmode = true;
|
||||
|
||||
//body { background-color: Canvas; color: CanvasText; }
|
||||
|
||||
function DrawSpan( rowspan, colspan, freq, target, docolor, extrastr = "" )
|
||||
{
|
||||
var fdist = Math.abs( freq - target );
|
||||
fdist = Math.pow( fdist, 0.5 ) * 300;
|
||||
if( fdist > 511 ) fdist = 511;
|
||||
|
||||
let ret = "<TD COLSPAN=" + colspan + ' ROWSPAN' + rowspan + ' ';
|
||||
|
||||
let bg = 8 - fdist / 60;
|
||||
if( bg < 0) bg = 0; if( bg > 8 ) bg = 8;
|
||||
if( docolor ) ret += 'STYLE="color:var(--' + ((bg >= 3 ) ? 'dark' : 'light' ) + ');' +
|
||||
'text-shadow: 1px 1px 2px ' + ((bg < 3 ) ? '#000' : '#fff' ) + ',' +
|
||||
'-1px 1px 2px ' + ((bg < 3 ) ? '#000' : '#fff' ) + ',' +
|
||||
'1px -1px 2px ' + ((bg < 3 ) ? '#000' : '#fff' ) + ',' +
|
||||
'-1px -1px 2px ' + ((bg < 3 ) ? '#000' : '#fff' ) + ';' +
|
||||
'background:var(--bg-' + bg.toFixed(0) + ');"';
|
||||
//background-color:rgba(' + fdist + ',' + (511-fdist) + ',0,0.2)";';
|
||||
ret += '>' + extrastr + freq.toFixed(6) + "</TD>";
|
||||
return ret;
|
||||
}
|
||||
|
||||
var system_rate = 288000000; // in MHz for effective ADC (note: This can be 2x normal clock if in dual ADC mode)
|
||||
var lastGn;
|
||||
var lastGmhz;
|
||||
var lastGfr;
|
||||
var lastGbrf;
|
||||
var lastGexact;
|
||||
var lastTargetMHz;
|
||||
|
||||
function Goertz( n, mhz, fr, brf, exact_compute, targetmhz )
|
||||
{
|
||||
lastGn = n;
|
||||
lastGmhz = mhz;
|
||||
lastGfr = fr;
|
||||
lastGbrf = brf;
|
||||
lastGexact = exact_compute;
|
||||
lastTargetMHz = targetmhz;
|
||||
SendGoertz();
|
||||
}
|
||||
|
||||
function SendGoertz()
|
||||
{
|
||||
var n = lastGn;
|
||||
var mhz = lastGmhz;
|
||||
var fr = lastGfr;
|
||||
var brf = lastGbrf;
|
||||
var exact_compute = lastGexact;
|
||||
|
||||
let tau = 3.1415926535*2.0;
|
||||
let omega = fr * tau;
|
||||
var textarea = document.getElementById("goertzeloutput");
|
||||
var g_attenuation_pow2 = Number( document.getElementById( "g_attenuation_pow2" ).value );
|
||||
|
||||
var goertzel_omega_per_sample_real = ( omega*2*(1<<29));
|
||||
var g_goertzel_omega_per_sample = Math.round( goertzel_omega_per_sample_real );
|
||||
var g_goertzel_coefficient = Math.round( (2 * Math.cos( omega ) * (1<<30)) );
|
||||
var g_goertzel_coefficient_s = Math.round( (2 * Math.sin( omega ) * (1<<30)) );
|
||||
|
||||
var omega_per_group = omega * brf;
|
||||
var goertzel_phasor_advance_radians_per_sample = tau * (Math.round( omega_per_group / tau ) - omega_per_group / tau);
|
||||
var g_goertzel_advance_r = Math.cos( goertzel_phasor_advance_radians_per_sample ) * 32768;
|
||||
var g_goertzel_advance_i = Math.sin( goertzel_phasor_advance_radians_per_sample ) * 32768;
|
||||
|
||||
var g_exactcompute = exact_compute;
|
||||
|
||||
if( textarea )
|
||||
{
|
||||
textarea.value =
|
||||
"int g_pwm_period = ("+n+"-1); // " + system_rate/lastGn/1000000. + " MHz Samplerate\n" +
|
||||
"int g_exactcompute = ("+exact_compute+");\n" +
|
||||
"int g_goertzel_buffer = ("+brf+");\n" +
|
||||
"int32_t g_goertzel_omega_per_sample = " + g_goertzel_coefficient.toFixed(0) + "; // " + ( omega / (3.1415926535*2.0)).toFixed(6) + " of whole per step / " + mhz.toFixed(6) + "MHz\n" +
|
||||
"int32_t g_goertzel_coefficient = " + g_goertzel_coefficient.toFixed(0) + ";\n" +
|
||||
"int32_t g_goertzel_coefficient_s = " + g_goertzel_coefficient_s.toFixed(0) + ";\n" +
|
||||
"int32_t g_goertzel_advance_r = " + g_goertzel_advance_r.toFixed(0) + ";\n" +
|
||||
"int32_t g_goertzel_advance_i = " + g_goertzel_advance_i.toFixed(0) + ";\n";
|
||||
"int32_t g_attenuation_pow2 = " + g_attenuation_pow2.toFixed(0) + ";\n";
|
||||
|
||||
// Highlight its content
|
||||
textarea.select();
|
||||
|
||||
// Copy the highlighted text
|
||||
document.execCommand("copy");
|
||||
|
||||
}
|
||||
|
||||
updateWebHidDeviceWithParameters( [
|
||||
(n-1)|0,
|
||||
brf|0,
|
||||
g_goertzel_omega_per_sample|0,
|
||||
g_goertzel_coefficient|0,
|
||||
g_goertzel_coefficient_s|0,
|
||||
exact_compute|0,
|
||||
g_goertzel_advance_r|0,
|
||||
g_goertzel_advance_i|0,
|
||||
document.getElementById( "toggle_adc_buffer").checked ? 1 : 0,
|
||||
g_attenuation_pow2,
|
||||
] );
|
||||
|
||||
// Update toggle control
|
||||
let target = lastTargetMHz;
|
||||
var tz = (target * 10000000.0) + 0.05;
|
||||
for( var i = 0|0; i < 10; i++ )
|
||||
{
|
||||
var tc = (tz / 1000000000.0) % 10;
|
||||
if( document.getElementById( "mhzm" + i ) )
|
||||
document.getElementById( "mhzm" + i ).value = tc|0;
|
||||
tz *= 10;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleBuffer( ths )
|
||||
{
|
||||
SendGoertz();
|
||||
}
|
||||
|
||||
function attenuationpow2wheel( event, ths )
|
||||
{
|
||||
event.preventDefault();
|
||||
let dy = event.deltaY > 0 ? -1 : 1;
|
||||
var thss = Number(ths.value) + dy;
|
||||
if( thss < -9 ) thss = -9;
|
||||
if( thss > 9 ) thss = 9;
|
||||
ths.value = thss;
|
||||
UpdateQuickSettings();
|
||||
}
|
||||
|
||||
function mhzm( event, ths )
|
||||
{
|
||||
event.preventDefault();
|
||||
let dy = event.deltaY > 0 ? -1 : 1;
|
||||
var thss = Number(ths.id.substr(4));
|
||||
|
||||
var hz = 0; // actually tents of hertz
|
||||
for( var i = 0|0; i < 10; i++ )
|
||||
{
|
||||
var dig = Number(document.getElementById( "mhzm" + i ).value);
|
||||
hz += Math.pow( 10, 9-i ) * dig;
|
||||
}
|
||||
|
||||
hz += dy * Math.pow( 10, 9-thss );
|
||||
|
||||
lastGmhz = hz/10000000.0;
|
||||
document.getElementById("targetmhz").value = lastGmhz;
|
||||
UpdateQuickSettings();
|
||||
}
|
||||
|
||||
function UpdateQuickSettings()
|
||||
{
|
||||
let xtal = Number(document.getElementById("crystalmhz").value );
|
||||
let target = Number(document.getElementById("targetmhz").value );
|
||||
let quadrature = document.getElementById("QUADRATURE").checked;
|
||||
let goertzels = document.getElementById("GOERTZELS").checked;
|
||||
let goertzel2 = document.getElementById("GOERTZEL2").checked;
|
||||
let quanta = Math.round(Number(document.getElementById("quanta").value));
|
||||
let quantasearch = Math.round(Number(document.getElementById("quantasearch").value));
|
||||
SaveDefaults();
|
||||
system_rate = xtal *1000000;
|
||||
|
||||
let n = lastGn;
|
||||
let freq = ( xtal / n );
|
||||
let goertzelpoint = 0;
|
||||
let goertzelpointinv = 0;
|
||||
let tgoertzelp = 0;
|
||||
let tgoertzelpi = 0;
|
||||
let quantaA = 0;
|
||||
let quantaINV = 0;
|
||||
|
||||
let h = 1;
|
||||
|
||||
let tquanta = (quanta&0xffffc);
|
||||
let base = freq * h;
|
||||
let next = freq * (h+1);
|
||||
|
||||
|
||||
let tgoertzelpoint = tquanta;
|
||||
tgoertzelpoint = ( target - base ) / ( next - base );
|
||||
tgoertzelpoint = ((tgoertzelpoint%1)+1)%1;
|
||||
|
||||
quantaA = tquanta;
|
||||
tgoertzelp = h;
|
||||
Goertz( n, freq * (h+tgoertzelpoint), (tgoertzelpoint), quantaA , 1, target);
|
||||
return false;
|
||||
}
|
||||
|
||||
function computeTable()
|
||||
{
|
||||
let xtal = Number(document.getElementById("crystalmhz").value );
|
||||
let target = Number(document.getElementById("targetmhz").value );
|
||||
let quadrature = document.getElementById("QUADRATURE").checked;
|
||||
let goertzels = document.getElementById("GOERTZELS").checked;
|
||||
let goertzel2 = document.getElementById("GOERTZEL2").checked;
|
||||
let quanta = Math.round(Number(document.getElementById("quanta").value));
|
||||
let quantasearch = Math.round(Number(document.getElementById("quantasearch").value));
|
||||
SaveDefaults();
|
||||
|
||||
const max_harmonics = 28|0;
|
||||
const min_harmonics = (quadrature?1:0)|0;
|
||||
|
||||
let contents = "";
|
||||
|
||||
if( quadrature )
|
||||
{
|
||||
contents += "<TABLE>" +
|
||||
"<TR><TD>Quadrature:</TD></TR>" +
|
||||
"<TR><TD>I = + + - -</TD></TR>" +
|
||||
"<TR><TD>Q = + - - +</TD></TR>" +
|
||||
"<TR><TD>Differntial:</TD></TR>" +
|
||||
"<TR><TD>V = + - + -</TD></TR>" +
|
||||
"<TR><TD>You choose the mode you operate in, either Quadrature or differential</TD></TR>" +
|
||||
"</TABLE>" +
|
||||
"<p> Table shows: </P>" +
|
||||
"<TABLE BORDER=1>" +
|
||||
"<TR><TD>Sample Frequency Harmonic</TD></TR>" +
|
||||
"<TR><TD>Lower Quadrature Frequency</TD></TR>" +
|
||||
"<TR><TD>Upper Quadrature Frequency</TD></TR>" +
|
||||
"<TR><TD>Differential Frequency</TD></TR>" +
|
||||
"</TABLE>";
|
||||
}
|
||||
else if( goertzels )
|
||||
{
|
||||
contents +=
|
||||
"<TABLE>" +
|
||||
"<TR><TD>Goertzel</TD></TR>" +
|
||||
"<TR><TD>Goertzel (Inverse)</TD></TR>" +
|
||||
"</TABLE><TEXTAREA ROWS=8 COLS=80 ID=goertzeloutput></TEXTAREA>" +
|
||||
"<P>Click on a ordinal offset to create the C code needed for that tuning parameter. Clicking will copy-to-clipboard.</P>" +
|
||||
"<P>N Divisor #30 (row 3) is usually pretty good. And, try to select things near 0.25 / 0.75, and avoid 0.0, 0.5, and 1.0.</P>" +
|
||||
"<P>Goertzel's mode is for the ch32v203</P>";
|
||||
}
|
||||
|
||||
if( goertzels || quadrature )
|
||||
{
|
||||
contents += "<BR>Scroll Wheel Control:<BR>";
|
||||
contents += "<TABLE BORDER=1>";
|
||||
contents += '<TR><TH>d\\h</div></TH>';
|
||||
for( let h = 0|min_harmonics; h <= max_harmonics; h++ )
|
||||
{
|
||||
contents += "<TH COLSPAN=2>" + h + "</TH>";
|
||||
}
|
||||
|
||||
for( let n = 0|28; n <= 66; n++ )
|
||||
{
|
||||
let freq = ( xtal / n );
|
||||
let goertzelpoint = 0;
|
||||
let goertzelpointinv = 0;
|
||||
let tgoertzelp = 0;
|
||||
let tgoertzelpi = 0;
|
||||
let quantaA = 0;
|
||||
let quantaINV = 0;
|
||||
for( let h = 0|min_harmonics; h <= max_harmonics; h++ )
|
||||
{
|
||||
let base = freq * h;
|
||||
let next = freq * (h+1);
|
||||
|
||||
// Round quanta down to next order-of-4-even
|
||||
for( let tquanta = (quanta&0xffffc) - (quantasearch&0xffffc); tquanta < (quanta&0xffffc) + (quantasearch&0xffffc); tquanta+=4 )
|
||||
{
|
||||
if( target <= next && target >= base )
|
||||
{
|
||||
var t;
|
||||
let tgoertzelpoint = ( target - base ) / ( next - base );
|
||||
tgoertzelpoint = Math.round(tquanta * tgoertzelpoint)/tquanta;
|
||||
if( Math.abs( freq*(h+tgoertzelpoint) - target ) < Math.abs( freq*(h+goertzelpoint) - target ) )
|
||||
{
|
||||
goertzelpoint = tgoertzelpoint;
|
||||
tgoertzelp = h;
|
||||
quantaA = tquanta;
|
||||
}
|
||||
|
||||
let tgoertzelpointinv = (1.0 - ( target - base ) / ( next - base ));
|
||||
tgoertzelpointinv = Math.round(tquanta * tgoertzelpointinv)/tquanta;
|
||||
|
||||
if( Math.abs( freq*(h-tgoertzelpointinv+1) - target ) < Math.abs( freq*(h-goertzelpointinv+1) - target ) )
|
||||
{
|
||||
goertzelpointinv = tgoertzelpointinv;
|
||||
tgoertzelpi = h;
|
||||
quantaINV = tquanta;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
contents += "</TR>";
|
||||
|
||||
for( let mode = 0; mode < 4; mode++ )
|
||||
{
|
||||
contents += "<TR>";
|
||||
if( mode == 0 )
|
||||
contents += "<TD ROWSPAN=" + 4 + ">" + n + "</TD>";
|
||||
for( let h = 0|min_harmonics; h <= max_harmonics; h++ )
|
||||
{
|
||||
if( quadrature )
|
||||
{
|
||||
if( mode == 0 )
|
||||
contents += DrawSpan( 1, 2, freq * h, target, false );
|
||||
else if( mode == 1 )
|
||||
contents += DrawSpan( 1, 2, freq * (h-.25), target, true );
|
||||
else if( mode == 2 )
|
||||
contents += DrawSpan( 1, 2, freq * (h+.25), target, true );
|
||||
else if( mode == 3 )
|
||||
contents += DrawSpan( 1, 2, freq * (h+0.5), target, true );
|
||||
}
|
||||
else
|
||||
{
|
||||
if( mode == 0 )
|
||||
{
|
||||
contents += "<TD COLSPAN=2>"
|
||||
if( tgoertzelp == h ) contents += "<INPUT TYPE=SUBMIT ONCLICK='Goertz(" + n + ", " + freq * (h+goertzelpoint) + ", " + (goertzelpoint) + ", " + quantaA + ", 0, " + freq + ")' VALUE='↑" + (goertzelpoint).toFixed(6) + "'/>";
|
||||
contents += "</TD>";
|
||||
}
|
||||
else if( mode == 1 )
|
||||
{
|
||||
contents += DrawSpan( 1, 2, freq * (h+goertzelpoint), target, true );
|
||||
}
|
||||
else if( mode == 2 )
|
||||
{
|
||||
contents += "<TD COLSPAN=2>"
|
||||
if( tgoertzelpi == h-1 ) contents += "<INPUT TYPE=SUBMIT ONCLICK='Goertz(" + n + ", " + freq * (h-goertzelpointinv) + ", " + goertzelpointinv + ", " + quantaINV + ", 0, " + freq + ")' VALUE='↓" + goertzelpointinv.toFixed(6) + "'/>";
|
||||
contents += "</TD>";
|
||||
}
|
||||
else if( mode == 3 )
|
||||
{
|
||||
contents += DrawSpan( 1, 2, freq * (h-goertzelpointinv), target, true );
|
||||
}
|
||||
}
|
||||
}
|
||||
contents += "</TD>";
|
||||
}
|
||||
}
|
||||
contents += "</TABLE>";
|
||||
}
|
||||
else if( goertzel2 )
|
||||
{
|
||||
contents += "</TABLE>";
|
||||
contents += "<TABLE><TR><TD><TEXTAREA ROWS=6 COLS=100 ID=goertzeloutput></TEXTAREA></TD><TD><DIV>";
|
||||
|
||||
// Add widget to control various things, realtime.
|
||||
contents += "<BR>Scroll Wheel Control:<BR>";
|
||||
contents += "<input id=mhzm0 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "<input id=mhzm1 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "<input id=mhzm2 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>.";
|
||||
contents += "<input id=mhzm3 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "<input id=mhzm4 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "<input id=mhzm5 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>,";
|
||||
contents += "<input id=mhzm6 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "<input id=mhzm7 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "<input id=mhzm8 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>,";
|
||||
contents += "<input id=mhzm9 onwheel='mhzm(event, this)' size=1 type=number min=0 max=9 class='scrollwheel_tune'>";
|
||||
contents += "</DIV></TD></TR></TABLE><BR>";
|
||||
contents += "v Click in this row; <TABLE BORDER=1>";
|
||||
contents += '<TR><TH>d\\h</div></TH>';
|
||||
for( let h = 0|min_harmonics; h <= max_harmonics+1; h++ )
|
||||
{
|
||||
contents += "<TH COLSPAN=1>" + h + "</TH>";
|
||||
}
|
||||
|
||||
for( let n = 0|42; n <= 96; n+=2 )
|
||||
{
|
||||
let freq = ( xtal / n );
|
||||
let goertzelpoint = 0;
|
||||
let goertzelpointinv = 0;
|
||||
let tgoertzelp = 0;
|
||||
let tgoertzelpi = 0;
|
||||
let quantaA = 0;
|
||||
let quantaINV = 0;
|
||||
|
||||
for( let rid = 0|0; rid < 2|0; rid++ )
|
||||
{
|
||||
contents += "<TR>";
|
||||
for( let h = -2|min_harmonics; h <= max_harmonics; h++ )
|
||||
{
|
||||
let tquanta = (quanta&0xffffc);
|
||||
let base = freq * h;
|
||||
let next = freq * (h+1);
|
||||
|
||||
let tgoertzelpoint = tquanta;
|
||||
tgoertzelpoint = ( target - base ) / ( next - base );
|
||||
tgoertzelpoint = ((tgoertzelpoint%1)+1)%1;
|
||||
|
||||
quantaA = tquanta;
|
||||
tgoertzelp = h;
|
||||
if( h == -2 )
|
||||
{
|
||||
if( rid == 0 )
|
||||
{
|
||||
contents += "<TD COLSPAN=1 ROWSPAN=2>"
|
||||
contents += "<INPUT TYPE=SUBMIT ONCLICK='Goertz(" + n + ", " + freq * (h+tgoertzelpoint) + ", " + (tgoertzelpoint) + ", " + quantaA + ", 1, " + target + " )' VALUE='↑" + n + "'/>";
|
||||
contents += "</TD>"
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( rid == 0 )
|
||||
{
|
||||
contents += DrawSpan( 1, 1, freq * (h+tgoertzelpoint), target, true );
|
||||
}
|
||||
else
|
||||
{
|
||||
contents += DrawSpan( 1, 1, freq * (h-tgoertzelpoint), target, true );
|
||||
}
|
||||
}
|
||||
}
|
||||
contents += "</TR>";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
contents += "</TABLE>";
|
||||
}
|
||||
|
||||
document.getElementById( "TABLE" ).innerHTML = contents;
|
||||
}
|
||||
|
||||
const savedFields = ["crystalmhz", "targetmhz", "quanta", "quantasearch", "toggle_adc_buffer", "g_attenuation_pow2"];
|
||||
|
||||
function SaveDefaults()
|
||||
{
|
||||
for( i in savedFields )
|
||||
{
|
||||
let f = savedFields[i];
|
||||
let e = document.getElementById(f);
|
||||
if( e )
|
||||
{
|
||||
localStorage.setItem( f, e.value );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function LoadDefaults()
|
||||
{
|
||||
for( i in savedFields )
|
||||
{
|
||||
let f = savedFields[i];
|
||||
let e = document.getElementById(f);
|
||||
let v = localStorage.getItem( f );
|
||||
console.log( `Loading: ${e} ${f} ${v}`);
|
||||
if( e && v )
|
||||
{
|
||||
if( v == 'on' )
|
||||
e.checked = true;
|
||||
else if( v == 'off' )
|
||||
e.checked = false;
|
||||
else
|
||||
e.value = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onLoad()
|
||||
{
|
||||
LoadDefaults();
|
||||
onLoadWebHidControl();
|
||||
}
|
||||
</SCRIPT>
|
||||
</HEAD>
|
||||
<BODY onLoad="onLoad()">
|
||||
<TABLE WIDTH=100%>
|
||||
<TR>
|
||||
<TD COLSPAN=2>
|
||||
<p>Tool for computing tuning to specific frequencies by use of direct ADC reading at specific timer-controlled rate to "tune" to specific frequencies either by quadrature or differential.</p>
|
||||
</TD>
|
||||
<TD ROWSPAN=2 VALIGN=TOP HEIGHT=200 WIDTH=100% ID=LiveGraphContainer>
|
||||
|
||||
<CANVAS WIDTH=100% HEIGHT=200 ID=LiveGraph> </CANVAS>
|
||||
</TD>
|
||||
</TR>
|
||||
<TR>
|
||||
<TD VALIGN=TOP ROWSPAN=2>
|
||||
<TABLE WIDTH=380>
|
||||
<TR><TD>System Rate MHz</TD><TD><INPUT ID=crystalmhz VALUE=288></TD></TR>
|
||||
<TR><TD>Target MHz</TD><TD><INPUT ID=targetmhz VALUE=27.019360></TD></TR>
|
||||
<TR><TD>Quanta</TD><TD><INPUT ID=quanta VALUE=1024></TD></TR>
|
||||
<TR><TD>Quanta Search Range</TD><TD><INPUT ID=quantasearch VALUE=64></TD></TR>
|
||||
<TR><TD>Table Type</TD><TD>
|
||||
<INPUT TYPE=RADIO ID=QUADRATURE NAME=computetype>Quadrature</INPUT><br>
|
||||
<INPUT TYPE=RADIO ID=GOERTZELS NAME=computetype>Goertzels</INPUT><br>
|
||||
<INPUT TYPE=RADIO ID=GOERTZEL2 NAME=computetype checked>Goertzel (unalign)</INPUT>
|
||||
</TD></TR>
|
||||
<TR><TD COLSPAN=2><INPUT TYPE=SUBMIT VALUE="Compute" ONCLICK="computeTable()"></TD></TR>
|
||||
</TABLE>
|
||||
</TD>
|
||||
<TD VALIGN=TOP ROWSPAN=2>
|
||||
Live Control:<br>
|
||||
<TABLE><TR>
|
||||
<TD><INPUT TYPE=SUBMIT onClick="reqConnect()" VALUE="Open Device" ID=connectButton>
|
||||
<INPUT TYPE=SUBMIT onClick="toggleAudio()" VALUE="Play Audio" ID="ToggleAudioButton">
|
||||
<INPUT TYPE=SUBMIT onClick="toggleAudioModulation()" VALUE="modulation" ID="ToggleAudioModulationButton">
|
||||
<DIV ID=STATUS></DIV></TD>
|
||||
</TR></TABLE>
|
||||
<DIV ID="StatusPerf"></DIV>
|
||||
</TD>
|
||||
<TD>
|
||||
</TD>
|
||||
</TR>
|
||||
<tr>
|
||||
<td>
|
||||
<div id=GeneralData></DIV>
|
||||
<input type=checkbox ID=toggle_adc_buffer onchange='toggleBuffer(this)'>ADC Buffer Enable
|
||||
<BR>Pow2 Attenuation:
|
||||
<input id=g_attenuation_pow2 onwheel='attenuationpow2wheel(event, this)' size=3 type=number style="width:3em" value=3><br>
|
||||
</td>
|
||||
</tr>
|
||||
<tr><td>
|
||||
<DIV STYLE="position:relative">
|
||||
<DIV style="margin:0px;top:0px;position:absolute" ID=TABLE></DIV>
|
||||
</DIV>
|
||||
</td></tr>
|
||||
</TABLE>
|
||||
</BODY>
|
||||
</HTML>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,583 @@
|
||||
/* This file is under the regular MIT license.
|
||||
|
||||
Copyright 2024 Charles Lohr (cnlohr)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
const expectedProductName = "CNLohr lolra ch32v203 goertzel test";
|
||||
const filter = { vendorId : 0x1209, productId : 0xd035 };
|
||||
let dev = null;
|
||||
let loopAbort = false;
|
||||
|
||||
const IQHistoryLen = 4096;
|
||||
var IQHistoryArray = new Uint32Array(IQHistoryLen);
|
||||
var MPHistoryArray = new Float32Array(IQHistoryLen*2);
|
||||
var IQHistoryHead = 0|0;
|
||||
var lastIntensity = 1.0;
|
||||
var lastNumQ = 0;
|
||||
var lastTotalTime = 1;
|
||||
var lastTimeUsed = 1;
|
||||
var didSetupGeneralData = false;
|
||||
var graphIsClicked = false;
|
||||
|
||||
function graphClick( e )
|
||||
{
|
||||
if( e.type == "mousedown" ) graphIsClicked = true;
|
||||
if( e.type == "mouseup" ) graphIsClicked = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function setStatus( msg )
|
||||
{
|
||||
document.getElementById( "STATUS" ).innerHTML = msg;
|
||||
console.log( msg );
|
||||
}
|
||||
|
||||
function setStatusError( msg )
|
||||
{
|
||||
setStatus( "<FONT COLOR=RED>" + msg + "</FONT>" );
|
||||
console.log( msg );
|
||||
console.trace();
|
||||
}
|
||||
|
||||
function tryConnect()
|
||||
{
|
||||
if( !navigator.hid )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if( !dev )
|
||||
{
|
||||
navigator.hid.getDevices().then( (devices) =>
|
||||
{
|
||||
if( devices.length == 0 )
|
||||
setStatusError( "No devices found. Open a device." );
|
||||
else
|
||||
devices.forEach( tryOpen );
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function closeDeviceTool()
|
||||
{
|
||||
loopAbort = false;
|
||||
setStatusError( "Disconnected" );
|
||||
dev = null;
|
||||
}
|
||||
|
||||
var playingAudioProcessor = null;
|
||||
var audioContext = null;
|
||||
|
||||
var targetModulation = 0;
|
||||
var targetGain = 0.0;
|
||||
|
||||
function UpdateButtonNames()
|
||||
{
|
||||
document.getElementById( "ToggleAudioButton" ).value = ( targetGain > 0.0 ) ? "Stop Audio" : "Start Audio";
|
||||
document.getElementById( "ToggleAudioModulationButton" ).value = ( targetModulation > 0.5 ) ? "FM" : "AM";
|
||||
}
|
||||
|
||||
async function toggleAudioModulation()
|
||||
{
|
||||
if( playingAudioProcessor != null )
|
||||
{
|
||||
var newVal = 1 - targetModulation;
|
||||
targetModulation = newVal;
|
||||
}
|
||||
UpdateButtonNames();
|
||||
}
|
||||
|
||||
async function toggleAudio()
|
||||
{
|
||||
if( playingAudioProcessor == null )
|
||||
{
|
||||
var bypass = '\
|
||||
class PlayingAudioProcessor extends AudioWorkletProcessor {\
|
||||
static get parameterDescriptors() {\
|
||||
return [\
|
||||
{ name: "gain", defaultValue: 0, },\
|
||||
{ name: "sampleAdvance", defaultValue: 0.5, },\
|
||||
]\
|
||||
};\
|
||||
constructor() {\
|
||||
super();\
|
||||
this.rbuffer = new Float32Array(8192); \
|
||||
this.rbufferhead = 0|0; \
|
||||
this.rbuffertail = 0|0; \
|
||||
this.sampleplace = 0.0; \
|
||||
this.dcoffset = 0.0; \
|
||||
this.totalsampcount = 0|0; \
|
||||
\
|
||||
this.port.onmessage = (e) => { \
|
||||
for( var i = 0|0; i < e.data.length|0; i++ ) \
|
||||
{ \
|
||||
let n = (this.rbufferhead + (1|0))%(8192|0); \
|
||||
if( n == this.rbuffertail ) \
|
||||
{ \
|
||||
this.rbuffertail = (this.rbuffertail + (1|0))%(8192|0); \
|
||||
/*console.log( `Overflow` ); */ \
|
||||
} \
|
||||
var vv = e.data[i]; \
|
||||
this.dcoffset = this.dcoffset * 0.995 + vv * 0.005; \
|
||||
this.rbuffer[this.rbufferhead] = vv - this.dcoffset; \
|
||||
this.rbufferhead = n; \
|
||||
} \
|
||||
}; \
|
||||
}\
|
||||
\
|
||||
process(inputs, outputs, parameters) {\
|
||||
/*console.log( parameters.gain[0] );*/ \
|
||||
/*console.log( this.ingestData );*/ \
|
||||
let len = outputs[0][0].length; \
|
||||
const sa = Math.fround( parameters.sampleAdvance[0] ); /*float*/ \
|
||||
var s = Math.fround( this.sampleplace ); /*float*/ \
|
||||
var tail = this.rbuffertail | 0; /* int*/ \
|
||||
var tailnext = this.rbuffertail | 0; /* int*/ \
|
||||
if( tail == this.rbufferhead ) { /*console.log( "Underflow " );*/ return true; }\
|
||||
var tsamp = Math.fround( this.rbuffer[tail] ); \
|
||||
var nsamp = Math.fround( this.rbuffer[tailnext] ); \
|
||||
this.totalsampcount += len|0; \
|
||||
for (let b = 0|0; b < len|0; b++) { \
|
||||
s += sa; \
|
||||
var excess = Math.floor( s ) | 0; \
|
||||
if( excess > 0 ) \
|
||||
{ \
|
||||
s -= excess; \
|
||||
tail = ( tail + (excess|0) ) % (8192|0); \
|
||||
tailnext = ( tail + (1|0) ) % (8192|0); \
|
||||
if( tail == this.rbufferhead ) { /* console.log( "Underflow" ); */ break; } \
|
||||
tsamp = Math.fround( this.rbuffer[tail] ); \
|
||||
nsamp = Math.fround( this.rbuffer[tailnext] ); \
|
||||
} \
|
||||
var valv = tsamp * (1.0-s) + nsamp * s; \
|
||||
outputs[0][0][b] = valv*parameters.gain[0]; \
|
||||
} \
|
||||
/*console.log( tail + " " + this.rbuffertail + " " + tsamp + " " + nsamp );*/ \
|
||||
this.rbuffertail = tail; \
|
||||
this.sampleplace = s; \
|
||||
return true; \
|
||||
} \
|
||||
} \
|
||||
\
|
||||
registerProcessor("playing-audio-processor", PlayingAudioProcessor);';
|
||||
|
||||
// The following mechanism does not work on Chrome.
|
||||
// const dataURI = URL.createObjectURL( new Blob([bypass], { type: 'text/javascript', } ) );
|
||||
|
||||
|
||||
// Extremely tricky trick to side-step local file:// CORS issues.
|
||||
// https://stackoverflow.com/a/67125196/2926815
|
||||
// https://stackoverflow.com/a/72180421/2926815
|
||||
let blob = new Blob([bypass], {type: 'application/javascript'});
|
||||
let reader = new FileReader();
|
||||
await reader.readAsDataURL(blob);
|
||||
let dataURI = await new Promise((res) => {
|
||||
reader.onloadend = function () {
|
||||
res(reader.result);
|
||||
}
|
||||
});
|
||||
|
||||
audioContext = new AudioContext();
|
||||
|
||||
await audioContext.audioWorklet.addModule(dataURI);
|
||||
|
||||
playingAudioProcessor = new AudioWorkletNode(
|
||||
audioContext,
|
||||
"playing-audio-processor"
|
||||
);
|
||||
playingAudioProcessor.connect(audioContext.destination);
|
||||
audioContext.resume();
|
||||
|
||||
let gainParam = playingAudioProcessor.parameters.get( "gain" );
|
||||
gainParam.setValueAtTime( 0, audioContext.currentTime );
|
||||
}
|
||||
|
||||
var newVal = 1.0 - targetGain;
|
||||
console.log( "Setting gain to: " + newVal );
|
||||
let gainParam = playingAudioProcessor.parameters.get("gain");
|
||||
gainParam.setValueAtTime( newVal, audioContext.currentTime);
|
||||
targetGain = newVal;
|
||||
document.getElementById( "ToggleAudioButton" ).value = ( newVal > 0.5 ) ? "Stop Audio" : "Start Audio";
|
||||
UpdateButtonNames();
|
||||
}
|
||||
|
||||
function onLoadWebHidControl()
|
||||
{
|
||||
liveGraph = document.getElementById( "LiveGraph" );
|
||||
liveGraph.addEventListener( "mousedown", graphClick );
|
||||
liveGraph.addEventListener( "mouseup", graphClick );
|
||||
|
||||
UpdateButtonNames();
|
||||
setTimeout( sendLoop, 1 );
|
||||
|
||||
if( !navigator.hid )
|
||||
{
|
||||
setStatusError( "Browser does not support HID." );
|
||||
document.getElementById( "connectButton" ).hidden = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
navigator.hid.addEventListener("disconnect", (event) => { if( event.device.productName == expectedProductName ) closeDeviceTool(); } );
|
||||
}
|
||||
|
||||
setTimeout( () => { elapsedOK = true; }, 3000 );
|
||||
|
||||
}
|
||||
|
||||
function reqConnect()
|
||||
{
|
||||
loopAbort = true;
|
||||
const initialization = navigator.hid.requestDevice( { filters: [ filter ] } );
|
||||
initialization.then( gotUSBDevice );
|
||||
initialization.catch( setStatusError );
|
||||
}
|
||||
|
||||
function gotUSBDevice(result)
|
||||
{
|
||||
if( result.length < 1 )
|
||||
{
|
||||
setStatusError( "Error: No devices found" );
|
||||
return;
|
||||
}
|
||||
|
||||
if( result[0].productName != expectedProductName )
|
||||
{
|
||||
setStatusError( "Error: Wrong device name. Got " + result[0].productName + " Expected " + expectedProductName );
|
||||
return;
|
||||
}
|
||||
|
||||
const thisDev = result[0];
|
||||
|
||||
tryOpen( thisDev );
|
||||
}
|
||||
|
||||
function tryOpen( thisDev )
|
||||
{
|
||||
thisDev.open().then( ( result ) => {
|
||||
if( result === undefined )
|
||||
{
|
||||
if( dev ) dev.close();
|
||||
loopAbort = false;
|
||||
dev = thisDev;
|
||||
setStatus( "Connected." );
|
||||
}
|
||||
else
|
||||
{
|
||||
setStatusError( "Error: Could not open; " + result );
|
||||
}
|
||||
} ).catch( (e) => setStatusError( "Error: Could not open; " + e ) );
|
||||
}
|
||||
|
||||
let sendReport = null;
|
||||
let receiveReport = null;
|
||||
|
||||
async function sendLoopError( e )
|
||||
{
|
||||
console.log( "SEND LOOP ERROR" );
|
||||
sendReport = null;
|
||||
receiveReport = null;
|
||||
if( dev ) await dev.close();
|
||||
dev = null;
|
||||
setStatusError( e );
|
||||
}
|
||||
|
||||
function updateWebHidDeviceWithParameters( paramlist )
|
||||
{
|
||||
var i = 0|0;
|
||||
var arraySend = new Uint8Array(63);
|
||||
for( var i = 0|0; i < paramlist.length|0; i++ )
|
||||
{
|
||||
var vv = paramlist[i] | 0;
|
||||
arraySend[i*4+7] = (vv>>0)&0xff;
|
||||
arraySend[i*4+8] = (vv>>8)&0xff;
|
||||
arraySend[i*4+9] = (vv>>16)&0xff;
|
||||
arraySend[i*4+10] = (vv>>24)&0xff;
|
||||
}
|
||||
arraySend[3] = paramlist.length | 0;
|
||||
sendReport = dev.sendFeatureReport( 0xAC, arraySend ).catch( sendLoopError );
|
||||
if( !sendReport ) sendLoopError( "error creating sendFeatureReport" );
|
||||
}
|
||||
|
||||
FMiirphase = 0.0; /* for FM */
|
||||
FMlastphase = 0.0; /* for FM */
|
||||
FMphaseout = 0.0; /* for FM */
|
||||
|
||||
lastadc = 0|0;
|
||||
|
||||
|
||||
remote_clock_mhz = 0;
|
||||
remote_clock_last_timestamp = 0|0;
|
||||
remote_clock_last_timems = 0.0;
|
||||
remote_clock_initted = false;
|
||||
remote_clock_refinement = 1.0;
|
||||
remote_clock_total_s = 0;
|
||||
remote_clock_total_ticks = 0.0;
|
||||
|
||||
function ComputeRemoteClock( remote_time_ticks, now_ms )
|
||||
{
|
||||
if( !remote_clock_initted )
|
||||
{
|
||||
remote_clock_last_timestamp = remote_time_ticks;
|
||||
remote_clock_last_timems = now_ms;
|
||||
remote_clock_refinement = 1.0;
|
||||
remote_clock_initted = true;
|
||||
remote_clock_total_ms = 0;
|
||||
remote_clock_total_ticks = 0|0;
|
||||
return;
|
||||
}
|
||||
|
||||
var delta_s = (now_ms - remote_clock_last_timems)/1000.0;
|
||||
var delta_clock = ((remote_time_ticks - remote_clock_last_timestamp)|0)*2; // convert 144MHz to 288MHz
|
||||
var this_mhz = delta_clock / delta_s;
|
||||
|
||||
remote_clock_total_s += delta_s;
|
||||
remote_clock_total_ticks += delta_clock * 1.0;
|
||||
|
||||
remote_clock_mhz = remote_clock_total_ticks / remote_clock_total_s;
|
||||
|
||||
remote_clock_total_s *= 0.99999;
|
||||
remote_clock_total_ticks *= 0.99999;
|
||||
|
||||
remote_clock_last_timestamp = remote_time_ticks;
|
||||
remote_clock_last_timems = now_ms;
|
||||
}
|
||||
|
||||
function updateCrystalWithMHz()
|
||||
{
|
||||
document.getElementById('crystalmhz').value = remote_clock_mhz/1000000.0;
|
||||
}
|
||||
|
||||
async function sendLoop()
|
||||
{
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
var frameNo = 0|0;
|
||||
var lastTime = performance.now();
|
||||
let goodCount = 0;
|
||||
let badCount = 0;
|
||||
let kBsecAvg = 0;
|
||||
let xActionSecAvg = 0;
|
||||
|
||||
while( true )
|
||||
{
|
||||
if( dev && dev !== null && !loopAbort )
|
||||
{
|
||||
receiveReport = dev.receiveFeatureReport( 0xAD ).catch( sendLoopError );
|
||||
if( !receiveReport ) sendLoopError( "error creating receiveReport" );
|
||||
|
||||
frameNo++
|
||||
|
||||
const updateStatsPerfPer = 4;
|
||||
if( frameNo % updateStatsPerfPer == 0 )
|
||||
{
|
||||
let thisTime = performance.now();
|
||||
let deltaTime = thisTime - lastTime;
|
||||
let kBsec = (255*1000/1024*updateStatsPerfPer)/(deltaTime);
|
||||
let xActionSec = (2*updateStatsPerfPer*1000)/(deltaTime);
|
||||
kBsecAvg = kBsecAvg * 0.9 + kBsec * 0.1;
|
||||
xActionSecAvg = xActionSecAvg * 0.9 + xActionSec * 0.1;
|
||||
|
||||
document.getElementById( "StatusPerf" ).innerHTML =
|
||||
(kBsecAvg).toFixed(2) + " kB/s<br>" +
|
||||
(xActionSecAvg).toFixed(2) + "x/s<br>";
|
||||
|
||||
if( !didSetupGeneralData )
|
||||
{
|
||||
document.getElementById( "GeneralData" ).innerHTML =
|
||||
"<TABLE WIDTH=100% border=1><TR><TD width=25% ID=gdCount>Count: " + goodCount + " / " + badCount + "</td>" +
|
||||
"<td width=20% ID=gdInten>Inten: " + ((Math.log( lastIntensity * lastIntensity )/Math.log(10)) * 10-120).toFixed(2) + "db (" + lastIntensity + ")</td>" +
|
||||
"<td width=20% ID=gdADCs>ADCs: " + (lastadc>>16).toFixed(0) + " / " + (lastadc&0xffff).toFixed(0) + "</td>" +
|
||||
"<td width=20%><INPUT TYPE=submit ID=gdButton style='padding:.1em' VALUE=" + (remote_clock_mhz/1000000.0).toFixed(6) + ` ONMOUSEDOWN="updateCrystalWithMHz()"> MHz ` + "</TD>" +
|
||||
"<td width=20% ID=gdPPM>" + ((remote_clock_mhz-288000000)/288).toFixed(3) + " PPM</td>" +
|
||||
"</tr></table>";
|
||||
didSetupGeneralData = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
document.getElementById( "gdCount" ).innerHTML = "Count: " + goodCount + " / " + badCount;
|
||||
document.getElementById( "gdInten" ).innerHTML = "Inten: " + ((Math.log( lastIntensity * lastIntensity )/Math.log(10)) * 10-120).toFixed(2) + "db (" + lastIntensity + ")";
|
||||
document.getElementById( "gdADCs" ).innerHTML = "ADC:" + (lastadc>>16).toFixed(0) + " / " + (lastadc&0xffff).toFixed(0);
|
||||
document.getElementById( "gdButton" ).value = "" + (remote_clock_mhz/1000000.0).toFixed(6);
|
||||
document.getElementById( "gdPPM" ).innerHTML = "" + ((remote_clock_mhz-288000000)/288).toFixed(3) + " PPM";
|
||||
didSetupGeneralData = true;
|
||||
}
|
||||
|
||||
lastTime = thisTime;
|
||||
}
|
||||
else if( frameNo % updateStatsPerfPer == 2 )
|
||||
{
|
||||
const ctx = liveGraph.getContext("2d");
|
||||
|
||||
if( !graphIsClicked )
|
||||
{
|
||||
let liveGraphContainer = document.getElementById( "LiveGraphContainer" );
|
||||
liveGraph.width = liveGraphContainer.clientWidth;
|
||||
liveGraph.style.position = 'absolute';
|
||||
|
||||
ctx.clearRect(0, 0, liveGraph.width, liveGraph.height);
|
||||
|
||||
let grey = darkmode?"rgb( 240 240 240 )":"rgb(16 16 16)";
|
||||
let mark = darkmode?"rgb( 255 255 255 )":"rgb(0 0 0)";
|
||||
|
||||
var filledness = lastNumQ * 198 / 120;
|
||||
ctx.fillStyle = grey;
|
||||
ctx.fillRect( 2, 2 + 198 - filledness, 18, filledness - 2);
|
||||
|
||||
filledness = ( lastTimeUsed * 1.0 / lastTotalTime ) * 198;
|
||||
ctx.fillStyle = grey;
|
||||
ctx.fillRect( 26, 2 + 198 - filledness, 18, filledness - 2 );
|
||||
|
||||
ctx.fillStyle = mark;
|
||||
|
||||
let mulcoeff = 2500.0 / lastIntensity;
|
||||
var lot = 1.2;
|
||||
var x = 253;
|
||||
for( var i = (IQHistoryHead-1) & (IQHistoryLen-1); i != IQHistoryHead|0; i = (i - 1 + IQHistoryLen) & (IQHistoryLen-1) )
|
||||
{
|
||||
let power = MPHistoryArray[i*2+0]; //Math.sqrt( real * real + imag * imag ) * mulcoeff;
|
||||
let phase = MPHistoryArray[i*2+1]; //Math.atan2( real, imag ) * 0.159155078*0.5;
|
||||
ctx.fillRect(x,power*120+10,2,2);
|
||||
ctx.fillRect(x,phase*80+110,2,2);
|
||||
|
||||
let v = IQHistoryArray[i];
|
||||
let real = (v >> 16);
|
||||
let imag = (v & 0xffff);
|
||||
if( real > 32767 ) real -= 65536;
|
||||
if( imag > 32767 ) imag -= 65536;
|
||||
real = real * mulcoeff + 100;
|
||||
imag = imag * mulcoeff + 100;
|
||||
if( real < 0 ) real = 0; if( real > 255 ) real = 255;
|
||||
if( imag < 0 ) imag = 0; if( imag > 255 ) imag = 255;
|
||||
x++;
|
||||
if( lot > 0 )
|
||||
{
|
||||
ctx.globalAlpha = lot;
|
||||
ctx.fillRect(real+50,imag,2,2);
|
||||
}
|
||||
ctx.globalAlpha = 1.0;
|
||||
lot -= 0.0015;
|
||||
}
|
||||
|
||||
ctx.strokeStyle = "rgb( 128 128 128 )";
|
||||
ctx.fillStyle = "rgb( 128 0 0 )";
|
||||
ctx.strokeRect( 1, 1, 20, 198 );
|
||||
ctx.strokeRect( 25, 1, 20, 198 );
|
||||
ctx.strokeRect( 49, 1, 200, 198 );
|
||||
ctx.strokeRect( 253, 1, liveGraph.width, 198 );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if( sendReport )
|
||||
{
|
||||
await sendReport;
|
||||
}
|
||||
if( receiveReport )
|
||||
{
|
||||
let receiveData = await receiveReport;
|
||||
if( receiveData && receiveData.buffer )
|
||||
{
|
||||
// Receive data from USB (from HandleHidUserGetReportSetup)
|
||||
let data = new Uint32Array( receiveData.buffer.slice( 0, 508 ) );
|
||||
let intensity = data[0]>>8;
|
||||
let numq = data[0] & 0xff;
|
||||
let time_total = data[1]>>16;
|
||||
let time_used = data[1]&0xffff;
|
||||
let sample_divisor = data[2]&0xffff;
|
||||
let remote_time = data[3];
|
||||
ComputeRemoteClock( remote_time, performance.now() );
|
||||
lastadc = data[4];
|
||||
let demodbuffer = new Float32Array(numq);
|
||||
let mulcoeff = 16.0 / lastIntensity;
|
||||
for( var i = 0|0; i < numq; i++ )
|
||||
{
|
||||
let vv = IQHistoryArray[IQHistoryHead] = data[i+5];
|
||||
let vi = vv >> 16;
|
||||
let vq = vv & 0xffff;
|
||||
if( vi >= 32768 ) vi = vi-65535;
|
||||
if( vq >= 32768 ) vq = vq-65535;
|
||||
let power = Math.sqrt( vi * vi + vq * vq ) * mulcoeff;
|
||||
let phase = Math.atan2( vi, vq ) * 0.159155078 + 0.5;
|
||||
MPHistoryArray[IQHistoryHead*2+0] = power; //Math.sqrt( real * real + imag * imag ) * mulcoeff;
|
||||
MPHistoryArray[IQHistoryHead*2+1] = phase; //Math.atan2( real, imag ) * 0.159155078*0.5;
|
||||
if( targetModulation == 0 )
|
||||
{ /* AM */
|
||||
demodbuffer[i] = power;
|
||||
}
|
||||
else if( targetModulation == 1 )
|
||||
{ /* FM */
|
||||
var diffphase = phase - FMlastphase;
|
||||
FMlastphase = phase;
|
||||
if( diffphase - FMiirphase < 0.0 ) diffphase += 1.0;
|
||||
if( diffphase - FMiirphase > 1.0 ) diffphase -= 1.0;
|
||||
FMiirphase = FMiirphase * 0.999 + diffphase * 0.001;
|
||||
diffphase -= FMiirphase;
|
||||
if( diffphase > 0.5 ) diffphase -= 1;
|
||||
if( diffphase <-0.5 ) diffphase += 1;
|
||||
var po = FMphaseout = FMphaseout * 0.993 + diffphase;
|
||||
if( po < 0.0 ) po += 1.0;
|
||||
if( po > 1.0 ) po -= 1.0;
|
||||
demodbuffer[i] = po * .3; // Turn down FM it's really loud.
|
||||
}
|
||||
|
||||
IQHistoryHead = (IQHistoryHead+1)%IQHistoryLen;
|
||||
}
|
||||
lastIntensity = intensity;
|
||||
lastNumQ = numq;
|
||||
lastTotalTime = time_total;
|
||||
lastTimeUsed = time_used;
|
||||
|
||||
if( audioContext != null && playingAudioProcessor != null )
|
||||
{
|
||||
let sampleAdvance = (system_rate/sample_divisor) / audioContext.sampleRate;
|
||||
let sampleAdvanceParam = playingAudioProcessor.parameters.get("sampleAdvance");
|
||||
sampleAdvanceParam.setValueAtTime( sampleAdvance, audioContext.currentTime);
|
||||
playingAudioProcessor.port.postMessage( demodbuffer );
|
||||
}
|
||||
goodCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
badCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if( loopAbort )
|
||||
{
|
||||
if( dev )
|
||||
{
|
||||
console.log( "Loop Aborting, Dev Closing" );
|
||||
await dev.close();
|
||||
console.log( "Loop Aborting, Dev Closed." );
|
||||
dev = null;
|
||||
}
|
||||
await sleep(100);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Try opening dev.
|
||||
console.log( "Attempting reconnect." );
|
||||
tryConnect();
|
||||
goodCount = 0;
|
||||
badCount = 0;
|
||||
let i = 0|0;
|
||||
for( i = 0; i < 10; i++ )
|
||||
{
|
||||
await sleep(100);
|
||||
if( dev )
|
||||
{
|
||||
//break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log( "ABORT\n" );
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
.vscode
|
||||
build
|
||||
@@ -0,0 +1,23 @@
|
||||
# The following lines of boilerplate have to be in your project's
|
||||
# CMakeLists in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
|
||||
add_custom_target(stub_bootload
|
||||
# If the swadge is running reboot it into the bootloader.
|
||||
COMMAND make -C ../tools/reboot_into_bootloader reboot
|
||||
COMMAND sleep 0.5
|
||||
)
|
||||
#add_dependencies(flash before_flash)
|
||||
add_custom_target(stub_run
|
||||
#Sometimes the swadge needs a kick to get rebooted
|
||||
COMMAND sleep 0.5
|
||||
COMMAND esptool.py --before no_reset --after no_reset load_ram ../tools/bootload_reboot_stub/bootload_reboot_stub.bin
|
||||
)
|
||||
|
||||
|
||||
project(usb_sandbox)
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
idf_component_register(SRCS "main.c" "app.c"
|
||||
INCLUDE_DIRS "" )
|
||||
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
/**
|
||||
|
||||
MIT-like-non-ai-license
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the two following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
In addition the following restrictions apply:
|
||||
|
||||
1. The Software and any modifications made to it may not be used for the
|
||||
purpose of training or improving machine learning algorithms, including but not
|
||||
limited to artificial intelligence, natural language processing, or data
|
||||
mining. This condition applies to any derivatives, modifications, or updates
|
||||
based on the Software code. Any usage of the Software in an AI-training dataset
|
||||
is considered a breach of this License.
|
||||
|
||||
2. The Software may not be included in any dataset used for training or
|
||||
improving machine learning algorithms, including but not limited to artificial
|
||||
intelligence, natural language processing, or data mining.
|
||||
|
||||
3. Any person or organization found to be in violation of these restrictions
|
||||
will be subject to legal action and may be held liable for any damages
|
||||
resulting from such use.
|
||||
|
||||
If any term is unenforcable, other terms remain in-force.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "esp_system.h"
|
||||
#include "hal/gpio_types.h"
|
||||
#include "esp_log.h"
|
||||
#include "soc/efuse_reg.h"
|
||||
#include "soc/soc.h"
|
||||
#include "soc/system_reg.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "soc/gpio_sig_map.h"
|
||||
|
||||
|
||||
#include "soc/io_mux_reg.h"
|
||||
#include "soc/dedic_gpio_reg.h"
|
||||
|
||||
// Funtenna will output on GPIO1 and 14. Otherwise it will be 17 and 18
|
||||
//#define FUNTENNA
|
||||
|
||||
int global_i = 100;
|
||||
|
||||
|
||||
static inline uint32_t getCycleCount()
|
||||
{
|
||||
uint32_t ccount;
|
||||
asm volatile("rsr %0,ccount":"=a" (ccount));
|
||||
return ccount;
|
||||
}
|
||||
|
||||
|
||||
#define IO_MUX_REG(x) XIO_MUX_REG(x)
|
||||
#define XIO_MUX_REG(x) IO_MUX_GPIO##x##_REG
|
||||
|
||||
#define GPIO_NUM(x) XGPIO_NUM(x)
|
||||
#define XGPIO_NUM(x) GPIO_NUM_##x
|
||||
|
||||
|
||||
#ifdef FUNTENNA
|
||||
|
||||
#define RF1_PIN 1
|
||||
#define RF2_PIN 14
|
||||
#else
|
||||
#define RF1_PIN 17
|
||||
#define RF2_PIN 18
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#include "hal/gpio_types.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "rom/gpio.h"
|
||||
#include "soc/i2s_reg.h"
|
||||
#include "soc/periph_defs.h"
|
||||
#include "rom/lldesc.h"
|
||||
#include "soc/rtc_cntl_reg.h"
|
||||
#include "soc/rtc.h"
|
||||
#include "soc/regi2c_apll.h"
|
||||
//#include "components/hal/esp32s2/include/hal/regi2c_ctrl_ll.h
|
||||
#include "hal/regi2c_ctrl_ll.h"
|
||||
#include "esp_private/periph_ctrl.h"
|
||||
#include "esp_private/regi2c_ctrl.h"
|
||||
#include "hal/clk_tree_ll.h"
|
||||
|
||||
|
||||
|
||||
|
||||
#define I2C_RTC_WIFI_CLK_EN (SYSCON_WIFI_CLK_EN_REG)
|
||||
|
||||
#define I2C_RTC_CLK_GATE_EN (BIT(18))
|
||||
#define I2C_RTC_CLK_GATE_EN_M (BIT(18))
|
||||
#define I2C_RTC_CLK_GATE_EN_V 0x1
|
||||
#define I2C_RTC_CLK_GATE_EN_S 18
|
||||
|
||||
#define I2C_RTC_CONFIG0 0x6000e048
|
||||
|
||||
#define I2C_RTC_MAGIC_CTRL 0x00001FFF
|
||||
#define I2C_RTC_MAGIC_CTRL_M ((I2C_RTC_MAGIC_CTRL_V)<<(I2C_RTC_MAGIC_CTRL_S))
|
||||
#define I2C_RTC_MAGIC_CTRL_V 0x1FFF
|
||||
#define I2C_RTC_MAGIC_CTRL_S 4
|
||||
|
||||
#define I2C_RTC_CONFIG1 0x6000e044
|
||||
|
||||
#define I2C_RTC_BOD_MASK (BIT(22))
|
||||
#define I2C_RTC_BOD_MASK_M (BIT(22))
|
||||
#define I2C_RTC_BOD_MASK_V 0x1
|
||||
#define I2C_RTC_BOD_MASK_S 22
|
||||
|
||||
#define I2C_RTC_SAR_MASK (BIT(18))
|
||||
#define I2C_RTC_SAR_MASK_M (BIT(18))
|
||||
#define I2C_RTC_SAR_MASK_V 0x1
|
||||
#define I2C_RTC_SAR_MASK_S 18
|
||||
|
||||
#define I2C_RTC_BBPLL_MASK (BIT(17))
|
||||
#define I2C_RTC_BBPLL_MASK_M (BIT(17))
|
||||
#define I2C_RTC_BBPLL_MASK_V 0x1
|
||||
#define I2C_RTC_BBPLL_MASK_S 17
|
||||
|
||||
#define I2C_RTC_APLL_MASK (BIT(14))
|
||||
#define I2C_RTC_APLL_MASK_M (BIT(14))
|
||||
#define I2C_RTC_APLL_MASK_V 0x1
|
||||
#define I2C_RTC_APLL_MASK_S 14
|
||||
|
||||
#define I2C_RTC_ALL_MASK 0x00007FFF
|
||||
#define I2C_RTC_ALL_MASK_M ((I2C_RTC_ALL_MASK_V)<<(I2C_RTC_ALL_MASK_S))
|
||||
#define I2C_RTC_ALL_MASK_V 0x7FFF
|
||||
#define I2C_RTC_ALL_MASK_S 8
|
||||
|
||||
#define I2C_RTC_CONFIG2 0x6000e000
|
||||
|
||||
#define I2C_RTC_BUSY (BIT(25))
|
||||
#define I2C_RTC_BUSY_M (BIT(25))
|
||||
#define I2C_RTC_BUSY_V 0x1
|
||||
#define I2C_RTC_BUSY_S 25
|
||||
|
||||
#define I2C_RTC_WR_CNTL (BIT(24))
|
||||
#define I2C_RTC_WR_CNTL_M (BIT(24))
|
||||
#define I2C_RTC_WR_CNTL_V 0x1
|
||||
#define I2C_RTC_WR_CNTL_S 24
|
||||
|
||||
#define I2C_RTC_DATA 0x000000FF
|
||||
#define I2C_RTC_DATA_M ((I2C_RTC_DATA_V)<<(I2C_RTC_DATA_S))
|
||||
#define I2C_RTC_DATA_V 0xFF
|
||||
#define I2C_RTC_DATA_S 16
|
||||
|
||||
#define I2C_RTC_ADDR 0x000000FF
|
||||
#define I2C_RTC_ADDR_M ((I2C_RTC_ADDR_V)<<(I2C_RTC_ADDR_S))
|
||||
#define I2C_RTC_ADDR_V 0xFF
|
||||
#define I2C_RTC_ADDR_S 8
|
||||
|
||||
#define I2C_RTC_SLAVE_ID 0x000000FF
|
||||
#define I2C_RTC_SLAVE_ID_M ((I2C_RTC_SLAVE_ID_V)<<(I2C_RTC_SLAVE_ID_S))
|
||||
#define I2C_RTC_SLAVE_ID_V 0xFF
|
||||
#define I2C_RTC_SLAVE_ID_S 0
|
||||
|
||||
#define I2C_RTC_MAGIC_DEFAULT (0x1c40)
|
||||
|
||||
#define I2C_BOD 0x61
|
||||
#define I2C_BBPLL 0x66
|
||||
#define I2C_SAR_ADC 0X69
|
||||
#define I2C_APLL 0X6D
|
||||
|
||||
|
||||
int lastend = 0;
|
||||
|
||||
// This generates a slow sweep over 17.8 seconds of exactly one full SDM0 iteration
|
||||
// this is to measure how good dithering can be.
|
||||
|
||||
const float fRadiator = 28.08; // In MHz 28.08MHz = in RTTY section of 10 Meters HAM band.
|
||||
const float fHarmonic = 1.0;
|
||||
const float fXTAL = 40;
|
||||
|
||||
// Set to 2 for highest possible frequencies (up to 69MHz) Lower to get more control at lower frequencies. This is the part in parenthesis (ODIV+2)
|
||||
// Higher numbers will give you more control. But, there is a limit. 350<40 * (SDM2 + SDM1/(2^8) + SDM0/(2^16) + 4)<500
|
||||
// Set to 3 for up to 46MHz
|
||||
// Set to 4 for up to 34MHz
|
||||
// set to 5 for up to 27MHz (well 27MHzish, you can go a tad higher)
|
||||
const float nPLLDivisorD2 = 5;
|
||||
|
||||
|
||||
|
||||
|
||||
// Configures APLL = 480 / 4 = 120
|
||||
// 40 * (SDM2 + SDM1/(2^8) + SDM0/(2^16) + 4) / ( 2 * (ODIV+2) );
|
||||
// Datasheet recommends that numerator does not exceed 500MHz.
|
||||
void IRAM_ATTR local_rtc_clk_apll_enable(bool enable, uint32_t sdm0, uint32_t sdm1, uint32_t sdm2, uint32_t o_div)
|
||||
{
|
||||
REG_SET_FIELD(RTC_CNTL_ANA_CONF_REG, RTC_CNTL_PLLA_FORCE_PD, enable ? 0 : 1);
|
||||
REG_SET_FIELD(RTC_CNTL_ANA_CONF_REG, RTC_CNTL_PLLA_FORCE_PU, enable ? 1 : 0);
|
||||
|
||||
if (enable) {
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_DSDM2, sdm2);
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_DSDM0, sdm0);
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_DSDM1, sdm1);
|
||||
REGI2C_WRITE(I2C_APLL, I2C_APLL_SDM_STOP, CLK_LL_APLL_SDM_STOP_VAL_1);
|
||||
REGI2C_WRITE(I2C_APLL, I2C_APLL_SDM_STOP, CLK_LL_APLL_SDM_STOP_VAL_2_REV1);
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_OR_OUTPUT_DIV, o_div );
|
||||
}
|
||||
|
||||
|
||||
// Settings determined experimentally.
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_OC_TSCHGP, 0 ); // 0 or 1
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_EN_FAST_CAL, 1 ); // 0 or 1
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_OC_DHREF_SEL, 3 ); // 0..3
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_OC_DLREF_SEL, 2 ); // 0..3
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_SDM_DITHER, 1 ); // 0 or 1
|
||||
REGI2C_WRITE_MASK(I2C_APLL, I2C_APLL_OC_DVDD, 25 ); // 0 .. 31
|
||||
|
||||
}
|
||||
|
||||
|
||||
void IRAM_ATTR regi2c_write_reg_raw_local(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t data)
|
||||
{
|
||||
uint32_t temp = ((block & I2C_RTC_SLAVE_ID_V) << I2C_RTC_SLAVE_ID_S)
|
||||
| ((reg_add & I2C_RTC_ADDR_V) << I2C_RTC_ADDR_S)
|
||||
| ((0x1 & I2C_RTC_WR_CNTL_V) << I2C_RTC_WR_CNTL_S)
|
||||
| (((uint32_t)data & I2C_RTC_DATA_V) << I2C_RTC_DATA_S);
|
||||
while (REG_GET_BIT(I2C_RTC_CONFIG2, I2C_RTC_BUSY));
|
||||
REG_WRITE(I2C_RTC_CONFIG2, temp);
|
||||
}
|
||||
|
||||
|
||||
void apll_quick_update( uint32_t sdm )
|
||||
{
|
||||
uint8_t sdm2 = sdm>>16;
|
||||
uint8_t sdm1 = (sdm>>8)&0xff;
|
||||
uint8_t sdm0 = (sdm>>0)&0xff;
|
||||
static int last_sdm_0 = -1;
|
||||
static int last_sdm_1 = -1;
|
||||
static int last_sdm_2 = -1;
|
||||
|
||||
if( sdm2 != last_sdm_2 )
|
||||
regi2c_write_reg_raw_local(I2C_APLL, I2C_APLL_HOSTID, I2C_APLL_DSDM2, sdm2);
|
||||
if( sdm0 != last_sdm_0 )
|
||||
regi2c_write_reg_raw_local(I2C_APLL, I2C_APLL_HOSTID, I2C_APLL_DSDM0, sdm0);
|
||||
if( sdm1 != last_sdm_1 )
|
||||
regi2c_write_reg_raw_local(I2C_APLL, I2C_APLL_HOSTID, I2C_APLL_DSDM1, sdm1);
|
||||
|
||||
last_sdm_2 = sdm2;
|
||||
last_sdm_1 = sdm1;
|
||||
last_sdm_0 = sdm0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void sandbox_main()
|
||||
{
|
||||
printf( "sandbox_main()\n" );
|
||||
|
||||
|
||||
|
||||
DPORT_SET_PERI_REG_MASK( DPORT_CPU_PERI_CLK_EN_REG, DPORT_CLK_EN_DEDICATED_GPIO );
|
||||
DPORT_CLEAR_PERI_REG_MASK( DPORT_CPU_PERI_RST_EN_REG, DPORT_RST_EN_DEDICATED_GPIO);
|
||||
|
||||
// Setup GPIO39 to be the PRO ALONE output (For LEDs)
|
||||
REG_WRITE( GPIO_OUT1_W1TC_REG, 1<<(39-32) );
|
||||
REG_WRITE( GPIO_ENABLE1_W1TS_REG, 1<<(39-32) );
|
||||
REG_WRITE( IO_MUX_GPIO39_REG, 2<<FUN_DRV_S );
|
||||
REG_WRITE( GPIO_FUNC39_OUT_SEL_CFG_REG, PRO_ALONEGPIO_OUT0_IDX );
|
||||
REG_WRITE( DEDIC_GPIO_OUT_CPU_REG, 0x01 ); // Enable CPU instruction output
|
||||
|
||||
|
||||
// Output clock on P2.
|
||||
|
||||
// Maximize the drive strength.
|
||||
gpio_set_drive_capability( GPIO_NUM(RF1_PIN), GPIO_DRIVE_CAP_3 );
|
||||
gpio_set_drive_capability( GPIO_NUM(RF2_PIN), GPIO_DRIVE_CAP_3 );
|
||||
|
||||
// Use the IO matrix to create the inverse of TX on pin 17.
|
||||
gpio_matrix_out( GPIO_NUM(RF1_PIN), CLK_I2S_MUX_IDX, 1, 0 );
|
||||
gpio_matrix_out( GPIO_NUM(RF2_PIN), CLK_I2S_MUX_IDX, 0, 0 );
|
||||
|
||||
periph_module_enable(PERIPH_I2S0_MODULE);
|
||||
|
||||
int use_apll = 1;
|
||||
|
||||
// Start with a default tone.
|
||||
int sdm0 = 100;
|
||||
int sdm1 = 230;
|
||||
int sdm2 = 8;
|
||||
int odiv = nPLLDivisorD2-2;
|
||||
|
||||
local_rtc_clk_apll_enable( use_apll, sdm0, sdm1, sdm2, odiv );
|
||||
|
||||
if( use_apll )
|
||||
{
|
||||
WRITE_PERI_REG( I2S_CLKM_CONF_REG(0), (1<<I2S_CLK_SEL_S) | (1<<I2S_CLK_EN_S) | (0<<I2S_CLKM_DIV_A_S) | (0<<I2S_CLKM_DIV_B_S) | (1<<I2S_CLKM_DIV_NUM_S) );
|
||||
}
|
||||
else
|
||||
{
|
||||
// fI2S = fCLK / ( N + B/A )
|
||||
// DIV_NUM = N
|
||||
// Note I2S_CLKM_DIV_NUM minimum = 2 by datasheet. Less than that and it will ignoreeee you.
|
||||
WRITE_PERI_REG( I2S_CLKM_CONF_REG(0), (2<<I2S_CLK_SEL_S) | (1<<I2S_CLK_EN_S) | (0<<I2S_CLKM_DIV_A_S) | (0<<I2S_CLKM_DIV_B_S) | (1<<I2S_CLKM_DIV_NUM_S) ); // Minimum reduction, 2:1
|
||||
}
|
||||
|
||||
lastend = getCycleCount();
|
||||
}
|
||||
|
||||
|
||||
|
||||
#define DisableISR() do { XTOS_SET_INTLEVEL(XCHAL_EXCM_LEVEL); portbenchmarkINTERRUPT_DISABLE(); } while (0)
|
||||
#define EnableISR() do { portbenchmarkINTERRUPT_RESTORE(0); XTOS_SET_INTLEVEL(0); } while (0)
|
||||
|
||||
|
||||
uint32_t frame = 0;
|
||||
void sandbox_tick()
|
||||
{
|
||||
|
||||
|
||||
const float fTarg = (fRadiator)/fHarmonic;
|
||||
const float fAPLL = fTarg * 2;
|
||||
const uint32_t sdmBaseTarget = ( fAPLL * (nPLLDivisorD2*2) / fXTAL - 4 ) * 65536 + 0.5; // ~649134
|
||||
|
||||
|
||||
{
|
||||
int iterct = 0;
|
||||
int dither = 0;
|
||||
|
||||
gpio_matrix_out( GPIO_NUM(RF1_PIN), CLK_I2S_MUX_IDX, 1, 0 );
|
||||
gpio_matrix_out( GPIO_NUM(RF2_PIN), CLK_I2S_MUX_IDX, 0, 0 );
|
||||
|
||||
//DisableISR();
|
||||
|
||||
while(1)
|
||||
{
|
||||
int fplv = 0;
|
||||
frame = (getCycleCount());
|
||||
fplv = 0;
|
||||
int microtone = ((frame & 0xfff00000 ) >> 20);
|
||||
dither = (((iterct)&0xffff)<microtone)?1:0;
|
||||
uint32_t sdm = sdmBaseTarget + fplv + dither;//( fplv ) / sdmDivisor + dither;
|
||||
apll_quick_update( sdm );
|
||||
iterct++;
|
||||
}
|
||||
|
||||
gpio_matrix_out( GPIO_NUM(RF1_PIN), CLK_I2S_MUX_IDX, 1, 1 );
|
||||
gpio_matrix_out( GPIO_NUM(RF2_PIN), CLK_I2S_MUX_IDX, 0, 1 );
|
||||
|
||||
printf( "Iter: %d\n", iterct );
|
||||
lastend = getCycleCount();
|
||||
}
|
||||
|
||||
// vTaskDelay( 1 );
|
||||
}
|
||||
|
||||
struct SandboxStruct
|
||||
{
|
||||
void (*fnIdle)();
|
||||
};
|
||||
struct SandboxStruct sandbox_mode =
|
||||
{
|
||||
.fnIdle = sandbox_tick,
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Charles Lohr "CNLohr"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "sdkconfig.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_system.h"
|
||||
#include "spi_flash_mmap.h"
|
||||
#include "esp_efuse.h"
|
||||
#include "esp_efuse_table.h" // or "esp_efuse_custom_table.h"
|
||||
#include "esp_task_wdt.h"
|
||||
#include "esp_log.h"
|
||||
#include "soc/dedic_gpio_reg.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "soc/soc.h"
|
||||
#include "soc/system_reg.h"
|
||||
#include "soc/usb_reg.h"
|
||||
#include "ulp_riscv.h"
|
||||
#include "driver/rtc_io.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "rom/gpio.h"
|
||||
#include "soc/rtc.h"
|
||||
|
||||
#define SOC_DPORT_USB_BASE 0x60080000
|
||||
|
||||
struct SandboxStruct
|
||||
{
|
||||
void (*fnIdle)();
|
||||
};
|
||||
|
||||
|
||||
struct SandboxStruct * g_SandboxStruct;
|
||||
|
||||
|
||||
void esp_sleep_enable_timer_wakeup();
|
||||
|
||||
volatile void * keep_symbols[] = { 0, vTaskDelay, ulp_riscv_halt,
|
||||
ulp_riscv_timer_resume, ulp_riscv_timer_stop, ulp_riscv_load_binary,
|
||||
ulp_riscv_run, ulp_riscv_config_and_run, esp_sleep_enable_timer_wakeup,
|
||||
ulp_set_wakeup_period, rtc_gpio_init, rtc_gpio_set_direction,
|
||||
rtc_gpio_set_level, gpio_config, gpio_matrix_out, gpio_matrix_in,
|
||||
rtc_clk_cpu_freq_get_config, rtc_clk_cpu_freq_set_config_fast,
|
||||
rtc_clk_apb_freq_get };
|
||||
|
||||
extern struct SandboxStruct sandbox_mode;
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
printf("Hello world! Keep table at %p\n", &keep_symbols );
|
||||
|
||||
g_SandboxStruct = &sandbox_mode;
|
||||
|
||||
// esp_efuse_set_rom_log_scheme(ESP_EFUSE_ROM_LOG_ALWAYS_OFF);
|
||||
esp_efuse_set_rom_log_scheme(ESP_EFUSE_ROM_LOG_ALWAYS_ON);
|
||||
|
||||
printf("Minimum free heap size: %d bytes\n", (int)esp_get_minimum_free_heap_size());
|
||||
|
||||
void sandbox_main();
|
||||
|
||||
sandbox_main();
|
||||
|
||||
do
|
||||
{
|
||||
if( g_SandboxStruct && g_SandboxStruct->fnIdle ) { g_SandboxStruct->fnIdle(); }
|
||||
esp_task_wdt_reset();
|
||||
taskYIELD();
|
||||
} while( 1 );
|
||||
|
||||
// printf("Restarting now.\n");
|
||||
// fflush(stdout);
|
||||
// esp_restart();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
# Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
|
||||
# Note: if you change the size of the nvs partition, make sure to update NVS_PARTITION_SIZE in `components/hdw-nvs/nvs_manager.h`
|
||||
nvs, data, nvs, 0x9000, 0x6000,
|
||||
phy_init, data, phy, 0xf000, 0x1000,
|
||||
factory, app, factory, 0x10000, 1M,
|
||||
storage, data, spiffs, , 0xF0000,
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -223,7 +223,6 @@ blocks:
|
||||
alias: ''
|
||||
comment: ''
|
||||
en_uvec: 'True'
|
||||
log_level: info
|
||||
states:
|
||||
bus_sink: false
|
||||
bus_source: false
|
||||
@@ -467,7 +466,7 @@ blocks:
|
||||
ant8: ''
|
||||
ant9: ''
|
||||
args: '"airspy=0"'
|
||||
bb_gain0: '10'
|
||||
bb_gain0: '25'
|
||||
bb_gain1: '20'
|
||||
bb_gain10: '20'
|
||||
bb_gain11: '20'
|
||||
@@ -604,7 +603,7 @@ blocks:
|
||||
dc_offset_mode7: '0'
|
||||
dc_offset_mode8: '0'
|
||||
dc_offset_mode9: '0'
|
||||
freq0: '1090000000'
|
||||
freq0: '100000000'
|
||||
freq1: 100e6
|
||||
freq10: 100e6
|
||||
freq11: 100e6
|
||||
@@ -636,7 +635,7 @@ blocks:
|
||||
freq7: 100e6
|
||||
freq8: 100e6
|
||||
freq9: 100e6
|
||||
gain0: '10'
|
||||
gain0: '25'
|
||||
gain1: '10'
|
||||
gain10: '10'
|
||||
gain11: '10'
|
||||
@@ -700,7 +699,7 @@ blocks:
|
||||
gain_mode7: 'False'
|
||||
gain_mode8: 'False'
|
||||
gain_mode9: 'False'
|
||||
if_gain0: '10'
|
||||
if_gain0: '25'
|
||||
if_gain1: '20'
|
||||
if_gain10: '20'
|
||||
if_gain11: '20'
|
||||
@@ -1282,4 +1281,4 @@ connections:
|
||||
|
||||
metadata:
|
||||
file_format: 1
|
||||
grc_version: 3.10.7.0
|
||||
|
||||
|
||||
Reference in New Issue
Block a user