Compare commits

...

49 Commits

Author SHA1 Message Date
cnlohr 5e79b88354 Add generic tools. They have not been validated yet. 2025-11-04 04:53:10 -05:00
cnlohr 3bb8c87519 Fix Merch Link 2025-01-04 17:26:28 -08:00
cnlohr 77cfc9f3b7 Fix compile (see Issue #13) 2024-11-30 15:35:49 -08:00
cnlohr ae63b4208f Bump 2024-11-17 00:19:01 -08:00
cnlohr 1940782c3d Forgot readme 2024-11-17 01:10:29 -05:00
cnlohr e5cd85ebf8 add skitterrx 2024-11-17 01:09:49 -05:00
cnlohr 7f57e4b003 Add references to some links 2024-11-06 10:57:31 -08:00
cnlohr 966076d5ed Fix merch link 2024-11-02 16:07:04 -04:00
cnlohr ce7b9c05d1 Merge pull request #12 from cnlohr/experiments_with_timers
More RF Shenanigans + Receiving with just a wire and an ADC.
2024-11-01 23:06:29 -07:00
cnlohr c7900d08b0 Add licenses and readme to lib files in ch32v 2024-11-02 02:05:13 -04:00
cnlohr 7f0f6ecb67 UUpdate readme with merch link 2024-11-02 01:49:14 -04:00
cnlohr 58aae1becd Bump readme 2024-10-31 18:35:37 -04:00
cnlohr 56ac27833b Try relative links 2024-10-31 18:29:44 -04:00
cnlohr 22c2149507 Adjust warnings 2024-10-31 18:27:46 -04:00
cnlohr e3ed2e9084 cleanup repo ready for release 2024-10-31 18:25:44 -04:00
cnlohr 73a80f4099 Merge pull request #11 from cnlohr/master
Merge from master
2024-10-29 11:17:56 -07:00
cnlohr 0033874cab Merge branch 'master' into experiments_with_timers 2024-10-29 11:18:26 -07:00
cnlohr 21a585236d Change gen code from rebuilding tree constantly. 2024-10-28 23:19:06 -07:00
cnlohr 710a07d913 Fix stylization for firefox 2024-10-28 20:08:03 -07:00
cnlohr ac768babae CSS Stylize the calculator page. 2024-10-28 18:49:33 -07:00
cnlohr 1115329d6b Update to use SPI OLED 2024-10-28 02:39:40 -07:00
cnlohr ccf9c1305b Update with remote clock precision checking 2024-10-15 05:50:57 -04:00
cnlohr 2cb413d827 Fix formatting + Prevent LCD from failing at startup 2024-10-15 04:50:19 -04:00
cnlohr fc83ea3c40 Add narrow FSK test 2024-10-15 03:09:55 -04:00
cnlohr a08fdc845b Add a very basic text app to make some tones 2024-10-13 05:18:31 -04:00
cnlohr f6b5dfe68d Cleanup 2024-10-10 01:11:08 -07:00
cnlohr a65de155c0 Bump submodule 2024-10-10 00:06:56 -07:00
cnlohr 9239f43759 Improve usability of various things 2024-10-09 23:35:23 -07:00
cnlohr c1bdfe0acf Add decibel control. 2024-10-09 03:03:32 -07:00
cnlohr 147fdc514d Niceities when working with the webpage. 2024-10-09 02:16:14 -07:00
cnlohr 933a3d4347 Dual mode working 2024-10-09 01:05:35 -07:00
cnlohr 4c84e5e538 Working - full vector scope, no dual mode yet 2024-10-08 22:19:46 -07:00
cnlohr 01216baaf9 Update oscope code + autoreconnect in webpageo 2024-10-08 21:25:10 -07:00
cnlohr 9044689537 Middle before totally swapping to new mode 2024-10-08 19:50:22 -07:00
cnlohr 529e85e066 Working with manual tuning. Still need to do vectorscope 2024-10-07 00:39:40 -07:00
cnlohr b2995f435f Working with phasor re-rotation 2024-10-06 23:06:59 -07:00
cnlohr 85fe805e32 Fix note about value of atrlr 2024-10-06 03:59:16 -07:00
cnlohr 6802a917ae Catch a couple missing updates + add 203 TX 2024-10-06 03:58:44 -07:00
cnlohr 39dbd6df19 Update, as good as I could generally get 003->003 2024-10-06 02:27:01 -07:00
cnlohr 591065938d Add readme for failed experiment 2024-10-06 05:26:38 -04:00
cnlohr 0273cb8d94 Bump 2024-10-06 05:25:09 -04:00
CNLohr d5d9de86bd Update README.md
Refs #8
2024-04-02 22:41:20 -04:00
CNLohr a9b780daea Merge pull request #7 from budnik/patch-1
Update README.md
2024-04-02 19:40:03 -07:00
CNLohr d5dbc3a7c0 Merge pull request #5 from eltociear/patch-1
Update README.md
2024-04-02 19:39:29 -07:00
CNLohr 53a4ac1115 Update README.md
Closes #4
2024-04-02 22:33:19 -04:00
Dmytro Budnyk 0872256b3c Update README.md
Fixes internal links for pages with spaces. Makes them work on github.com
2024-03-30 23:58:30 +02:00
Ikko Eltociear Ashimine d17b0ee51e Update README.md
tageting -> targeting
2024-03-29 00:43:02 +09:00
CNLohr dc1d3d1d2c Update README.md 2024-03-27 16:25:23 -07:00
cnlohr 6948175113 Initial Commit 2024-03-25 14:52:07 -07:00
49 changed files with 4645 additions and 392 deletions
+131 -75
View File
@@ -1,25 +1,73 @@
# LoLRa # 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) If you are looking for the Hackaday 2024 microcontroller radio talk, you can <a href=https://cnlohr.github.io/lolra_talk>click here</a>.
If you are looking for LoLRa Merch (Like t-shirts, etc.), <a href="https://cnlohr-shop.fourthwall.com/">click here</a>.
* [Introduct and repo overview](#introduction-and-repo-overview)
* LoRa
* [Introduction (LoRa)](#introduction-lora)
* [Background](#background) * [Background](#background)
* [LoRaWAN](#lorawan) * [LoRaWAN](#lorawan)
* [Limitations](#limitations) * [Limitations](#limitations)
* [Future Work](#future_Work) * [Future Work](#future-work)
* [Resources](#resources) * [Resources](#resources)
* [Special Thanks](#special_thanks) * [Special Thanks](#special-thanks)
* [Range Tests](#range_tests) * [Range Tests](#range-tests)
## Introduction
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.
> [!NOTE] > [!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 ![LICENSE](LICENSE) 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] > [!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. There are two major modes that this repository works with.
@@ -31,16 +79,13 @@ Click Below for the Youtube Video version of this page:
[![LoRa Without A Radio](https://i3.ytimg.com/vi/eIdHBDSQHyw/maxresdefault.jpg)](https://www.youtube.com/watch?v=eIdHBDSQHyw) [![LoRa Without A Radio](https://i3.ytimg.com/vi/eIdHBDSQHyw/maxresdefault.jpg)](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 ![LICENSE](LICENSE) for more information.
## Background ## Background
### Square waves, and images ### 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)
![Square 220 Hz](https://github.com/cnlohr/lolra/blob/master/resources/SquareHarmonics.png?raw=true) ![Square 220 Hz](https://github.com/cnlohr/lolra/blob/master/resources/SquareHarmonics.png?raw=true)
@@ -68,13 +113,13 @@ The second principle is signal mixing. If you create a signal, then "mix" it wi
![Signal Mixing](https://github.com/cnlohr/lolra/blob/master/resources/UpSpectrumImages.png?raw=true) ![Signal Mixing](https://github.com/cnlohr/lolra/blob/master/resources/UpSpectrumImages.png?raw=true)
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. 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: Crystal Output:
![Crystal Output](resources/CrystalOut.png) ![Crystal Output](resources/CrystalOut.png)
@@ -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. 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. 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.
![Bitstream Analysis](resources/bitstreamdiagram.png) ![Bitstream Analysis](resources/bitstreamdiagram.png)
You can see from the above diagram 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. * **** 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. * **** 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. * **** 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). * **** 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 **𝔼**. * 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. 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. 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. 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! 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: 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. 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 fundamentally limits the performance of the sending of frames. 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. 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. 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. 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 ## 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 ### 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: Setup is pretty starightforward. You need to:
1. Create an account (they are free for personal/academic use) 1. Create an account (they are free for personal/academic use)
@@ -175,14 +220,14 @@ Setup is pretty starightforward. You need to:
## Limitations ## Limitations
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. * 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. * 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) * 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 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. * 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 ## 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. 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! 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 ## Range Tests
Urban testing was performed on 2024-02-23, Suburban on 2022-02-26 and Rural testing was performed on 2022-02-27. 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 | 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-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 | 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-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 | | 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 @ 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 | 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) (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 + 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 Percipitation | 705' / 215m | -139 / -15 | 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 | | 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. 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. 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
-2
View File
@@ -1,5 +1,3 @@
// XXX TODO: Play with high bits of ADC control to see if there's a gain cicuit.
/** /**
MIT-like-non-ai-license MIT-like-non-ai-license
+21
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
THIS DOES NOT WORK DO NOT USE IT YET
+378
View File
@@ -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 );
}
+10
View File
@@ -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.
+155
View File
@@ -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
+9
View File
@@ -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'
+20 -13
View File
@@ -60,6 +60,8 @@ SOFTWARE.
uint32_t dmadata[DMA_SIZE/2] __attribute__((aligned(64))); uint32_t dmadata[DMA_SIZE/2] __attribute__((aligned(64)));
uint32_t ercnt = 0;
#define IQDLEN 32 #define IQDLEN 32
int32_t lastintenR[IQDLEN], lastintenI[IQDLEN]; int32_t lastintenR[IQDLEN], lastintenI[IQDLEN];
uint32_t intenhead; uint32_t intenhead;
@@ -79,6 +81,7 @@ void DMA1_Channel1_IRQHandler( void )
static uint32_t * here = dmadata; static uint32_t * here = dmadata;
static uint32_t thisintenR; static uint32_t thisintenR;
static uint32_t thisintenI; 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 the next data we want to analyize.
// We have a pointer to where the tail of the new data is. // We have a pointer to where the tail of the new data is.
@@ -91,22 +94,21 @@ void DMA1_Channel1_IRQHandler( void )
// two. And we either reset the pointer to the beginning of // two. And we either reset the pointer to the beginning of
// the array, OR, we stop because we ran out of data. // the array, OR, we stop because we ran out of data.
do
{
uint32_t cnt = DMA1_Channel1->CNTR; uint32_t cnt = DMA1_Channel1->CNTR;
if( cnt == 0 ) cnt = 1; if( cnt == 0 ) cnt = 1;
uint32_t tail_offset = DMA_SIZE - cnt; 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 * tail = dmadata + tail_offset/2; // Tuncate down to quads if a pair has not been fully written.
uint32_t * stopat = (here < tail) ? tail : end; uint32_t * stopat = (here < tail) ? tail : end;
if( here == tail ) break; do
{
do do
{ {
int32_t vA = *(here++); int32_t vA = *(here++);
int32_t vB = *(here++); int32_t vB = *(here++);
thisintenR += (vA&0x3ff) - (vB >> 16); thisintenR += (vA&0xfff) - (vB&0xfff);
thisintenI += (vB&0x3ff) - (vA >> 16); thisintenI += (vA >> 16) - (vB >> 16);
rcnt++;
} while( here != stopat ); } while( here != stopat );
@@ -120,6 +122,8 @@ void DMA1_Channel1_IRQHandler( void )
thisintenR = 0; thisintenR = 0;
thisintenI = 0; thisintenI = 0;
here = head; here = head;
ercnt = rcnt;
rcnt = 0;
wordouts++; wordouts++;
} }
@@ -136,8 +140,6 @@ int main()
Delay_Ms( 100 ); Delay_Ms( 100 );
funPinMode( ADC_PIN, GPIO_CFGLR_IN_ANALOG );
EXTEND->CTR = 1<<10; // LDO trim EXTEND->CTR = 1<<10; // LDO trim
funGpioInitAll(); funGpioInitAll();
@@ -156,7 +158,7 @@ int main()
// set sampling time for chl 7, 4, 3, 2 // set sampling time for chl 7, 4, 3, 2
// 0:7 => 3/9/15/30/43/57/73/241 cycles // 0:7 => 3/9/15/30/43/57/73/241 cycles
#ifdef USE_TIMER #ifdef USE_TIMER
ADC1->SAMPTR2 = (0<<(3*ADCNO)); ADC1->SAMPTR2 = (1<<(3*ADCNO));
#else #else
ADC1->SAMPTR2 = (3<<(3*ADCNO)); ADC1->SAMPTR2 = (3<<(3*ADCNO));
#endif #endif
@@ -208,7 +210,7 @@ int main()
#ifdef USE_TIMER #ifdef USE_TIMER
TIM2->PSC = 0x0000; // Prescalar TIM2->PSC = 0x0000; // Prescalar
TIM2->ATRLR = 49; // TIM2 max before reset. 48 = Period of 49 cycles. TIM2->ATRLR = 46; // TIM2 max before reset. 48 = Period of 49 cycles.
TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE; TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE;
TIM2->CTLR1 = TIM_ARPE; TIM2->CTLR1 = TIM_ARPE;
TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP; TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP;
@@ -224,9 +226,14 @@ int main()
funPinMode( LEDPIN, GPIO_CFGLR_OUT_50Mhz_PP ); funPinMode( LEDPIN, GPIO_CFGLR_OUT_50Mhz_PP );
//funPinMode( PD4, GPIO_CFGLR_OUT_50Mhz_AF_PP ); //funPinMode( PD4, GPIO_CFGLR_OUT_50Mhz_AF_PP );
funPinMode( ADC_PIN,
//GPIO_CFGLR_IN_PUPD
GPIO_CFGLR_IN_ANALOG
);
while(1) while(1)
{ {
// printf( "%5d %5d %d %d %d %d\n", (int)lastintenR[intenhead], (int)lastintenI[intenhead], dmadata[0]&0xfff, dmadata[0]>>16, dmadata[1]&0xfff, dmadata[1]>>16 ); 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; int i;
int32_t lR[8], lI[8]; int32_t lR[8], lI[8];
@@ -240,10 +247,10 @@ int main()
for( i = 0; i < 8; i++ ) for( i = 0; i < 8; i++ )
{ {
printf( "%6d%6d\n", lR[i], lI[i] ); printf( "%6ld%6ld\n", lR[i], lI[i] );
} }
printf( "%08x %d\n", dmadata[0], wordouts ); printf( "%08lx %ld ** %d\n", dmadata[0], wordouts, ercnt );
Delay_Ms( 1000 ); Delay_Ms( 1000 );
} }
+11 -10
View File
@@ -67,25 +67,26 @@ int main()
TIM2->PSC = 0x0000; // Prescalar TIM2->PSC = 0x0000; // Prescalar
TIM2->ATRLR = 3; // Max TIM2->ATRLR = 3; // Max
TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE; TIM2->CHCTLR1 = TIM_OC1M_2 | TIM_OC1M_1 | TIM_OC1PE | TIM_OC1FE;
TIM2->CTLR1 = TIM_ARPE; TIM2->CTLR1 = TIM_ARPE;
TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP; TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP;
TIM2->SWEVGR = TIM_UG; TIM2->SWEVGR = TIM_UG;
// Enable TIM2 // Enable TIM2
TIM2->CTLR1 |= TIM_CEN; TIM2->CTLR1 |= TIM_CEN;
TIM2->CH1CVR = 2; TIM2->CH1CVR = TIM2->ATRLR/2;
printf( "Going\n"); while(1);
while(1) while(1)
; {
/* { TIM2->CH1CVR = 2;
TIM2->CCER = TIM_CC1E | TIM_CC1P | TIM_CC1NP;
funDigitalWrite( LEDPIN, 1 );
Delay_Ms( 1000 );
TIM2->CCER = TIM_CC1E | TIM_CC1P; TIM2->CCER = TIM_CC1E | TIM_CC1P;
funDigitalWrite( LEDPIN, 1 );
Delay_Us( 1500 );
TIM2->CCER = TIM_CC1E;
TIM2->CH1CVR = 2;
funDigitalWrite( LEDPIN, 0 ); funDigitalWrite( LEDPIN, 0 );
Delay_Ms( 1000 ); Delay_Us( 1500 );
}*/ }
} }
+1
View File
@@ -81,6 +81,7 @@ volatile uint16_t adc_buffer[ADC_BUFFSIZE];
void SetupADC() void SetupADC()
{ {
// XXX TODO -look into PGA // XXX TODO -look into PGA
// XXX TODO - look into BUFEN and TKITUNE
// XXX TODO - Look into tag-teaming the ADCs // XXX TODO - Look into tag-teaming the ADCs
// PDA is analog input chl 7 // PDA is analog input chl 7
+9 -4
View File
@@ -62,8 +62,13 @@ SOFTWARE.
#include <stdio.h> #include <stdio.h>
#define SH1107_128x128 #define SH1107_128x128
#define SSD1306_REMAP_I2C #define SSD1306_RST_PIN PA3
#include "ssd1306_i2c.h" #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" #include "ssd1306.h"
#define FIX_FFT_IMPLEMENTATION #define FIX_FFT_IMPLEMENTATION
@@ -442,8 +447,8 @@ int main()
SetupADC(); SetupADC();
printf( "Setting up OLED.\n" ); printf( "Setting up OLED.\n" );
ssd1306_i2c_setup(); //ssd1306_spi_setup();
uint8_t ret = ssd1306_i2c_init(); uint8_t ret = ssd1306_spi_init();
ssd1306_init(); ssd1306_init();
ssd1306_setbuf(0); ssd1306_setbuf(0);
+3
View File
@@ -27,3 +27,6 @@ TODO: TODO: Test HTML values.
TODO: TODO: g_goertzel_omega_per_sample lokos WRONG. TODO: TODO: g_goertzel_omega_per_sample lokos WRONG.
Extra notes:
.87996033 = 880 AM, why?
+337 -197
View File
@@ -41,36 +41,65 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
**/ **/
// NOT LORA!!! -- but experimenting with the possibility of rx.
// SETUP INSTRUCTIONS: // SETUP INSTRUCTIONS:
// (1) `make` in the optionbytes folder to configure `RESET` correctly. // (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) 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 // (2) or, for 24.387096762MHz - ../ch32v003fun/minichlink/minichlink -X ECLK 1:150:49:8:3
/* More notes /* More notes
* Minimum sample time with DMA = fCPU / 28 (5.14MHz) * Minimum sample time with DMA = fCPU / 28 (5.14MHz)
*/ */
// TODO:
// 1: Cleanup some code.
// 2: Leverage other ADC.
// 3:
#include "ch32v003fun.h" #include "ch32v003fun.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.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 SH1107_128x128
#define SSD1306_REMAP_I2C #define SSD1306_REMAP_I2C
//#define PWM_OUTPUT //#define SSD1306_I2C_IRQ
#define ENABLE_OLED
#define PROFILING_PIN PA0
#include "ssd1306_i2c.h" #include "ssd1306_i2c.h"
#include "ssd1306.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 "./usb_config.h"
#include "../ch32v003fun/examples_v20x/otg_device/otgusb.h" #include "../ch32v003fun/examples_v20x/otg_device/otgusb.h"
@@ -79,72 +108,22 @@ SOFTWARE.
volatile uint16_t adc_buffer[ADC_BUFFSIZE]; volatile uint16_t adc_buffer[ADC_BUFFSIZE];
int g_volume_pwm = 127; // 0 - 127 (100%) (but you can go over 100) int32_t g_goertzel_phasor_r = 32768;
int32_t g_goertzel_phasor_i = 0;
#if 0 int32_t g_attenuation_pow2 = 4;
int g_pwm_period = (30-1);
int g_goertzel_buffer = (752);
int g_exactcompute = (0);
int32_t g_goertzel_omega_per_sample = 2485087396; // 0.368351 of whole per step / 27.031915MHz
int32_t g_goertzel_coefficient = -1453756170;
int32_t g_goertzel_coefficient_s = 1580594514;
#endif
#if 1 #if 1
int g_pwm_period = (30-1); // Very basic setup, for tuning to 880AM
int g_goertzel_buffer = (180); int g_pwm_period = (60-1);
int g_exactcompute = (0); int g_exactcompute = (1);
int32_t g_goertzel_omega_per_sample = 5509657063; // 0.816667 of whole per step / 0.880000MHz 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 = 873460290;
int32_t g_goertzel_coefficient_s = -1961823932; int32_t g_goertzel_coefficient_s = 1961823932;
int32_t g_goertzel_advance_r = -3425;
int32_t g_goertzel_advance_i = 32588;
#endif #endif
#if 0
int g_pwm_period = (31-1);
int g_goertzel_buffer = (412);
int g_exactcompute = (0);
const int32_t g_goertzel_omega_per_sample = 1670254667; // 0.247573 of whole per step / 1.150016MHz
const int32_t g_goertzel_coefficient = 32748822;
const int32_t g_goertzel_coefficient_s = 2147233926;
#endif
#if 0
int g_pwm_period = (30-1);
int g_goertzel_buffer = (576);
int g_exactcompute = (0);
int32_t g_goertzel_omega_per_sample = 1264972285; // 0.187500 of whole per step / 90.300000MHz
int32_t g_goertzel_coefficient = 821806413;
int32_t g_goertzel_coefficient_s = 1984016189;
#endif
#if 0
int g_pwm_period = (30-1);
int g_goertzel_buffer = (320);
int g_exactcompute = (0);
const int32_t g_goertzel_omega_per_sample = 990894956; // 0.146875 of whole per step / 101.505000MHz
const int32_t g_goertzel_coefficient = 1296126516;
const int32_t g_goertzel_coefficient_s = 1712233066;
#endif
#if 0
int g_pwm_period = (30-1);
int g_goertzel_buffer = (384);
int g_exactcompute = (0);
const int32_t g_goertzel_omega_per_sample = 4251712402; // 0.630208 of whole per step / 27.025000MHz
const int32_t g_goertzel_coefficient = -1468003291;
const int32_t g_goertzel_coefficient_s = -1567371161;
#endif
#if 0
int g_pwm_period = (30-1);
int g_goertzel_buffer = (336);
int g_exactcompute = (0);
const int32_t g_goertzel_omega_per_sample = 1827182189; // 0.270833 of whole per step / 89.900000MHz
const int32_t g_goertzel_coefficient = -280302863;
const int32_t g_goertzel_coefficient_s = 2129111628;
#endif
int intensity_average = 1; int intensity_average = 1;
#define LOG_GOERTZEL_LIST 512 #define LOG_GOERTZEL_LIST 512
@@ -156,45 +135,59 @@ void SetupADC()
// XXX TODO -look into PGA // XXX TODO -look into PGA
// XXX TODO - Look into tag-teaming the ADCs // XXX TODO - Look into tag-teaming the ADCs
// PDA is analog input chl 7 // PDA is analog input chl CHANNEL
GPIOA->CFGLR &= ~(0xf<<(4*7)); // CNF = 00: Analog, MODE = 00: Input GPIOA->CFGLR &= ~(0xf<<(4*CHANNEL)); // CNF = 00: Analog, MODE = 00: Input
// ADC CLK is chained off of APB2. // ADC CLK is chained off of APB2.
// Reset the ADC to init all regs // Reset the ADC to init all regs
RCC->APB2PRSTR |= RCC_APB2Periph_ADC1; RCC->APB2PRSTR |= RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2;
RCC->APB2PRSTR &= ~RCC_APB2Periph_ADC1; RCC->APB2PRSTR &= ~( RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 );
// ADCCLK = 12 MHz => RCC_ADCPRE divide by 4 // 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; // 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. 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 // Set up single conversion on chl 7
ADC1->RSQR1 = 0; ADC1->RSQR3 = CHANNEL; // 0-9 for 8 ext inputs and two internals Set to 7 for PA7
ADC1->RSQR2 = 0; ADC2->RSQR3 = CHANNEL; // 0-9 for 8 ext inputs and two internals Set to 7 for PA7
ADC1->RSQR3 = 7; // 0-9 for 8 ext inputs and two internals
ADC1->ISQR = CHANNEL; // Mirror in case we switch to injection mode.
ADC2->ISQR = CHANNEL;
// Not using injection group. // Not using injection group.
// Sampling time for channels. Careful: This has PID tuning implications. // Sampling time for channels. Careful: This has PID tuning implications.
// Note that with 3 and 3,the full loop (and injection) runs at 138kHz. // Note that with 3 and 3,the full loop (and injection) runs at 138kHz.
ADC1->SAMPTR2 = (0<<(3*7)); ADC1->SAMPTR2 = (SAMPLETIME<<(3*CHANNEL)); // (3*channel)
ADC2->SAMPTR2 = (SAMPLETIME<<(3*CHANNEL)); // (3*channel)
// Turn on ADC and set rule group to sw trig // Turn on ADC and set rule group to sw trig
// 0 = Use TRGO event for Timer 1 to fire ADC rule. // 0 = Use TRGO event for Timer 1 to fire ADC rule.
ADC1->CTLR2 = ADC_ADON | ADC_EXTTRIG | ADC_DMA; 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 // Reset calibration
ADC1->CTLR2 |= ADC_RSTCAL; ADC1->CTLR2 |= ADC_RSTCAL;
ADC2->CTLR2 |= ADC_RSTCAL;
while(ADC1->CTLR2 & ADC_RSTCAL); while(ADC1->CTLR2 & ADC_RSTCAL);
while(ADC2->CTLR2 & ADC_RSTCAL);
// Calibrate ADC // Calibrate ADC
ADC1->CTLR2 |= ADC_CAL; ADC1->CTLR2 |= ADC_CAL;
ADC2->CTLR2 |= ADC_CAL;
while(ADC1->CTLR2 & ADC_CAL); while(ADC1->CTLR2 & ADC_CAL);
while(ADC2->CTLR2 & ADC_CAL);
// ADC_SCAN: Allow scanning. // ADC_SCAN: Allow scanning.
ADC1->CTLR1 = ADC_Pga_64 | ADC_SCAN; 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 // Turn on DMA
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1; RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
@@ -202,32 +195,21 @@ void SetupADC()
//DMA1_Channel1 is for ADC //DMA1_Channel1 is for ADC
DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR; DMA1_Channel1->PADDR = (uint32_t)&ADC1->RDATAR;
DMA1_Channel1->MADDR = (uint32_t)adc_buffer; DMA1_Channel1->MADDR = (uint32_t)adc_buffer;
DMA1_Channel1->CNTR = ADC_BUFFSIZE; DMA1_Channel1->CNTR = ADC_BUFFSIZE/2;
DMA1_Channel1->CFGR = DMA1_Channel1->CFGR =
DMA_M2M_Disable | DMA_M2M_Disable |
DMA_Priority_VeryHigh | DMA_Priority_VeryHigh |
DMA_MemoryDataSize_HalfWord | DMA_MemoryDataSize_Word |
DMA_PeripheralDataSize_HalfWord | DMA_PeripheralDataSize_Word |
DMA_MemoryInc_Enable | DMA_MemoryInc_Enable |
DMA_Mode_Circular | DMA_Mode_Circular |
DMA_DIR_PeripheralSRC; DMA_DIR_PeripheralSRC;
// NVIC_SetPriority( DMA1_Channel1_IRQn, 0<<4 ); //We don't need to tweak priority.
NVIC_EnableIRQ( DMA1_Channel1_IRQn ); NVIC_EnableIRQ( DMA1_Channel1_IRQn );
DMA1_Channel1->CFGR |= DMA_CFGR1_EN | DMA_IT_TC | DMA_IT_HT; // Transmission Complete + Half Empty Interrupts. DMA1_Channel1->CFGR |= DMA_CFGR1_EN | DMA_IT_TC | DMA_IT_HT; // Transmission Complete + Half Empty Interrupts.
// Turn on DMA channel 1
DMA1_Channel1->CFGR |= DMA_CFGR1_EN;
// Enable continuous conversion and DMA // Enable continuous conversion and DMA
ADC1->CTLR2 |= ADC_DMA; // | ADC_CONT; ADC1->CTLR2 |= ADC_DMA; // | ADC_CONT;
// start conversion
ADC1->CTLR2 |= ADC_SWSTART;// | ADC_CONT;
} }
static void SetupTimer1() static void SetupTimer1()
@@ -251,18 +233,69 @@ static void SetupTimer1()
TIM1->BDTR |= 0xc000;//TIM_MOE; TIM1->BDTR |= 0xc000;//TIM_MOE;
#endif #endif
TIM1->CCER |= TIM_CC1E; TIM1->CCER |= TIM_CC1E | TIM_CC4E | TIM_CC3E;
TIM1->CHCTLR1 |= TIM_OC1M_2 | TIM_OC1M_1; TIM1->CHCTLR1 |= TIM_OC1M_2 | TIM_OC1M_1;
TIM1->CH1CVR = 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 (NOTE: Not on the 203! TIM1_TRGO is only connected to injection) // Setup TRGO to trigger for ADC injection group
//TIM1->CTLR2 = TIM_MMS_1; TIM1->CTLR2 = TIM_MMS_1;
// Enable TIM1 outputs // Enable TIM1 outputs
TIM1->BDTR = TIM_MOE; TIM1->BDTR = TIM_MOE;
TIM1->CTLR1 = TIM_CEN; 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)); void InnerLoop() __attribute__((noreturn));
@@ -309,7 +342,9 @@ void DMA1_Channel1_IRQHandler( void )
// Clear all possible flags. // Clear all possible flags.
DMA1->INTFCR = DMA1_IT_GL1; DMA1->INTFCR = DMA1_IT_GL1;
int tpl = ADC_BUFFSIZE - DMA1_Channel1->CNTR; // Warning, sometimes this is == to the base, or == 0 (i.e. might be 256, if top is 255) 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 += ADC_BUFFSIZE;
tpl = (tpl & (ADC_BUFFSIZE-1)); tpl = (tpl & (ADC_BUFFSIZE-1));
if( tpl == ADC_BUFFSIZE ) tpl = 0; if( tpl == ADC_BUFFSIZE ) tpl = 0;
@@ -328,6 +363,9 @@ void DMA1_Channel1_IRQHandler( void )
// Here is where the magic happens. // Here is where the magic happens.
#if 1 #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 XSTR(x) #x
#define GOERTZELLOOP(idx) \ #define GOERTZELLOOP(idx) \
asm volatile("\n\ asm volatile("\n\
@@ -384,24 +422,59 @@ void DMA1_Channel1_IRQHandler( void )
int32_t zp = g_goertzelp_store; int32_t zp = g_goertzelp_store;
int32_t zp2 = g_goertzelp2_store; int32_t zp2 = g_goertzelp2_store;
int32_t rr = (((int64_t)(g_goertzel_coefficient ) * (int64_t)zp<<1)>>32) - (zp2); 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); 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[qibaselogs_head] = ((uint16_t)rr) | (((uint16_t)ri)<<16);
qibaselogs_head = ( qibaselogs_head + 1 ) & ((LOG_GOERTZEL_LIST)-1); qibaselogs_head = ( qibaselogs_head + 1 ) & ((LOG_GOERTZEL_LIST)-1);
rr>>=2;
ri>>=2;
int s = rr * rr + ri * ri; int s = rr * rr + ri * ri;
//int intensity = 1<<( ( 32 - __builtin_clz(s) )/2); //int intensity = 1<<( ( 32 - __builtin_clz(s) )/2);
#define ABS(x) (((x)<0)?-(x):(x)) #define ABS(x) (((x)<0)?-(x):(x))
int intensity = (ABS(rr) + ABS(ri)) * 26100 / 32768; // Found experimentally (Also try to avoid divide-by-zero. int intensity = (ABS(rr) + ABS(ri)) * 26100 / 32768; // Found experimentally (Also try to avoid divide-by-zero.
if( intensity == 0 ) //if( intensity == 0 )
intensity = 1; // intensity = 1;
intensity++;
intensity = (intensity + s/intensity)/2; intensity = (intensity + s/intensity)/2;
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); 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 #ifdef PWM_OUTPUT
intensity = intensity * g_volume_pwm * g_pwm_period / (intensity_average>>(10-12)); intensity = intensity * g_volume_pwm * g_pwm_period / (intensity_average>>(10-12));
@@ -419,6 +492,18 @@ void DMA1_Channel1_IRQHandler( void )
adc_offset -= accumulate_over_window / g_goertzel_buffer; adc_offset -= accumulate_over_window / g_goertzel_buffer;
accumulate_over_window = 0; 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 #ifdef PROFILING_PIN
funDigitalWrite( PROFILING_PIN, 1 ); funDigitalWrite( PROFILING_PIN, 1 );
#endif #endif
@@ -451,77 +536,32 @@ static inline uint32_t gets2()
return ret; return ret;
} }
uint8_t i2c_send_buffer[16];
void InnerLoop() void setup_i2c_dma(void)
{ {
while(1){ // Turn on DMA
#if 0 RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
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
int pxa = 0; //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;
// Only display half of the list so the other half could DMA1_Channel6->CFGR |= DMA_CFGR1_EN;
// be updated by the ISR.
int glread = qibaselogs_head;
int intensity = 0; NVIC_DisableIRQ(I2C1_EV_IRQn);
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;
#ifdef ENABLE_OLED
ssd1306_drawPixel( rr, ri, 1 );
#endif
} }
#ifdef ENABLE_OLED
//char cts[32];
//snprintf( cts, 32, "%d", intensity_average );
//ssd1306_drawstr( 0, 0, cts, 1 );
ssd1306_refresh();
//static int ik = 0;
//printf( "%d %08x\n", ik, ssd1306_buffer[ik++] );
//if( ik == sizeof(ssd1306_buffer) ) ik = 0;
ssd1306_setbuf(0);
#else
Delay_Ms(17);
#endif
// printf( "%6d %8d %8d - %8d %8d - %8d\n", g_goertzel_outs,g_goertzelp2_store, g_goertzelp_store, rr, ri, x );
// Delay_Ms(940);
//printf( "!!!!\n ");
}
}
int main() int main()
{ {
@@ -563,7 +603,7 @@ int main()
SetupADC(); SetupADC();
#ifdef ENABLE_OLED #if defined( ENABLE_OLED )
ssd1306_i2c_setup(); ssd1306_i2c_setup();
ssd1306_i2c_init(); ssd1306_i2c_init();
@@ -576,32 +616,52 @@ int main()
ssd1306_refresh(); ssd1306_refresh();
#endif #endif
#if 0 #ifdef ENABLE_OLED_SCOPE
int i = 0; int i;
int k = 0;
int frame = 0; ssd1306_spi_init();
while( 1) ssd1306_rst();
{
// ssd1306_drawLine( (frame)%128, (0)%128, (0)%128, (127-frame)%128, 1 ); if( ssd1306_init() )
ssd1306_drawstr( frame%128, frame%128, "hello", 1 ); printf( "Failed to initialize OLED\n" );
else
printf( "Initialized OLED\n" );
ssd1306_refresh();
ssd1306_setbuf(0); ssd1306_setbuf(0);
frame++;
// 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 );
} }
while(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
#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 #endif
#ifdef PROFILING_PIN #ifdef PROFILING_PIN
@@ -613,7 +673,56 @@ int main()
USBOTGSetup(); USBOTGSetup();
InnerLoop(); 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);
}
} }
@@ -662,12 +771,19 @@ int HandleHidUserGetReportSetup( struct _USBState * ctx, tusb_control_request_t
int samps_to_send = (qibaselogs_head - last_baselog + LOG_GOERTZEL_LIST * 2 - 1) & (LOG_GOERTZEL_LIST-1); 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; if( samps_to_send > 120 ) samps_to_send = 120;
((uint32_t*)scratchpad)[0] = (intensity_average<<12) | samps_to_send; 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)[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)[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; int i;
for( i = 3; i < samps_to_send + 3; i++ ) for( i = 5; i < samps_to_send + 5; i++ )
{ {
last_baselog = (last_baselog+1)&(LOG_GOERTZEL_LIST-1); last_baselog = (last_baselog+1)&(LOG_GOERTZEL_LIST-1);
((uint32_t*)(scratchpad))[i] = ((int32_t*)qibaselogs)[last_baselog]; ((uint32_t*)(scratchpad))[i] = ((int32_t*)qibaselogs)[last_baselog];
@@ -702,7 +818,7 @@ void HandleHidUserReportOutComplete( struct _USBState * ctx )
uint32_t * configs = (uint32_t*)scratchpad; uint32_t * configs = (uint32_t*)scratchpad;
// Note: configs[0] == 0xac (command type) // Note: configs[0] == 0xac (command type)
printf( "Is Configure Packet %08x\n", configs[1] ); //printf( "Is Configure Packet %08x\n", configs[1] );
int numconfigs = configs[1]; int numconfigs = configs[1];
if( numconfigs > 0) g_pwm_period = configs[2]; if( numconfigs > 0) g_pwm_period = configs[2];
@@ -711,11 +827,35 @@ void HandleHidUserReportOutComplete( struct _USBState * ctx )
if( numconfigs > 3) g_goertzel_coefficient = configs[5]; if( numconfigs > 3) g_goertzel_coefficient = configs[5];
if( numconfigs > 4) g_goertzel_coefficient_s = configs[6]; if( numconfigs > 4) g_goertzel_coefficient_s = configs[6];
if( numconfigs > 5) g_exactcompute = configs[7]; 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. // Need to reset so we don't blast by.
g_goertzel_samples = 0; g_goertzel_samples = 0;
TIM1->ATRLR = g_pwm_period; TIM1->ATRLR = g_pwm_period;
TIM1->CH1CVR = 1;
TIM1->CH3CVR = TIM1->ATRLR/2+1;
g_isConfigurePacket = 0; g_isConfigurePacket = 0;
} }
return; return;
+7 -1
View File
@@ -1,4 +1,10 @@
all : test floattest 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 floattest : floattestt
./floattestt ./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);
}
}
}
@@ -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;
}
}
@@ -2,6 +2,7 @@ all : flash
TARGET:=loratest TARGET:=loratest
TARGET_MCU:=CH32V203 TARGET_MCU:=CH32V203
TARGET_MCU_PACKAGE:=C8
CH32V003FUN:=../ch32v003fun/ch32v003fun CH32V003FUN:=../ch32v003fun/ch32v003fun
EXTRA_ELF_DEPENDENCIES:=chirpbuff.h EXTRA_ELF_DEPENDENCIES:=chirpbuff.h
+13
View File
@@ -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
+51
View File
@@ -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 );
}
}
+9
View File
@@ -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.
+6
View File
@@ -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)
+305
View File
@@ -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%); }
}
+264 -45
View File
@@ -1,43 +1,104 @@
<!DOCTYPE html> <!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> <HTML>
<HEAD> <HEAD>
<LINK rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> <LINK rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<META charset="UTF-8"> <link rel="stylesheet" type="text/css" href="calculator.css" />
<STYLE> <META charset="UTF-8"/>
body { background-color: Canvas; color: CanvasText; }
:root { color-scheme: dark; }
</STYLE>
<SCRIPT src=webhidcontrol.js></SCRIPT> <SCRIPT src=webhidcontrol.js></SCRIPT>
<SCRIPT> <SCRIPT>
var darkmode = true;
//body { background-color: Canvas; color: CanvasText; }
function DrawSpan( rowspan, colspan, freq, target, docolor, extrastr = "" ) function DrawSpan( rowspan, colspan, freq, target, docolor, extrastr = "" )
{ {
var fdist = Math.abs( freq - target ); var fdist = Math.abs( freq - target );
fdist = Math.pow( fdist, 0.5 ) * 500; fdist = Math.pow( fdist, 0.5 ) * 300;
// if( fdist > 255 ) fdist = 255; if( fdist > 511 ) fdist = 511;
let ret = "<TD COLSPAN=" + colspan + ' ROWSPAN' + rowspan + ' '; let ret = "<TD COLSPAN=" + colspan + ' ROWSPAN' + rowspan + ' ';
if( docolor ) ret += 'STYLE="color:black;background-color:rgb(' + fdist + ',' + (511-fdist) + ',0)";';
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>"; ret += '>' + extrastr + freq.toFixed(6) + "</TD>";
return ret; return ret;
} }
function Goertz( n, mhz, fr, brf, exact_compute ) var system_rate = 288000000; // in MHz for effective ADC (note: This can be 2x normal clock if in dual ADC mode)
{ var lastGn;
let omega = fr * 3.1415926535*2.0; var lastGmhz;
var textarea = document.getElementById("goertzeloutput"); var lastGfr;
var lastGbrf;
var lastGexact;
var lastTargetMHz;
var g_goertzel_omega_per_sample = Math.round( ( omega*2*(1<<29)) ); 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 = Math.round( (2 * Math.cos( omega ) * (1<<30)) );
var g_goertzel_coefficient_s = Math.round( (2 * Math.sin( 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; var g_exactcompute = exact_compute;
if( textarea )
{
textarea.value = textarea.value =
"int g_pwm_period = ("+n+"-1);\n" + "int g_pwm_period = ("+n+"-1); // " + system_rate/lastGn/1000000. + " MHz Samplerate\n" +
"int g_exactcompute = ("+exact_compute+");\n" + "int g_exactcompute = ("+exact_compute+");\n" +
"int g_goertzel_buffer = ("+brf+");\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_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 = " + g_goertzel_coefficient.toFixed(0) + ";\n" +
"int32_t g_goertzel_coefficient_s = " + g_goertzel_coefficient_s.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 // Highlight its content
textarea.select(); textarea.select();
@@ -45,7 +106,105 @@ function Goertz( n, mhz, fr, brf, exact_compute )
// Copy the highlighted text // Copy the highlighted text
document.execCommand("copy"); 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 ] ); }
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() function computeTable()
@@ -57,7 +216,7 @@ function computeTable()
let goertzel2 = document.getElementById("GOERTZEL2").checked; let goertzel2 = document.getElementById("GOERTZEL2").checked;
let quanta = Math.round(Number(document.getElementById("quanta").value)); let quanta = Math.round(Number(document.getElementById("quanta").value));
let quantasearch = Math.round(Number(document.getElementById("quantasearch").value)); let quantasearch = Math.round(Number(document.getElementById("quantasearch").value));
SaveDefaults();
const max_harmonics = 28|0; const max_harmonics = 28|0;
const min_harmonics = (quadrature?1:0)|0; const min_harmonics = (quadrature?1:0)|0;
@@ -85,10 +244,10 @@ function computeTable()
else if( goertzels ) else if( goertzels )
{ {
contents += contents +=
"<TABLE BORDER=1>" + "<TABLE>" +
"<TR><TD>Goertzel</TD></TR>" + "<TR><TD>Goertzel</TD></TR>" +
"<TR><TD>Goertzel (Inverse)</TD></TR>" + "<TR><TD>Goertzel (Inverse)</TD></TR>" +
"</TABLE><TEXTAREA ROWS=6 COLS=120 ID=goertzeloutput></TEXTAREA>" + "</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>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>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>"; "<P>Goertzel's mode is for the ch32v203</P>";
@@ -96,6 +255,7 @@ function computeTable()
if( goertzels || quadrature ) if( goertzels || quadrature )
{ {
contents += "<BR>Scroll Wheel Control:<BR>";
contents += "<TABLE BORDER=1>"; contents += "<TABLE BORDER=1>";
contents += '<TR><TH>d\\h</div></TH>'; contents += '<TR><TH>d\\h</div></TH>';
for( let h = 0|min_harmonics; h <= max_harmonics; h++ ) for( let h = 0|min_harmonics; h <= max_harmonics; h++ )
@@ -169,7 +329,7 @@ function computeTable()
if( mode == 0 ) if( mode == 0 )
{ {
contents += "<TD COLSPAN=2>" contents += "<TD COLSPAN=2>"
if( tgoertzelp == h ) contents += "<SPAN ONCLICK='Goertz(" + n + ", " + freq * (h+goertzelpoint) + ", " + (goertzelpoint) + ", " + quantaA + ", 0)'>↑" + (goertzelpoint).toFixed(6) + "</SPAN>"; if( tgoertzelp == h ) contents += "<INPUT TYPE=SUBMIT ONCLICK='Goertz(" + n + ", " + freq * (h+goertzelpoint) + ", " + (goertzelpoint) + ", " + quantaA + ", 0, " + freq + ")' VALUE='↑" + (goertzelpoint).toFixed(6) + "'/>";
contents += "</TD>"; contents += "</TD>";
} }
else if( mode == 1 ) else if( mode == 1 )
@@ -179,7 +339,7 @@ function computeTable()
else if( mode == 2 ) else if( mode == 2 )
{ {
contents += "<TD COLSPAN=2>" contents += "<TD COLSPAN=2>"
if( tgoertzelpi == h-1 ) contents += "<SPAN ONCLICK='Goertz(" + n + ", " + freq * (h-goertzelpointinv) + ", " + goertzelpointinv + ", " + quantaINV + ", 0)'>↓" + goertzelpointinv.toFixed(6) + "</SPAN>"; if( tgoertzelpi == h-1 ) contents += "<INPUT TYPE=SUBMIT ONCLICK='Goertz(" + n + ", " + freq * (h-goertzelpointinv) + ", " + goertzelpointinv + ", " + quantaINV + ", 0, " + freq + ")' VALUE='↓" + goertzelpointinv.toFixed(6) + "'/>";
contents += "</TD>"; contents += "</TD>";
} }
else if( mode == 3 ) else if( mode == 3 )
@@ -195,15 +355,30 @@ function computeTable()
} }
else if( goertzel2 ) else if( goertzel2 )
{ {
contents += "</TABLE><TEXTAREA ROWS=6 COLS=120 ID=goertzeloutput></TEXTAREA><BR>"; contents += "</TABLE>";
contents += "<TABLE BORDER=1>"; 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>'; contents += '<TR><TH>d\\h</div></TH>';
for( let h = 0|min_harmonics; h <= max_harmonics+1; h++ ) for( let h = 0|min_harmonics; h <= max_harmonics+1; h++ )
{ {
contents += "<TH COLSPAN=1>" + h + "</TH>"; contents += "<TH COLSPAN=1>" + h + "</TH>";
} }
for( let n = 0|28; n <= 96; n++ ) for( let n = 0|42; n <= 96; n+=2 )
{ {
let freq = ( xtal / n ); let freq = ( xtal / n );
let goertzelpoint = 0; let goertzelpoint = 0;
@@ -233,7 +408,7 @@ function computeTable()
if( rid == 0 ) if( rid == 0 )
{ {
contents += "<TD COLSPAN=1 ROWSPAN=2>" contents += "<TD COLSPAN=1 ROWSPAN=2>"
contents += "<SPAN ONCLICK='Goertz(" + n + ", " + freq * (h+tgoertzelpoint) + ", " + (tgoertzelpoint) + ", " + quantaA + ", 1)'>↑" + n + "</SPAN>"; contents += "<INPUT TYPE=SUBMIT ONCLICK='Goertz(" + n + ", " + freq * (h+tgoertzelpoint) + ", " + (tgoertzelpoint) + ", " + quantaA + ", 1, " + target + " )' VALUE='↑" + n + "'/>";
contents += "</TD>" contents += "</TD>"
} }
} }
@@ -257,45 +432,79 @@ function computeTable()
contents += "</TABLE>"; contents += "</TABLE>";
} }
document.getElementById( "TABLE" ).innerHTML = contents; 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() function onLoad()
{ {
LoadDefaults();
onLoadWebHidControl(); onLoadWebHidControl();
} }
</SCRIPT> </SCRIPT>
</HEAD> </HEAD>
<BODY onLoad="onLoad()"> <BODY onLoad="onLoad()">
<TABLE WIDTH=100%> <TABLE WIDTH=100%>
<TR> <TR>
<TD COLSPAN=3> <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> <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>
<TD ROWSPAN=2 VALIGN=TOP WIDTH=100% ID=LiveGraphContainer> <TD ROWSPAN=2 VALIGN=TOP HEIGHT=200 WIDTH=100% ID=LiveGraphContainer>
<CANVAS WIDTH=100% HEIGHT=200 ID=LiveGraph> </CANVAS> <CANVAS WIDTH=100% HEIGHT=200 ID=LiveGraph> </CANVAS>
</TD> </TD>
</TR> </TR>
<TR> <TR>
<TD VALIGN=TOP> <TD VALIGN=TOP ROWSPAN=2>
<TABLE WIDTH=480> <TABLE WIDTH=380>
<TR><TD>Crystal MHz</TD><TD><INPUT ID=crystalmhz VALUE=144></TD></TR> <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>Target MHz</TD><TD><INPUT ID=targetmhz VALUE=27.019360></TD></TR>
<TR><TD>Quanta</TD><TD><INPUT ID=quanta VALUE=1024> (Goertzel's Only)</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> (Goertzel's Only)</TD></TR> <TR><TD>Quanta Search Range</TD><TD><INPUT ID=quantasearch VALUE=64></TD></TR>
<TR><TD>Table Type</TD><TD> <TR><TD>Table Type</TD><TD>
<INPUT TYPE=RADIO ID=QUADRATURE NAME=computetype>Quadrature</INPUT> <INPUT TYPE=RADIO ID=QUADRATURE NAME=computetype>Quadrature</INPUT><br>
<INPUT TYPE=RADIO ID=GOERTZELS NAME=computetype>Goertzels</INPUT> <INPUT TYPE=RADIO ID=GOERTZELS NAME=computetype>Goertzels</INPUT><br>
<INPUT TYPE=RADIO ID=GOERTZEL2 NAME=computetype checked>Goertzel (unalign)</INPUT> <INPUT TYPE=RADIO ID=GOERTZEL2 NAME=computetype checked>Goertzel (unalign)</INPUT>
</TD></TR> </TD></TR>
<TR><TD COLSPAN=2><INPUT TYPE=SUBMIT VALUE="Compute" ONCLICK="computeTable()"></TD></TR> <TR><TD COLSPAN=2><INPUT TYPE=SUBMIT VALUE="Compute" ONCLICK="computeTable()"></TD></TR>
</TABLE> </TABLE>
</TD> </TD>
<TD VALIGN=TOP> <TD VALIGN=TOP ROWSPAN=2>
Live Control:<br>
Live Control:
<TABLE><TR> <TABLE><TR>
<TD><INPUT TYPE=SUBMIT onClick="reqConnect()" VALUE="Open Device" ID=connectButton> <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="toggleAudio()" VALUE="Play Audio" ID="ToggleAudioButton">
@@ -304,12 +513,22 @@ Live Control:
</TR></TABLE> </TR></TABLE>
<DIV ID="StatusPerf"></DIV> <DIV ID="StatusPerf"></DIV>
</TD> </TD>
<TD>
</TD> </TD>
</TR> </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> </TABLE>
<DIV ID=TABLE></DIV>
</BODY> </BODY>
</HTML> </HTML>
+104 -19
View File
@@ -1,3 +1,15 @@
/* 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 expectedProductName = "CNLohr lolra ch32v203 goertzel test";
const filter = { vendorId : 0x1209, productId : 0xd035 }; const filter = { vendorId : 0x1209, productId : 0xd035 };
let dev = null; let dev = null;
@@ -11,7 +23,7 @@ var lastIntensity = 1.0;
var lastNumQ = 0; var lastNumQ = 0;
var lastTotalTime = 1; var lastTotalTime = 1;
var lastTimeUsed = 1; var lastTimeUsed = 1;
var didSetupGeneralData = false;
var graphIsClicked = false; var graphIsClicked = false;
function graphClick( e ) function graphClick( e )
@@ -57,6 +69,7 @@ async function closeDeviceTool()
{ {
loopAbort = false; loopAbort = false;
setStatusError( "Disconnected" ); setStatusError( "Disconnected" );
dev = null;
} }
var playingAudioProcessor = null; var playingAudioProcessor = null;
@@ -109,7 +122,7 @@ async function toggleAudio()
if( n == this.rbuffertail ) \ if( n == this.rbuffertail ) \
{ \ { \
this.rbuffertail = (this.rbuffertail + (1|0))%(8192|0); \ this.rbuffertail = (this.rbuffertail + (1|0))%(8192|0); \
console.log( `Overflow` ); \ /*console.log( `Overflow` ); */ \
} \ } \
var vv = e.data[i]; \ var vv = e.data[i]; \
this.dcoffset = this.dcoffset * 0.995 + vv * 0.005; \ this.dcoffset = this.dcoffset * 0.995 + vv * 0.005; \
@@ -127,7 +140,7 @@ async function toggleAudio()
var s = Math.fround( this.sampleplace ); /*float*/ \ var s = Math.fround( this.sampleplace ); /*float*/ \
var tail = this.rbuffertail | 0; /* int*/ \ var tail = this.rbuffertail | 0; /* int*/ \
var tailnext = this.rbuffertail | 0; /* int*/ \ var tailnext = this.rbuffertail | 0; /* int*/ \
if( tail == this.rbufferhead ) { console.log( "Underflow " ); return true; }\ if( tail == this.rbufferhead ) { /*console.log( "Underflow " );*/ return true; }\
var tsamp = Math.fround( this.rbuffer[tail] ); \ var tsamp = Math.fround( this.rbuffer[tail] ); \
var nsamp = Math.fround( this.rbuffer[tailnext] ); \ var nsamp = Math.fround( this.rbuffer[tailnext] ); \
this.totalsampcount += len|0; \ this.totalsampcount += len|0; \
@@ -139,7 +152,7 @@ async function toggleAudio()
s -= excess; \ s -= excess; \
tail = ( tail + (excess|0) ) % (8192|0); \ tail = ( tail + (excess|0) ) % (8192|0); \
tailnext = ( tail + (1|0) ) % (8192|0); \ tailnext = ( tail + (1|0) ) % (8192|0); \
if( tail == this.rbufferhead ) { console.log( "Underflow" ); break; } \ if( tail == this.rbufferhead ) { /* console.log( "Underflow" ); */ break; } \
tsamp = Math.fround( this.rbuffer[tail] ); \ tsamp = Math.fround( this.rbuffer[tail] ); \
nsamp = Math.fround( this.rbuffer[tailnext] ); \ nsamp = Math.fround( this.rbuffer[tailnext] ); \
} \ } \
@@ -186,7 +199,7 @@ async function toggleAudio()
gainParam.setValueAtTime( 0, audioContext.currentTime ); gainParam.setValueAtTime( 0, audioContext.currentTime );
} }
var newVal = 0.1 - targetGain; var newVal = 1.0 - targetGain;
console.log( "Setting gain to: " + newVal ); console.log( "Setting gain to: " + newVal );
let gainParam = playingAudioProcessor.parameters.get("gain"); let gainParam = playingAudioProcessor.parameters.get("gain");
gainParam.setValueAtTime( newVal, audioContext.currentTime); gainParam.setValueAtTime( newVal, audioContext.currentTime);
@@ -267,6 +280,7 @@ let receiveReport = null;
async function sendLoopError( e ) async function sendLoopError( e )
{ {
console.log( "SEND LOOP ERROR" );
sendReport = null; sendReport = null;
receiveReport = null; receiveReport = null;
if( dev ) await dev.close(); if( dev ) await dev.close();
@@ -295,6 +309,50 @@ FMiirphase = 0.0; /* for FM */
FMlastphase = 0.0; /* for FM */ FMlastphase = 0.0; /* for FM */
FMphaseout = 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() async function sendLoop()
{ {
@@ -308,7 +366,7 @@ async function sendLoop()
while( true ) while( true )
{ {
if( dev && !loopAbort ) if( dev && dev !== null && !loopAbort )
{ {
receiveReport = dev.receiveFeatureReport( 0xAD ).catch( sendLoopError ); receiveReport = dev.receiveFeatureReport( 0xAD ).catch( sendLoopError );
if( !receiveReport ) sendLoopError( "error creating receiveReport" ); if( !receiveReport ) sendLoopError( "error creating receiveReport" );
@@ -326,9 +384,31 @@ async function sendLoop()
xActionSecAvg = xActionSecAvg * 0.9 + xActionSec * 0.1; xActionSecAvg = xActionSecAvg * 0.9 + xActionSec * 0.1;
document.getElementById( "StatusPerf" ).innerHTML = document.getElementById( "StatusPerf" ).innerHTML =
(kBsecAvg).toFixed(2) + " kBytes/s<br>" + (kBsecAvg).toFixed(2) + " kB/s<br>" +
(xActionSecAvg).toFixed(2) + "transactions/sec<br>" + (xActionSecAvg).toFixed(2) + "x/s<br>";
"Count: " + goodCount + " / " + badCount;
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; lastTime = thisTime;
} }
else if( frameNo % updateStatsPerfPer == 2 ) else if( frameNo % updateStatsPerfPer == 2 )
@@ -343,19 +423,20 @@ async function sendLoop()
ctx.clearRect(0, 0, liveGraph.width, liveGraph.height); 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; var filledness = lastNumQ * 198 / 120;
ctx.fillStyle = "rgb( 240 240 240 )"; ctx.fillStyle = grey;
ctx.fillRect( 2, 2 + 198 - filledness, 18, filledness - 2); ctx.fillRect( 2, 2 + 198 - filledness, 18, filledness - 2);
filledness = ( lastTimeUsed * 1.0 / lastTotalTime ) * 198; filledness = ( lastTimeUsed * 1.0 / lastTotalTime ) * 198;
ctx.fillStyle = "rgb( 240 240 240 )"; ctx.fillStyle = grey;
ctx.fillRect( 26, 2 + 198 - filledness, 18, filledness - 2 ); ctx.fillRect( 26, 2 + 198 - filledness, 18, filledness - 2 );
ctx.fillStyle = `rgb( 255 255 255 )`; ctx.fillStyle = mark;
let mulcoeff = 10000.0 / lastIntensity;
let mulcoeff = 2500.0 / lastIntensity;
var lot = 1.2; var lot = 1.2;
var x = 253; var x = 253;
for( var i = (IQHistoryHead-1) & (IQHistoryLen-1); i != IQHistoryHead|0; i = (i - 1 + IQHistoryLen) & (IQHistoryLen-1) ) for( var i = (IQHistoryHead-1) & (IQHistoryLen-1); i != IQHistoryHead|0; i = (i - 1 + IQHistoryLen) & (IQHistoryLen-1) )
@@ -403,17 +484,21 @@ async function sendLoop()
let receiveData = await receiveReport; let receiveData = await receiveReport;
if( receiveData && receiveData.buffer ) if( receiveData && receiveData.buffer )
{ {
// Receive data from USB (from HandleHidUserGetReportSetup)
let data = new Uint32Array( receiveData.buffer.slice( 0, 508 ) ); let data = new Uint32Array( receiveData.buffer.slice( 0, 508 ) );
let intensity = data[0]>>8; let intensity = data[0]>>8;
let numq = data[0] & 0xff; let numq = data[0] & 0xff;
let time_total = data[1]>>16; let time_total = data[1]>>16;
let time_used = data[1]&0xffff; let time_used = data[1]&0xffff;
let sample_divisor = data[2]&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 demodbuffer = new Float32Array(numq);
let mulcoeff = 100.0 / lastIntensity; let mulcoeff = 16.0 / lastIntensity;
for( var i = 0|0; i < numq; i++ ) for( var i = 0|0; i < numq; i++ )
{ {
let vv = IQHistoryArray[IQHistoryHead] = data[i+3]; let vv = IQHistoryArray[IQHistoryHead] = data[i+5];
let vi = vv >> 16; let vi = vv >> 16;
let vq = vv & 0xffff; let vq = vv & 0xffff;
if( vi >= 32768 ) vi = vi-65535; if( vi >= 32768 ) vi = vi-65535;
@@ -439,7 +524,7 @@ async function sendLoop()
var po = FMphaseout = FMphaseout * 0.993 + diffphase; var po = FMphaseout = FMphaseout * 0.993 + diffphase;
if( po < 0.0 ) po += 1.0; if( po < 0.0 ) po += 1.0;
if( po > 1.0 ) po -= 1.0; if( po > 1.0 ) po -= 1.0;
demodbuffer[i] = po; demodbuffer[i] = po * .3; // Turn down FM it's really loud.
} }
IQHistoryHead = (IQHistoryHead+1)%IQHistoryLen; IQHistoryHead = (IQHistoryHead+1)%IQHistoryLen;
@@ -451,8 +536,7 @@ async function sendLoop()
if( audioContext != null && playingAudioProcessor != null ) if( audioContext != null && playingAudioProcessor != null )
{ {
// TODO: Use crystalmhz let sampleAdvance = (system_rate/sample_divisor) / audioContext.sampleRate;
let sampleAdvance = (144000000.0/sample_divisor) / audioContext.sampleRate;
let sampleAdvanceParam = playingAudioProcessor.parameters.get("sampleAdvance"); let sampleAdvanceParam = playingAudioProcessor.parameters.get("sampleAdvance");
sampleAdvanceParam.setValueAtTime( sampleAdvance, audioContext.currentTime); sampleAdvanceParam.setValueAtTime( sampleAdvance, audioContext.currentTime);
playingAudioProcessor.port.postMessage( demodbuffer ); playingAudioProcessor.port.postMessage( demodbuffer );
@@ -494,5 +578,6 @@ async function sendLoop()
} }
} }
} }
console.log( "ABORT\n" );
} }
+2
View File
@@ -0,0 +1,2 @@
.vscode
build
+23
View File
@@ -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 "" )
+378
View File
@@ -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,
};
+94
View File
@@ -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();
}
+7
View File
@@ -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,
1 # Name, Type, SubType, Offset, Size, Flags
2 # Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
3 # Note: if you change the size of the nvs partition, make sure to update NVS_PARTITION_SIZE in `components/hdw-nvs/nvs_manager.h`
4 nvs, data, nvs, 0x9000, 0x6000,
5 phy_init, data, phy, 0xf000, 0x1000,
6 factory, app, factory, 0x10000, 1M,
7 storage, data, spiffs, , 0xF0000,
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
all : genericgen
genericgen : genericgen.c
gcc -g -o $@ $^
clean :
rm -rf genericgen
+361
View File
@@ -0,0 +1,361 @@
/**
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.
**/
// Designed for generating chirp buffer to mimic hackaday badge... The idea is
// you can feed this data you want to send... and it feeds you a generic
// language of quarter chirps telling you when to up or down chirp.
//
// If the output value is negative, you need to emit a down-chirp. If it is
// positive, you output an up-chirp.
//
// Down chirps are represented in one's compliment.
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "../lib/LoRa-SDR-Code.h"
// Optionally send LoRaWAN messages. Be sure to copy your keys from the things network.
//#define LORAWAN
#define HACKADAY
#ifdef LORAWAN
#include "lorawan_simple.h"
static const uint8_t payload_key[AES_BLOCKLEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // AppSKey Big Endian
static const uint8_t network_skey[AES_BLOCKLEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // NwkSKey Big Endian
static const uint8_t devaddress[4] = { 0x00, 0x00, 0x00, 0x00 }; // Device address Little Endian LSB (Written backwards from Device address default view)
#endif
#ifdef HACKADAY
#define SF_NUMBER 7
#define CHIRPLENGTH_WORDS 128
#endif
#if !defined( LORAWAN ) && !defined( HACKADAY )
#error Need to define LORWAN or HACKADAY
#endif
// Bits are shifted out MSBit first, then to LSBit
#define MAX_BYTES 160
#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 16
#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;
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;
}
int main()
{
#if 0
SystemInit();
funGpioInitAll();
// Force HCLK to be nodiv. ch32vfun sets it to be a reasonbly high div.
RCC->CFGR0 &= ~RCC_PPRE1_DIV16;
// MCO for testing.
// funPinMode( PA8, GPIO_CFGLR_OUT_50Mhz_AF_PP ); RCC->CFGR0 |= RCC_CFGR0_MCO_PLL;
printf( "Switching to HSE\n" );
Delay_Ms( 100 );
// Disable clock security system.
RCC->CTLR &= ~RCC_CSSON;
#ifdef USE_EXTERNAL_CLOCK
// No crystal - use clock.
RCC->CTLR |= RCC_HSEBYP;
#endif
// Enable external crystal
RCC->CTLR |= RCC_HSEON;
// Set System Clock Source to be 0.
RCC->CFGR0 = (RCC->CFGR0 & ~RCC_SW) | 0;
// Disable PLL
RCC->CTLR &= ~RCC_PLLON;
#ifdef USE_EXTERNAL_CLOCK
// Set PLL to 9x not 18x
RCC->CFGR0 = ( RCC->CFGR0 & ~RCC_PLLMULL18 ) | RCC_PLLMULL9;
#endif
// 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 );
// funPinMode( PB12, GPIO_CFGLR_OUT_50Mhz_AF_PP ); // NSS
// funPinMode( PB13, GPIO_CFGLR_OUT_50Mhz_AF_PP ); // SCK
// funPinMode( PB14, GPIO_CFGLR_OUT_50Mhz_AF_PP ); // MISO
funPinMode( PB15, GPIO_CFGLR_OUT_50Mhz_AF_PP ); // MOSI
RCC->APB1PRSTR = RCC_SPI2RST;
RCC->APB1PRSTR = 0;
RCC->APB1PCENR |= RCC_APB1Periph_SPI2;
RCC->AHBPCENR |= RCC_AHBPeriph_DMA1;
// Configure SPI
SPI2->CTLR1 =
SPI_NSS_Soft | SPI_CPHA_1Edge | SPI_CPOL_Low | SPI_DataSize_16b |
SPI_Mode_Master | SPI_Direction_1Line_Tx |
0 |
0<<3; // Divisior = 0
// If using DMA may need this.
SPI2->CTLR2 = SPI_CTLR2_TXDMAEN;
SPI2->HSCR = 1; // High-speed enable.
SPI2->CTLR1 |= CTLR1_SPE_Set;
//SPI2->DATAR = 0x55aa; // Set SPI line Low.
//DMA1_Channel5 is for SPI2TX
DMA1_Channel5->PADDR = (uint32_t)&SPI2->DATAR;
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_MemoryDataSize_HalfWord |
DMA_PeripheralDataSize_HalfWord |
DMA_MemoryInc_Enable |
DMA_Mode_Normal | // OR DMA_Mode_Circular or DMA_Mode_Normal
DMA_DIR_PeripheralDST |
DMA_IT_TC | DMA_IT_HT; // Transmission Complete + Half Empty Interrupts.
NVIC_EnableIRQ( DMA1_Channel5_IRQn );
DMA1_Channel5->CFGR |= DMA_CFGR1_EN;
memset( sendbuff, 0x00, sizeof( sendbuff ) );
// Enter critical section.
DMA1_Channel5->CNTR = 0;
DMA1_Channel5->MADDR = (uint32_t)sendbuff;
DMA1_Channel5->CNTR = SENDBUFF_WORDS; // Number of unique uint16_t entries.
DMA1_Channel5->CFGR |= DMA_Mode_Circular;
#endif
uint16_t lora_symbols[MAX_SYMBOLS];
int lora_symbols_count;
//while(1)
{
//Delay_Ms( 1000 );
#ifdef LORAWAN
//Delay_Ms( 1000 );
static uint32_t frame = 0;
// Send a message with LoraWan. Formatted specifically for thethings.network.
uint8_t inner_payload_raw[24];
int inner_payload_len = snprintf( (char*)inner_payload_raw, 24, "meow%lu ", frame%10 );
inner_payload_len = 5;
// Just some random data.
uint8_t raw_payload_with_b0[259+8] = { };
uint8_t * payload_in = raw_payload_with_b0 + 16;
uint8_t * pl = payload_in;
int payload_in_size = 0;
pl += GenerateLoRaWANPacket( raw_payload_with_b0, inner_payload_raw, inner_payload_len, payload_key, network_skey, devaddress, frame++);
payload_in_size = pl - payload_in;
lora_symbols_count = 0;
#else
// Just some random data.
uint8_t payload_in[128] = {
0x07, 0xe9, 0x23, 0xee, 0x03, 0x80, 0xff, 0xff, 0xff, 0xff, 0x16, 0xca,
0x51, 0xd0, 0x06, 0x00, 0x02, 0x59, 0x6c, 0x6f, 0x6c, 0x72, 0x61, 0x00,
0x00, 0x00, 0x00, 0x00, 0x61, 0x61, 0x61, 0x61, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
int payload_in_size = sizeof(payload_in);
static int msgno = 0;
payload_in[4] = msgno++;
#endif
lora_symbols_count = 0;
// int r = CreateMessageFromPayload( lora_symbols, &lora_symbols_count, MAX_SYMBOLS, SF_NUMBER, 4, payload_in, payload_in_size );
// I think the Hackaday swadge uses 5/4, not 8/4
int r = CreateMessageFromPayload( lora_symbols, &lora_symbols_count, MAX_SYMBOLS, SF_NUMBER, 1, payload_in, payload_in_size );
if( r < 0 )
{
printf( "Failed to generate message (%d)\n", r );
// Failed
return -1;
}
int j;
quadsetcount = 0;
int16_t * qso = quadsets;
for( j = 0; j < PREAMBLE_CHIRPS; j++ )
{
qso = AddChirp( qso, 0, 0 );
}
// Hackaday Syncword.
uint8_t syncword = 0x21;
#define CODEWORD_SHIFT 3
if( CODEWORD_LENGTH > 0 )
qso = AddChirp( qso, ( ( syncword & 0xf ) << CODEWORD_SHIFT ), 0 );
if( CODEWORD_LENGTH > 1 )
qso = AddChirp( qso, ( ( ( syncword & 0xf0 ) >> 4 ) << CODEWORD_SHIFT ), 0);
*(qso++) = -(CHIPSSPREAD * 0 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 1 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 2 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 3 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 0 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 1 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 2 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 3 / 4 )-1;
*(qso++) = -(CHIPSSPREAD * 0 / 4 )-1;
if( SF_NUMBER <= 6 )
{
// Two additional upchirps with SF6 https://github.com/tapparelj/gr-lora_sdr/issues/74#issuecomment-1891569580
for( j = 0; j < 2; j++ )
qso = AddChirp( qso, 0, 0 );
}
for( j = 0; j < lora_symbols_count; j++ )
{
int ofs = lora_symbols[j];
//ofs = ofs ^ ((MARK_FROM_SF6<<6) -1);
//ofs &= (MARK_FROM_SF6<<6) -1;
qso = AddChirp( qso, ofs, 0 );
//printf( "0x%03x, ", ofs );
}
printf( "\n" );
printf( "const int16_t quadstarts[%ld] = {", qso - quadsets );
for (j = 0; j < qso - quadsets; j++ )
{
if( ( j & 0xf ) == 0 ) printf( "\n\t" );
printf( "%4d, ", quadsets[j] );
}
printf( "};\n" );
//int16_t * qso = quadsets
runningcount_bits = 0;
// This tells the interrupt we have data.
quadsetcount = qso - quadsets + 0;
printf( "--- %d [%d] %d\n", (int)lora_symbols_count, (int)quadsetcount, CHIPSSPREAD/4 );
quadsetplace = 0;
}
}
+5 -6
View File
@@ -223,7 +223,6 @@ blocks:
alias: '' alias: ''
comment: '' comment: ''
en_uvec: 'True' en_uvec: 'True'
log_level: info
states: states:
bus_sink: false bus_sink: false
bus_source: false bus_source: false
@@ -467,7 +466,7 @@ blocks:
ant8: '' ant8: ''
ant9: '' ant9: ''
args: '"airspy=0"' args: '"airspy=0"'
bb_gain0: '10' bb_gain0: '25'
bb_gain1: '20' bb_gain1: '20'
bb_gain10: '20' bb_gain10: '20'
bb_gain11: '20' bb_gain11: '20'
@@ -604,7 +603,7 @@ blocks:
dc_offset_mode7: '0' dc_offset_mode7: '0'
dc_offset_mode8: '0' dc_offset_mode8: '0'
dc_offset_mode9: '0' dc_offset_mode9: '0'
freq0: '1090000000' freq0: '100000000'
freq1: 100e6 freq1: 100e6
freq10: 100e6 freq10: 100e6
freq11: 100e6 freq11: 100e6
@@ -636,7 +635,7 @@ blocks:
freq7: 100e6 freq7: 100e6
freq8: 100e6 freq8: 100e6
freq9: 100e6 freq9: 100e6
gain0: '10' gain0: '25'
gain1: '10' gain1: '10'
gain10: '10' gain10: '10'
gain11: '10' gain11: '10'
@@ -700,7 +699,7 @@ blocks:
gain_mode7: 'False' gain_mode7: 'False'
gain_mode8: 'False' gain_mode8: 'False'
gain_mode9: 'False' gain_mode9: 'False'
if_gain0: '10' if_gain0: '25'
if_gain1: '20' if_gain1: '20'
if_gain10: '20' if_gain10: '20'
if_gain11: '20' if_gain11: '20'
@@ -1282,4 +1281,4 @@ connections:
metadata: metadata:
file_format: 1 file_format: 1
grc_version: 3.10.7.0