Compare commits

..

25 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 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
26 changed files with 1105 additions and 127 deletions
+135 -79
View File
@@ -1,25 +1,73 @@
# LoLRa
*Transmit 900MHz LoRa frames surprisingly far without a radio*
Transmit 900MHz LoRa frames surprisingly far without a radio (And other radio shenanigans using ADCs, PWMs and I2S/SPI busses) including sending other RF data, as well as receiving RF signals (Though admittedly not a LoRa receiver).
* [Introduction](#introduction)
* [Background](#background)
* [LoRaWAN](#lorawan)
* [Limitations](#limitations)
* [Future Work](#future_Work)
* [Resources](#resources)
* [Special Thanks](#special_thanks)
* [Range Tests](#range_tests)
If you are looking for the Hackaday 2024 microcontroller radio talk, you can <a href=https://cnlohr.github.io/lolra_talk>click here</a>.
## Introduction
If you are looking for LoLRa Merch (Like t-shirts, etc.), <a href="https://cnlohr-shop.fourthwall.com/">click here</a>.
Firmware-only LoRa transmission, for a variety of processors. Send LoRa packets, without any radio, chips, external hardware or built-in radios at all on a variety of common, inexpensive processors. While not truly bit banging, this repository shows how using either a shift register (i.e. I2S or SPI port) or an APLL, you can send lora packets that can be decoded by commercial off the shelf LoRa gateways and other chips.
* [Introduct and repo overview](#introduction-and-repo-overview)
* LoRa
* [Introduction (LoRa)](#introduction-lora)
* [Background](#background)
* [LoRaWAN](#lorawan)
* [Limitations](#limitations)
* [Future Work](#future-work)
* [Resources](#resources)
* [Special Thanks](#special-thanks)
* [Range Tests](#range-tests)
> [!NOTE]
> This repo is designed for use with ITU Region 2 (The Americas) tageting 902-928MHz. Code changes are needed for use in Region 1 (EU, Russia, Afraica) to target 863-870MHz or 3 (Australia, China, India) to target 920-923MHz.
> 1. Portions of code in this repo are under various licenses and cannot be trivially incorporated into other libraries, including some files containing a no-ai-training license for any of the RF-specific portions of the project. Be cautious when using code from this repo. See ![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]
> Because we rely on harmdonics and aliasing, the primary frequency components emitted by your microcontroller are going to be in portions of the RF spectrum where RF transmissions are banned. Please filter your output or perform your tests in an area where you are unlikely to leak significant RF. The overall EIRP output is genreally ≪300uW across the whole spectrum spread out over hundreds of emission frequencies, but there is virtually no way a device deliberately transmitting on these frequencies could ever pass FCC part 15 compliance, even with filtering.
> Because we rely on harmonics and aliasing, the primary frequency components emitted by your microcontroller are going to be in portions of the RF spectrum where RF transmissions are banned. Please filter your output or perform your tests in an area where you are unlikely to leak significant RF. The overall EIRP output is genreally ≪300uW across the whole spectrum spread out over hundreds of emission frequencies, but there is virtually no way a device deliberately transmitting on these frequencies could ever pass FCC part 15 compliance, even with filtering.
## Introduction and Repo Overview
I have always been fascinated with sending and receiving radio signals from microcontrollers that don't have dedicated radio hardware. This repo serves as a overview of many of the projects I've done to do this decoding, along with example code (Though some of it is restrictively licensed)
In general the repo is split up in to many projects, but categoriezed by device type.
* ch32v (Note, all examples require 8MHz (v203) or 24Mhz (v003) crystal oscillator)
* General Note: All OLED displays used here are 128x128 SPI-mode OLED displays.
* [ch32v003-adcrx](ch32v/ch32v003-adcrx) - prints quadrature values for receiving at 1/4 sample rate signals, or harmonics thereof. Specifically this is tuned to receiv CW on citizen band frequencies, specifically 27.000050 MHz
* [ch32v003-lora](ch32v/ch32v003-lora) - Successful (but very poor) transmission of LoRa messages with a ch32v003.
* [ch32v003-timer](ch32v/ch32v003-timer) - An attempt to use non-tabled dithering of PWM signals to send FM radio and/or 315MHz signals. *This does not work well* but it is included as a reference for dtrying to dither RF on the 003.
* [ch32v003-txrx](ch32v/ch32v003-txrx) - Trying to send from one 003 to another 003 receiving. This does not work well - only about 1'.
* [ch32v203-adcrx](ch32v203-adcrx) - Very basic quadrature decoding on a ch32v203.
* [ch32v203-fft](ch32v203-fft) - Perform an FFT on a small window of samples on a ch32v203. This outputs to an OLED display. It doesn't keep up in realtime though. It also relies on <a href=https://gist.github.com/cnlohr/c4f9647a220781c005ff1a733dc9ed7f>fix_fft.h</a> (which cannot be distirbuted with this project because of a lack of license.
* [**ch32v203-goertzel**](ch32v/ch32v203-goertzel) - Perform a full goertzel's tuning on an incoming ADC signal so that it can listen to multiple AM and NBFM radio stations from an ADC pin.
* [lib/calculator.html](ch32v/lib/calculator.html) - webpage that can use webhid with ch32v203-goertzel.
* [**ch32v203-lora**](ch32v/ch32v203-lora) - Proper transmission of LoRaWAN packets (from the tests outlined below).
* [ch32v203-tx](ch32v/ch32v203-tx) - Very basic test, setup to just turn on a PWM on the ch32v203.
* esp32-s2
* [**loratest**](esp32-s2/loratest) - Full stack protocol for sending LoRa messages from an esp32-s2. (From range test)
* [**narrow_fsk_test**](esp32-s2/narrow_fsk_test) - Very basic test using dithering and the PLL in the esp32-s2 to see how tight/narrow control is possible with the esp32-s2. This does not do a dithered closed loop, but would not be terribly hard to add.
* [**videoending**](esp32-s2/videoending) - Mechanism for allowing an ESP32-S2 to FSK, hopping around to draw a picture in a spectrogram. This was used for the video ending.
* esp8266
* [example_125k_raw](esp8266/example_125k_raw) - Sending a raw 125kHz wide LoRa message.
* [example_500k_raw](esp8266/example_500k_raw) - Sending a raw 500kHz wide LoRa message.
* [**lorawan_example**](esp8266/lorawan_example) - Using the I2S bus on the ESP8266 to send a full-stack LoRaWAN message to the things network.
* [non_lora_310_transmit](esp8266/non_lora_310_transmit) - Exmaple of how to transmit 310MHz OOK with an ESP8266.
* lib
* [aes-cbc-cmac.h](lib/aes-cbc-cmac.h) - Public Domain RFC4493 AES-CMAC header only library.
* [LoRa-SDR-Code.h](lib/LoRa-SDR-Code.h) - MIT (unrestrictive) Licensed code to construct LoRa packets
* [lorawan_simple.h](lib/lorawan_simple.h) - MIT (unrestrictive) Licensed code to construct LoRaWAN packets.
* [rf_data_gen.h](lib/rf_data_gen.h) - Helper function for helping generate bit tables for I2S/SPI outpiut of carefully crafted signals.
* [tiny-AES-c.h](lib/rf_data_gen.h) - Public Domain AES encryption/decryption library.
* tools
* [60-rtlsdr.rules](tools/60-rtlsdr.rules) - Make it so you can use your airspy from Linux as a user.
* [complex_magsink_to_image.c](tools/complex_magsink_to_image.c) - Generate ultra high resolution (in time domain) waterfall views.
* [testloradec.grc](tools/testloradec.grc) - Using gr_lora exmaple to decode LoRa in GNURadio
## Introduction (LoRa)
Firmware-only LoRa transmission, for a variety of processors. Send LoRa packets, without any radio, chips, external hardware or built-in radios at all on a variety of common, inexpensive processors. While not truly bit banging, this repository shows how using either a shift register (i.e. I2S or SPI port) or an APLL, you can send LoRa packets that can be decoded by commercial off the shelf LoRa gateways and other chips.
There are two major modes that this repository works with.
@@ -31,16 +79,13 @@ Click Below for the Youtube Video version of this page:
[![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
### 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)
@@ -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)
Now, the real magic happens, when you realize these two principles actually work together. You get an image at the base band, a reflected image around the sampling frequency, then around ×3 the sampling frequency, you get another 2 images, the forward and reverse. And ×5, and ×7, etc.
Now the real magic happens, when you realize these two principles actually work together. You get an image at the base band, a reflected image around the sampling frequency, then around ×3 the sampling frequency, you get another 2 images, the forward and reverse. And ×5, and ×7, etc.
With this, with a precise enough clock, we can arbitrarily generate any frequency we wish, provided there's enough bandwidth left on the GPIO of our micro to generate it, even if the "actual" signal we're generating is much much lower in frequency.
#### A side-note: RC/RLC oscllators vs crystal oscillators.
#### A side-note: RC/RLC oscillators vs crystal oscillators.
Internal oscillators in microcontrollers aren't only inacacurate, but they also jitter around in frequency. You might think this a negative, but in fact, using the internal oscillator built into micros can often be a lifesaver, getting you past EMI/EMC. Because the internal oscillators aren't just imprecise but jittery, they prevent harmonics of individual frequencies higher up in the spectrum because the clock rate drifts around so heavily.
Internal oscillators in microcontrollers aren't only inaccurate, but they also jitter around in frequency. You might think this a negative, but in fact, using the internal oscillator built into micros can often be a lifesaver, getting you past EMI/EMC. Because the internal oscillators aren't just imprecise but jittery, they prevent harmonics of individual frequencies higher up in the spectrum because the clock rate drifts around so heavily.
Crystal Output:
![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.
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.
![Bitstream Analysis](resources/bitstreamdiagram.png)
You can see from the above diagram in:
* **𝔸** our output on a platform like the CH32V203 is not perfect, that's because the SPI bus on the CH32V203 glitches by parts of a bit here and there. This causes other, weaker images in the output. But, largely we can produce totally valid and readable (at a long distance) LoRa packets.
* **𝔹** LoRa consists of several upchirps some in a preamble.
* **** two more upchirps with a phase offset indicating a sync word if we select 0x43 (or 0x34 depending on endain) for the upchirps here our packets will be decoded and potentially forwarded by commercial LoRa gateways.
* **𝔻** 2.25 down chrips in. That extra .25 causes some pain 😈 (the minimum logical unit is a quarter chirp, not a whole chirp).
* Then a payload where each upchirp is offset by a phase to convey information in **𝔼**.
This diagram shows frequency on the X axis, and time on the Y axis (top to bottom)... You can see:
* **** our output on a platform like the CH32V203 is not perfect, that's because the SPI bus on the CH32V203 glitches by parts of a bit here and there. This causes other, weaker images in the output. But, largely we can produce totally valid and readable (at a long distance) LoRa packets.
* **** LoRa consists of several upchirps some in a preamble.
* **** two more upchirps with a phase offset indicating a sync word if we select 0x43 (or 0x34 depending on endian) for the upchirps here, our packets will be decoded and potentially forwarded by commercial LoRa gateways.
* **** 2.25 down chrips in. That extra .25 causes some pain (the minimum logical unit is a quarter chirp, not a whole chirp).
* Then a payload where each upchirp is offset by a phase to convey information in ****.
Conveniently the window for a given chirp is stable depending on the spreading factor. For the above packet, with SF7, it works out to 1,024us per symbol, or for SF8, 2,048us per symbol. Each symbol/chirp can represent a number of bits, by a phase offset.
The raw "phase" of a chirp is grey-coded in order to better spread the bit error between bits to higher layers of the process. For instance, if you are off-by-one with regards to the phase you believe the chirp is at, it could be over a boundary from say 0b1111 and 0b10000 and would cause 5 bit errors. By grey coding it, it minimizes the bit errors created by an off-by-one or even a few of the phase.
After this raw bitstream is decoded from the individual chirps and de-grey-coded (see `encodeHamming84sx`) in [`LoRa-SDR-Code.h`](https://github.com/cnlohr/lolra/blob/master/lib/LoRa-SDR-Code.h), then we transpose/interleve the bits so any one symbol that could get taken out (see `diagonalInterleaveSx`) to spread any errors out so a single lost symbol can be recovered, whitened (I believe this is actually a worthless step in this protocol, correct me if I'm wrong) see `Sx1272ComputeWhitening`. Above whitening is an error correction layer to help fix any of the bit errors taht could happen at a lower layer (see `encodeFec`).
After this raw bitstream is decoded from the individual chirps and de-grey-coded (see `encodeHamming84sx`) in [`LoRa-SDR-Code.h`](https://github.com/cnlohr/lolra/blob/master/lib/LoRa-SDR-Code.h), then we transpose/interleve the bits so any one symbol that could get taken out (see `diagonalInterleaveSx`) to spread any errors out so a single lost symbol can be recovered and whitened (I believe this is actually a worthless step in this protocol, correct me if I'm wrong) see `Sx1272ComputeWhitening`. Above whitening is an error correction layer to help fix any of the bit errors that could happen at a lower layer (see `encodeFec`).
Overall the messages have a header, and a payload. Note that this can be a little tricky, because the header sometimes uses different encoding settings than the payload. And that's it.
@@ -115,16 +160,16 @@ A more detailed view of the protocol can be found [here, for a more academic vie
I started the project with an ESP32-S2 to see if I could output a signal using the internal built-in APLL, and routing the APLL/2 clock out via the IOMUX, and the answer was I could. Because this generates a simple square wave, and square waves have harmonics at F×3, F×5, F×7, etc... up the spectrum, if I set the APLL to 139.06 MHz, it outputs 69.53MHz. The 13th harmonic is 903.9 MHz, or the first 125kHz LoRa channel. Then by tuning the least significant PLL control bits, we can tune it from 903.9 MHz - 62.5kHz to 903.9 + 62.5kHz, by tuning the APLL to 139.06 MHz - 9.62kHz to 139.06 MHz + 9.62 kHz. This lets us generate the characteristic LoRa chirps and indeed this is receivable!
The ESP32-S2 also has another trick - the gpio mux is capable of outputting a signal or the inverse of that signal. That way we can differentially create the 139.06MHz signal, boosting the power output by 3dB!
The ESP32-S2 also has another trick - the GPIO mux is capable of outputting a signal or the inverse of that signal. That way we can differentially create the 139.06MHz signal, boosting the power output by 3dB!
There are issues with the ESP32-S2, however. Notably that:
1. The APLL is quite rough since it's actually an analog device fundamentally and struggles to keep tight control on the output signal.
2. Its output looks very unusual, and is something that fundamentally limits the performance of the sending of frames.
1. The APLL is quite rough since it's fundamentally an analog device and struggles to keep tight control on the output signal.
2. Its output looks very unusual, and is something that limits the performance of the sending of frames.
3. Because it is operating down at the F÷13 node, it has to operate over a very, very small window, ±9.62 kHz, which is quite challenging.
Additioanlly, very few processors even have an APLL, so in spite of this fast success, I decided to move onto direct synthesis.
Additioanlly, very few processors even have an APLL, so in spite of this fast success, I decided to move onto...
### Direct bitstream synthesis.
### Direct bitstream synthesis
Several years ago, I did a number of projects that used direct bitstream synthesis to do a few things, like [Broadcasting RF Color NTSC television on Channel 3 with an ESP8266](https://www.youtube.com/watch?v=bcez5pcp55w) or [Using Ethernet Packets to transmit AM radio](https://www.youtube.com/watch?v=-7jlRfqaYuY). One of the neat tricks is, if you transmit a bitstream out on an SPI or I2S shift register, it causes aliasing at the sample rate, with images at F×3, F×5, F×7, etc. But, the neat part is it preserves the size/shape of the transmitted waveform at images/aliases up the spectrum. For Channel 3, the 65MHz signal was being refelcted around the 40MHz sampling rate. Harry Nyquist can go bite a lemon.
@@ -132,21 +177,21 @@ This technique gives an incredible amount of fidelity even in extremely poor sit
There are several ways to accomplish this, but typically it's easiest with a shift register. A shift register like that in an I2S or SPI bus. And, if you use DMA, you can easily feed the shift register with more data without waking the CPU up every cycle. There are other ways, though, such as directly toggling an IO, or using a timer to turn an IO on and off at the right time, but it's easiest to write code to generate a bitstream and shift it out.
For shift registers, a few considerations must be made, such as making sure that the endianness and bit widths and memory arrangements are corret, but, in general, you can keep up, and unless there is lag, like time between each word, they are typically able to faithfully-enough represent a bit pattern on output to be transferred and shifted out of a pin.
For shift registers, a few considerations must be made, such as making sure that the endianness and bit widths and memory arrangements are correct, but, in general, you can keep up, and unless there is lag, like time between each word, they are typically able to faithfully-enough represent a bit pattern on output to be transferred and shifted out of a pin.
The "lohrcut" described in the video involves writing a function that, given a point in time determines the amplitude of a signal. This function can be to determine the amplitude of a very high frequency signal, then, the sample rate can be whatever physically realizable sample rate that's avaialble. This will create an image of the high frequency signal at a much lower frequency signal, building it out of power between 0 and Fs/2.
The "lohrcut" described in the video involves writing a function that, given a point in time, determines the amplitude of a signal. This function can be to determine the amplitude of a very high frequency signal, then, the sample rate can be whatever physically realizable sample rate that's avaialble. This will create an image of the high frequency signal at a much lower frequency signal, building it out of power between 0 and Fs/2.
Another concern is flash on some systems accesses inconsistently or doesn't work well at certain frequencies. In those cases, like on the ESP8266, the tables must be read into RAM and played from there.
Another concern is flash, on some systems accesses inconsistently or doesn't work well at certain frequencies. In those cases, like on the ESP8266, the tables must be read into RAM and played from there.
## LoRaWAN
LoRa frames are totally encapsulated. If you wanted, we could stop here. You could even use a commercial gateway, but the frames could not be set to brokers like The Things Network. For instance, if you ran a raspberry pi gateway, you could just accept whatever old LoRa frames you wanted, but, we took this a step further by hleping the packets get forwarded around the world. LoRaWAN is "end to end" encryption, in that none of your neighbors, or gateways can read the messages. Though, it is curious - the things network CAN read youe messages because they have the encryption keys.
LoRa frames are totally encapsulated. If you wanted, we could stop here. You could even use a commercial gateway, but without using LoRaWAN, the frames could not be sent to brokers like The Things Network. For instance, if you ran a raspberry pi gateway, you could just accept whatever old LoRa frames you wanted, but, we took this a step further by helping the packets get forwarded around the world. LoRaWAN is "end to end" encryption, in that none of your neighbors, or gateways can read the messages. Though, it is curious - The Things Network CAN read your messages because they have the encryption keys.
Conveniently, there is a single function call, `GenerateLoRaWANPacket` in [`lib/lorawan_simple.h`](https://github.com/cnlohr/lolra/blob/master/lib/lorawan_simple.h) that handles all of the required encapsulation. Simply use this function to getnerate your frames, and broadcast them!
Conveniently, you can call, `GenerateLoRaWANPacket` in [`lib/lorawan_simple.h`](https://github.com/cnlohr/lolra/blob/master/lib/lorawan_simple.h) handles all of the required encapsulation. Simply use this function to generate your frames, and broadcast them!
### The LoRa Gateway
We can transmit these messages. Cool. But now to receive them, we either will need a devices like a [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module) or a gateway like a [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit). The latter is really interesting here because there are thousands of these set up all over the world, and connected to [The Things Network](https://www.thethingsnetwork.org/). That means if we transmit a properly formatted LoRaWAN packet within earshot of one of those gateways, we can get the frame elsewhere on the planet!
We can transmit these messages. Cool. But now to receive them, we will either need a devices like a [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module) or a gateway like a [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit). The latter is really interesting here because there are thousands of these set up all over the world, and connected to [The Things Network](https://www.thethingsnetwork.org/). That means if we transmit a properly formatted LoRaWAN packet within earshot of one of those gateways, we can get the frame elsewhere on the planet!
Setup is pretty starightforward. You need to:
1. Create an account (they are free for personal/academic use)
@@ -175,14 +220,14 @@ Setup is pretty starightforward. You need to:
## Limitations
* SF <= 6, SF >= 11 are unavailable. I spent 10+ hours trying to figure them out and gave up.
PR's are open if you can figure any of these out! I just spent all the time I plan to spend on this project before I got here.
* SF <= 6, SF >= 11 are unavailable. I spent 10+ hours trying to figure them out and gave up.
* There seems to be something not quite perfect for some sizes. As in I was getting CRC errors in some places that my code "should" work but doesn't.
* I never got LDRO to work correctly. I believe it might have to do with the LoRa Code Word (prefixing the 2 downchirps)
* The SPI on the ch32v203 still isn't perfect. I was unable to get the I2S engine working, perhaps it doesn't work on the ch32v203?
* The licenses in this project are a hodgepodge. I encourage people to just use this project as a starting point for other work.
PR's are open if you can figure any of these three out! I just spent all the time I plan to spend on this project before I got here.
## Future Work
For LoRa specifically, waves are very well behaved and should be completely creatable with timer circuitry on the fly and should not need any precomputation, but I haven't gotten around to it yet. This would forego the need to have a large table for the chirps flashed into a device.
@@ -193,38 +238,6 @@ Additionally, it would be fun to add a filter, or maybe try to build a filter in
Additionally, additionally, it would be very cool to try to build a Class C amplifier for the 900MHz signal. This would be very cool because it could be efficient, incredibly cheap and simple and also provide as much as 10-20dB of gain!
## Resources
### LoRa Software
* [The C++ Library I based my LoRa Frames On](https://github.com/myriadrf/LoRa-SDR)
* [A gnuradio LoRa library](https://github.com/tapparelj/gr-lora_sdr)
* [Another gnuradio LoRa library](https://github.com/rpp0/gr-lora)
* [GQRX](https://www.gqrx.dk/)
* [gnuradio](https://www.gnuradio.org/)
* [LoRa Baud Rate Calculator](https://unsigned.io/understanding-lora-parameters/) << be sure to select 125 or 500k Bandwidths, the default bandwidth is intenable.
### Papers and other resources
* [A Great LoRa Introduction](https://medium.com/@prajzler/what-is-lora-the-fundamentals-79a5bb3e6dec)
* [A more grounded paper on LoRa](https://chrisye-liu.github.io/files/yang22emu.pdf)
* [Reversing LoRa by Matt Knight](https://github.com/matt-knight/research/blob/master/2016_05_20_jailbreak/Reversing-Lora-Knight.pdf)
* [An academic paper on LoRa](https://dl.acm.org/doi/10.1145/3546869)
### Software Resources Directly Used
* [ch32v003fun](https://github.com/cnlohr/ch32v003fun)
* [esputil](https://github.com/cpq/esputil) dependency-free ESP programming
* [nosdk8266](github.com/cnlohr/nosdk8266)
Hardware
* [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit)
* [Airspy Mini SDR](https://v3.airspy.us/product/a-airspy-mini/)
* [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module)
## Special Thanks
* @MustardTiger for a crazy amount of support work in this project
* Willmore for the editing work
* My girlfriend for testing help and auxiliary camera work
* Everyone who helped out with my various open source projects.
## Range Tests
Urban testing was performed on 2024-02-23, Suburban on 2022-02-26 and Rural testing was performed on 2022-02-27.
@@ -238,7 +251,7 @@ For TTGO Lora32, there was a +3dBi antenna added. For the MikroTik LR9, it used
|------------|---------------------|--------------|-----------|-----|----------------------------------------------------|---------------|------------------|--------|
| 2024-02-23 | CH32V203 | MikroTik LR9 | SF8/CR48 | 125 | Downtown Bellevue (Urban) | 435' 132m | -98 / -9 | Ground |
| 2024-02-23 | CH32V203 | MikroTik LR9 | SF10/CR48 | 500 | Downtown Bellevue (Urban) | 435' 132m | -90 / -18 | Ground |
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Mirramont Park (Light Suburban + Woods) | >576' >176m | -134 / -12 | Ground |
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Miramont Park (Light Suburban + Woods) | >576' >176m | -134 / -12 | Ground |
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Poo Poo Point Trailhead (Rural) | >1117' >340m | -123 / -6 | Ground |
| 2024-02-26 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Issaquah Suburb (+Light Trees) | 2200' 669m | -133 / -10 | Ground |
| 2024-02-27 | CH32V203 | TTGO Lora32 | SF8/CR48 | 125 | Meadowbrook (Rural) Red Longer Antenna | 2220' 677m | -135 / -13 | Drone |
@@ -248,8 +261,8 @@ For TTGO Lora32, there was a +3dBi antenna added. For the MikroTik LR9, it used
| 2024-02-27 | ESP8266 @ 80MHz | TTGO Lora32 | SF8/CR48 | 125 | Meadowbrook (Rural) Grey VNA Matched Antenna | 2789' 850m | -138 / -13 | Drone |
| 2024-02-27 | ESP8266 @ 173MHz | TTGO Lora32 | SF7/CR48 | 125 | Meadowbrook (Rural) Grey VNA Matched Antenna | 2812' 857m | -131 / -8 | Drone |
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Meadowbrook (Rural) (Note 1) | 3428' 1044m | -137 / -13 | Ground |
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Meadowbrook (Rural) Light Percipitation | >4895' >1492m | -130 / -8 | Drone |
| 2024-02-27 | ESP32-S2 + Funtenna | TTGO Lora32 | SF10/CR48 | 125 | Meadow brook (Rural) Light Percipitation | 705' / 215m | -139 / -15 | Drone |
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Meadowbrook (Rural) Light Precipitation | >4895' >1492m | -130 / -8 | Drone |
| 2024-02-27 | ESP32-S2 + Funtenna | TTGO Lora32 | SF10/CR48 | 125 | Meadow brook (Rural) Light Precipitation | 705' / 215m | -139 / -15 | Drone |
| 2024-02-27 | ESP32-S2 + Bitenna | TTGO Lora32 | SF10/CR48 | 125 | Snoqualmie Trail, Dog Park to Ribary Creek (Rural) Light Percipitation | 8460' / 2580m | -141 / -16 | Drone |
1. There were two ground ESP32-S2 + Bitenna Tests. The one mentioned in the video is not recorded here, since I didn't get accurate results.
@@ -257,3 +270,46 @@ For TTGO Lora32, there was a +3dBi antenna added. For the MikroTik LR9, it used
3. On the CH32V203, there is a 60 uA difference at 3.3V with anteanna on/off (some is going to be capacitive / inductive loading / reflected back because of SWR). The EIRP is **less** than this, based on the antenna stub SWR, but this is the total power consumption, so it is probably less than 120uW of EIRP.
## Resources
### LoRa Software
* [The C++ Library I based my LoRa Frames On](https://github.com/myriadrf/LoRa-SDR)
* [A gnuradio LoRa library](https://github.com/tapparelj/gr-lora_sdr)
* [Another gnuradio LoRa library](https://github.com/rpp0/gr-lora)
* [GQRX](https://www.gqrx.dk/)
* [gnuradio](https://www.gnuradio.org/)
* [LoRa Baud Rate Calculator](https://unsigned.io/understanding-lora-parameters/) << be sure to select 125 or 500k Bandwidths, the default bandwidth is not useful.
### Papers and other resources
* [A Great LoRa Introduction](https://medium.com/@prajzler/what-is-lora-the-fundamentals-79a5bb3e6dec)
* [A more grounded paper on LoRa](https://chrisye-liu.github.io/files/yang22emu.pdf)
* [Reversing LoRa by Matt Knight](https://github.com/matt-knight/research/blob/master/2016_05_20_jailbreak/Reversing-Lora-Knight.pdf)
* [An academic paper on LoRa](https://dl.acm.org/doi/10.1145/3546869)
* Brought to my attention after I published, [Everything has its Bad Side and Good Side: Turning Processors to
Low Overhead Radios Using Side-Channels](https://dl.acm.org/doi/abs/10.1145/3583120.3586959) Accomplished something very similar to this, with an arduino!
### Software Resources Directly Used
* [ch32v003fun](https://github.com/cnlohr/ch32v003fun)
* [esputil](https://github.com/cpq/esputil) dependency-free ESP programming
* [nosdk8266](https://github.com/cnlohr/nosdk8266)
### Hardware
* [MikroTik LR9](https://mikrotik.com/product/wap_lr9_kit)
* [Airspy Mini SDR](https://v3.airspy.us/product/a-airspy-mini/)
* [LILYGO® T-Beam Meshtastic](https://www.lilygo.cc/products/t-beam-v1-1-esp32-lora-module)
### LoLRa Like Things
* [Wirelessly control 49 MHz toy with I/O line flipping on Pi Pico](https://www.youtube.com/watch?v=K-6dos8Hvm8)
### Other Interesting Radio Links
* [Radio station snafu in Seattle bricks some Mazda infotainment systems](https://arstechnica.com/cars/2022/02/radio-station-snafu-in-seattle-bricks-some-mazda-infotainment-systems/)
## Special Thanks
* @MustardTiger for a crazy amount of support work in this project
* Willmore for the editing work
* Several other folks in my discord for review work and editing work on this page
* My girlfriend for testing help and auxiliary camera work
* Everyone who helped out with my various open source projects
-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
+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
@@ -2,6 +2,7 @@ all : flash
TARGET:=loratest
TARGET_MCU:=CH32V203
TARGET_MCU_PACKAGE:=C8
CH32V003FUN:=../ch32v003fun/ch32v003fun
EXTRA_ELF_DEPENDENCIES:=chirpbuff.h
+3 -45
View File
@@ -1,48 +1,6 @@
/**
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.
**/
// 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>
+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)
+12
View File
@@ -1,4 +1,16 @@
<!DOCTYPE html>
<!-- This file is under the regular MIT license.
Copyright 2024 Charles Lohr (cnlohr)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<HTML>
<HEAD>
<LINK rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
+12
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 filter = { vendorId : 0x1209, productId : 0xd035 };
let dev = null;
+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;
}
}
+1
View File
@@ -1281,3 +1281,4 @@ connections:
metadata:
file_format: 1