├── .gitignore ├── LICENSE ├── README.md ├── lora.py ├── misc ├── airtime_calculator.jpg ├── airtime_calculator.zip ├── console_output.png ├── fhss.jpg ├── issue │ └── 8 │ │ └── setup.jpg ├── receiver.ipynb └── sender.ipynb ├── receiver ├── lora.py └── receiver.py └── sender ├── lora.py └── sender.py /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .picowgo 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repo implements more than basic SX1276 operations while [Learn_SX1276](https://github.com/xg590/Learn_SX1276) shows all the basics. 2 | ## SX1276 3 | MicroPython Library for SX1276 LoRa radio modem 4 | ## Features 5 | * MAC layer (half-duplex). 6 | * One SX1276 can send a "REQ" packet (in a blocking way) and expect a specified SX1276 to respond with an "ACK" packet. This process is handled by this library. 7 | * One SX1276 can send a "BRD" packet (in a non-blocking way) and expect no "ACK" reply. 8 | * Implement FHSS (first?) 9 | * FCC mandates frequency hopping if dwell time is above the threshold 400ms. 10 | * Large spreading factor and narrow bandwidth can significantly prolong the dwell time so that freq hopping is necessary for transmiiting large packet. 11 | ## Usage 12 | * Upload lora.py to MCUs (Heltec WiFi LoRa 32 V2) 13 | * Run [sender.py](sender/sender.py) and [receiver.py](receiver/receiver.py) on two separate MCUs 14 | ## My dev environment 15 | * Two MCUs with SX1276 (ESP32: Heltec WiFi LoRa 32 V2) 16 | * Flash MCUs with MicroPython 17 | * Connect two MCUs to a Linux Machine with VSCode via USB 18 | * Install Pico-W-Go extension for VSCode 19 | * Open sender/receiver folders in two VSCode windows 20 | * Configure sender/receiver projects for Pico-W-Go 21 | * Specify the "Manual Com Device" in Pico-W-Go and restart the Pico-W-Go 22 | * Play with Pico-W-Go commands 23 | ## Console Output of sample code 24 | 25 | ## FHSS 26 | * To prove the point of frequency hopping, I use a RTL-SDR to monitor the spectrum. In following waterfall diagram, we see the signal hops between 914 and 916MHz as I programmed it to be. 27 | 28 | * FHSS is not necessary if the message is short. For example, a 29Bytes packet can be transmitted under 400ms, given parameters {SF:10, BW:125kHz, CR:4/5, Header: Explicit , Preamble: 6}. 29 |
30 | Download the above air time [calculator](misc/airtime_calculator.zip) 31 | 32 | ## Note 33 | * FHSS feature can be turned off by only specifying one frequency in channels2Hopping / FHSS_list. 34 | * It is meaningless to do Channel Activity Detection (CAD) before Tx because SX1276 only match elusive preambles which last few milliseconds. No good solution to do Listen Before Talk or CSMA. -------------------------------------------------------------------------------- /lora.py: -------------------------------------------------------------------------------- 1 | import time, urandom, struct 2 | from machine import Pin, SPI 3 | 4 | class SX1276: 5 | def __init__(self, RST_Pin, CS_Pin, SPI_CH, SCK_Pin, MOSI_Pin, MISO_Pin, DIO0_Pin, DIO1_Pin, SRC_Id, FHSS_list, plus20dBm=False, debug=False): 6 | self.src_id = SRC_Id # id of packet sender 7 | self.pkt_id = 0 # pkt_id is a random packet id. Why we need this ? If we ask the receiver return an acknowledgement, how do we know which packet it is acknowledging? 8 | self.pkt_type = 0 9 | # REQ or Request : Sender needs an ACK packet from the receiver as the response to this REQ packet 10 | # ACK or Acknowledge: Receiver sends this ACK response 11 | # BRD or Broadcast : Sender needs no ACK response 12 | self.PKT_TYPE = {'REQ':0, 'ACK':1, 'BRD':2} 13 | self.header_fmt = 'HHHH' # src_id, dst_id, pkt_id, pkt_type 14 | self.header_size = struct.calcsize(self.header_fmt) 15 | self._mode = None 16 | self.FHSS_list = FHSS_list 17 | self.debug = debug 18 | self.is_available = False # let the main code know Tx and RxCont is done 19 | ######################## 20 | # # 21 | # 1. Reset the modem # 22 | # # 23 | ######################## 24 | rst_pin = Pin(RST_Pin, Pin.OUT) 25 | rst_pin.off() 26 | time.sleep(0.01) 27 | rst_pin.on() 28 | time.sleep(0.01) 29 | 30 | ################################# 31 | # # 32 | # 2. SPI comm with the modem. # 33 | # # 34 | ################################# 35 | 36 | # Tx: Modem's wireless transmittion, Rx: Reception 37 | # Modem communicates with other modem since we command the modem to perform Tx/Rx operations via the SPI interface. 38 | # We disable SPI communication with the modem first, to ensure Tx/Rx operations only happends when we need. 39 | self.cs_pin = Pin(CS_Pin, Pin.OUT) 40 | self.cs_pin.on() # Release board from SPI Bus by bringing it into high impedance status. 41 | 42 | # SPI communication 43 | # See datasheet: Device support SPI mode 0 (polarity & phase = 0) up to a max of 10MHz. 44 | self.spi = SPI(SPI_CH, baudrate=10_000_000, polarity=0, phase=0, 45 | sck=Pin(SCK_Pin), mosi=Pin(MOSI_Pin), miso=Pin(MISO_Pin) 46 | ) 47 | 48 | #################### 49 | # # 50 | # 3.Lora # 51 | # # 52 | #################### 53 | self.RegTable = { # register table 54 | 'RegFifo' : 0x00 , 55 | 'RegOpMode' : 0x01 , # operation mode 56 | 'RegFrfMsb' : 0x06 , 57 | 'RegFrfMid' : 0x07 , 58 | 'RegFrfLsb' : 0x08 , 59 | 'RegPaConfig' : 0x09 , 60 | 'RegFifoTxBaseAddr' : 0x0e , 61 | 'RegFifoRxBaseAddr' : 0x0f , 62 | 'RegFifoAddrPtr' : 0x0d , 63 | 'RegFifoRxCurrentAddr' : 0x10 , 64 | 'RegIrqFlags' : 0x12 , 65 | 'RegRxNbBytes' : 0x13 , # Number of received bytes 66 | 'RegPktSnrValue' : 0x19 , 67 | 'RegPktRssiValue' : 0x1a , 68 | 'RegRssiValue' : 0x1b , 69 | 'RegHopChannel' : 0x1c , 70 | 'RegModemConfig1' : 0x1d , 71 | 'RegModemConfig2' : 0x1e , 72 | 'RegPreambleMsb' : 0x20 , 73 | 'RegPreambleLsb' : 0x21 , 74 | 'RegPayloadLength' : 0x22 , 75 | 'RegHopPeriod' : 0x24 , 76 | 'RegModemConfig3' : 0x26 , 77 | 'RegDioMapping1' : 0x40 , 78 | 'RegVersion' : 0x42 , 79 | 'RegPaDac' : 0x4d 80 | } 81 | 82 | self.Mode = { # see Table 16 LoRa ® Operating Mode Functionality 83 | 'SLEEP' : 0b000, 84 | 'STANDBY' : 0b001, 85 | 'TX' : 0b011, 86 | 'RXCONTINUOUS' : 0b101, 87 | 'RXSINGLE' : 0b110, 88 | 'CAD' : 0b111, 89 | } 90 | 91 | if True: # code folding 92 | # Choose LoRa mode and Test write/read functions 93 | LongRangeMode = 0b1 94 | # Choose LoRa (instead of FSK) mode for SX1276 and put the module in sleep mode 95 | self.spi_write('RegOpMode', self.Mode['SLEEP'] | LongRangeMode << 7) 96 | # Test read function 97 | assert self.spi_read('RegOpMode') == (self.Mode['SLEEP'] | LongRangeMode << 7), "LoRa initialization failed" 98 | 99 | # Set modem config: bandwidth, coding rate, header mode, spreading factor, CRC, and etc. 100 | # See 4.4. LoRa Mode Register Map 101 | Bw = {'125KHz':0b0111, '500kHz':0b1001} 102 | CodingRate = {5:0b001, 6:0b010, 7:0b011, 8:0b100} 103 | ImplicitHeaderModeOn = {'Implicit':0b1, 'Explicit':0b0} 104 | self.spi_write('RegModemConfig1', Bw['125KHz'] << 4 | CodingRate[5] << 1 | ImplicitHeaderModeOn['Explicit']) 105 | 106 | SpreadingFactor = {7:0x7, 9:0x9, 10:0xA, 12:0xC} 107 | TxContinuousMode = {'normal':0b0, 'continuous':0b1} 108 | RxPayloadCrcOn = {'disable':0b0, 'enable':0b1} 109 | self.spi_write('RegModemConfig2', SpreadingFactor[10] << 4 | TxContinuousMode['normal'] << 3 | RxPayloadCrcOn['enable'] << 2 | 0x00) # Last 0x00 is SymbTimeout(9:8) 110 | 111 | LowDataRateOptimize = {'Disabled':0b0, 'Enabled':0b1} 112 | AgcAutoOn = {'register LnaGain':0b0, 'internal AGC loop':0b1} 113 | self.spi_write('RegModemConfig3', LowDataRateOptimize['Enabled'] << 3 | AgcAutoOn['internal AGC loop'] << 2) 114 | 115 | # Preamble length 116 | self.spi_write('RegPreambleMsb', 0x0) # Preamble can be (2^15)kb long, much longer than payload 117 | self.spi_write('RegPreambleLsb', 0x8) # but we just use 8-byte preamble 118 | 119 | # FHSS 120 | # How does SX1276 chip hop the freq spectrum? 121 | # First, two SX1276 chips were given a same series of frequencies (FHSS_list) in advance. 122 | # One SX1276 is configured as sender and another is receiver. 123 | # The sender is configured to be interrupted (IRQ) by 'TxDone' and 'FhssChangeChannel' 124 | # The receiver is configured to be interrupted by 'RxDone' and 'FhssChangeChannel' 125 | # After the chip spent enough (dwell) time on one frequency channel during Tx or Rx, 'FhssChangeChannel' IRQ is triggered. 126 | # New freq (next unused element in FHSS_list) is set in the 'FhssChangeChannel' IRQ handler. 127 | # After enough channels are hopped, Tx/Rx is done and TxDone/RxDone is triggered. 128 | 129 | # Symbol duration: Tsym = 2^SF / BW 130 | # For example, if SF = 10, BW = 125kHz, then Tsym = 8.192ms 131 | # Given FCC permits a 400ms max dwell time per channel, we must hop at least every 48 symbols 132 | # HoppingPeriod (dwell time on each freq) = FreqHoppingPeriod * Tsym 133 | # In the following code, the chip would hop freq for every 20 symbols. 134 | FreqHoppingPeriod = 20 # Symbol periods between freq hops. 135 | if len(FHSS_list) == 1: # As requested in Issue 8, the FHSS feature can be turned off when one freq is provided. 136 | FreqHoppingPeriod = 0 # Hopping feature is turned off by this line 137 | self.spi_write('RegHopPeriod', FreqHoppingPeriod) # HoppingPeriod = 20 * 8.192ms 138 | FhssPresentChannel = self.spi_read('RegHopChannel') 139 | 140 | # See 4.1.4. Frequency Settings 141 | FXOSC = 32e6 # Freq of XOSC 142 | self.FSTEP = FXOSC / (2**19) 143 | 144 | # Output Power 145 | # If desired output power is within -4 ~ +15dBm, use PA_LF or PA_HF as amplifier. 146 | # Use PA_BOOST as amplifier to output +2 ~ +17dBm continuous power or up to 20dBm peak power in a duty cycled operation. 147 | # Here we will always use PA_BOOST. 148 | # Since we use PA_BOOST, Pout = 2 + OutputPower and MaxPower could be any number (Why not 0b111/0x7?) 149 | PaSelect = {'PA_BOOST':0b1, 'RFO':0b0} # Choose PA_BOOST (instead of RFO) as the power amplifier 150 | MaxPower = {'15dBm':0x7, '13dBm':0x2} # Pmax = 10.8 + 0.6 * 7 151 | OutputPower = {'17dBm':0xf, '2dBm':0x0} 152 | self.spi_write('RegPaConfig', PaSelect['PA_BOOST'] << 7 | MaxPower['15dBm'] << 4 | OutputPower['2dBm']) 153 | 154 | # Enables the +20dBm option on PA_BOOST pin. 155 | if plus20dBm: # PA (Power Amplifier) DAC (Digital Analog Converter) 156 | PaDac = {'default':0x04, 'enable_PA_BOOST':0x07} # Can be 0x04 or 0x07. 0x07 will enables the +20dBm option on PA_BOOST pin 157 | self.spi_write('RegPaDac', PaDac['enable_PA_BOOST']) 158 | 159 | # FIFO data buffer 160 | # SX1276 has a 256 byte memory area as the FIFO buffer for Tx/Rx operations. 161 | # How do we know which area is for Tx and which is for Rx. 162 | # We must set the base addresses RegFifoTxBaseAddr and RegFifoRxBaseAddr independently. 163 | # Since SX1276 work in a half-duplex manner, we better set both base addresses 164 | # at the bottom (0x00) of the FIFO buffer so that we can buffer 256 byte data 165 | # during transmition or reception. 166 | self.Fifo_Bottom = 0x00 # We choose this value to max buffer we can write (then send out) 167 | self.spi_write('RegFifoTxBaseAddr', self.Fifo_Bottom) 168 | self.spi_write('RegFifoRxBaseAddr', self.Fifo_Bottom) 169 | 170 | ####################### 171 | # # 172 | # 4. Interrupt # 173 | # # 174 | ####################### 175 | 176 | # If configured, An TxDone IRQ is triggered transmittion finishes. 177 | # How to understand Table 18? When we want to set IRQ trigger, We use Table 18. 178 | # If we want RxDone triggers DIO0, we write 0b00 << 6 to RegDioMapping1. How we know it is 6? Because 6th and 7th bits are for DIO0. 179 | # Why 0b00 instead of 0b01? Because TxDone would trigger DIO0. 180 | # If we want FhssChangeChannel trigger DIO1, we write 0b01 << 4 to RegDioMapping1. 181 | # Why 0b01? See Table 18, col "DIO1", row "01" 182 | self.DioMapping = { 183 | 'Dio0' : { 184 | 'RxDone' : 0b00 << 6, 185 | 'TxDone' : 0b01 << 6, 186 | 'CadDone' : 0b10 << 6 187 | }, 188 | 'Dio1' : { 189 | 'RxTimeout' : 0b00 << 4, 190 | 'FhssChangeChannel': 0b01 << 4, 191 | 'CadDetected' : 0b10 << 4 192 | }, 193 | 'Dio2' : { 194 | 'FhssChangeChannel': 0b00 << 2, 195 | 'FhssChangeChannel': 0b01 << 2, 196 | 'FhssChangeChannel': 0b10 << 2 197 | }, 198 | 'Dio3' : { }, 199 | 'Dio4' : { }, 200 | 'Dio5' : { 201 | 'ModeReady' : 0b00 << 4, 202 | }, 203 | } 204 | 205 | self.DioMapping = { 206 | 'Tx' : self.DioMapping['Dio0']['TxDone'] | self.DioMapping['Dio1']['FhssChangeChannel'], 207 | 'Rx' : self.DioMapping['Dio0']['RxDone'] | self.DioMapping['Dio1']['FhssChangeChannel'] 208 | } 209 | 210 | self.IrqFlags = { 211 | 'RxTimeout' : 0b1 << 7, 212 | 'RxDone' : 0b1 << 6, 213 | 'PayloadCrcError' : 0b1 << 5, 214 | 'ValidHeader' : 0b1 << 4, 215 | 'TxDone' : 0b1 << 3, 216 | 'CadDone' : 0b1 << 2, 217 | 'FhssChangeChannel': 0b1 << 1, 218 | 'CadDetected' : 0b1 << 0, 219 | } 220 | 221 | dio0_pin = Pin(DIO0_Pin, Pin.IN) 222 | dio0_pin.irq(handler=self._irq_handler, trigger=Pin.IRQ_RISING) 223 | dio1_pin = Pin(DIO1_Pin, Pin.IN) 224 | dio1_pin.irq(handler=self._irq_handler, trigger=Pin.IRQ_RISING) 225 | self.mode = 'STANDBY' # Request Standby mode so SX1276 performs reception initialization. 226 | 227 | def spi_write(self, reg, data, fifo=False): 228 | wb = bytes([self.RegTable[reg] | 0x80]) # Create a writing byte 229 | if fifo: 230 | data = wb + data 231 | else: 232 | data = wb + bytes([data]) 233 | self.cs_pin.value(0) # Bring the CS pin low to enable communication 234 | self.spi.write(data) 235 | self.cs_pin.value(1) # release the bus. 236 | 237 | def spi_read(self, reg=None, length=None): 238 | self.cs_pin.value(0) 239 | # https://docs.micropython.org/en/latest/library/machine.SPI.html#machine-softspi 240 | if length is None: 241 | data = self.spi.read(2, self.RegTable[reg])[1] 242 | else: 243 | data = self.spi.read(length+1, self.RegTable[reg])[1:] 244 | self.cs_pin.value(1) 245 | return data 246 | 247 | def set_freq(self): 248 | FhssPresentChannel = self.spi_read('RegHopChannel') & 0b00_111_111 249 | Frf = int(self.FHSS_list[FhssPresentChannel] / self.FSTEP) 250 | #if self.debug: print('[New CH]', FhssPresentChannel) 251 | self.spi_write('RegFrfMsb', (Frf >> 16) & 0xff) 252 | self.spi_write('RegFrfMid', (Frf >> 8) & 0xff) 253 | self.spi_write('RegFrfLsb', Frf & 0xff) 254 | 255 | @property 256 | def mode(self): 257 | return self._mode 258 | 259 | @mode.setter 260 | def mode(self, value): 261 | #print('[New mode]', value) 262 | if value == 'TX': 263 | self.set_freq() 264 | self.spi_write('RegDioMapping1', self.DioMapping['Tx']) 265 | self.is_available = False 266 | elif value == 'RXCONTINUOUS': 267 | # Q: so why we use RXCONTINUOUS instead of RXSINGLE? 268 | # A: If you refers to page 39 of the datasheet, you will find RXSINGLE procedure has a Timeout mechanism. 269 | # It is an energy-saving measure. The receiver wakes up from sleep mode and listen the channel. 270 | # If it find nothing, it goes back to sleep. 271 | # When we do regular commu, our receive will listen the channel indefinitely until we stop it actively. 272 | self.set_freq() 273 | self.spi_write('RegDioMapping1', self.DioMapping['Rx']) 274 | self.is_available = False 275 | elif value == 'STANDBY': 276 | self.spi_write('RegDioMapping1', 0x00) 277 | else: 278 | print('[Error] Unknown working mode') 279 | if self.mode != value: 280 | self.spi_write('RegOpMode', self.Mode[value]) 281 | self._mode = value 282 | 283 | def read_fifo(self): 284 | self.spi_write('RegFifoAddrPtr', self.spi_read('RegFifoRxCurrentAddr')) 285 | packet = self.spi_read('RegFifo', self.spi_read('RegRxNbBytes')) 286 | PacketSnr = self.spi_read('RegPktSnrValue') 287 | SNR = struct.unpack_from('b', bytes([PacketSnr]))[0] / 4 288 | PacketRssi = self.spi_read('RegPktRssiValue') 289 | #Rssi = read(RegRssiValue) 290 | if SNR < 0: 291 | RSSI = -157 + PacketRssi + SNR 292 | else: 293 | RSSI = -157 + 16 / 15 * PacketRssi 294 | RSSI = round(RSSI, 2) # Table 7 Frequency Synthesizer Specification 295 | return packet, SNR, RSSI 296 | 297 | def write_fifo(self, data): 298 | self.spi_write('RegFifoAddrPtr', self.Fifo_Bottom) 299 | self.spi_write('RegFifo', data, fifo=True) # Write Data FIFO 300 | self.spi_write('RegPayloadLength', len(data)) 301 | 302 | def send(self, dst_id=0, pkt_id=0, pkt_type=0, msg='', retry=1, timeout=9, debug=False): # src_id, dst_id, 303 | if len(msg) > 240: 304 | # The message in the buffer object will be stored in FIFO register before it is sent out. While, the FIFO register is 256 byte in size and it cannot be overflowed. 305 | # In addition, this library is working in data link layer and it is upper layer's responsibility to do fragmentation (https://www.geeksforgeeks.org/fragmentation-network-layer/). 306 | print('You got the error because you are trying to send a very long message. You can find an explaination to this error in the code comment.') 307 | raise # cannot send a too large message 308 | # 1. Create header 309 | # 2. Put header and message together 310 | # 3. Write payload to FIFO 311 | # 4. Put the modem in Tx mode so payload is sent out 312 | # 5. Then put the modem in Rx mode and wait 15 seconds if the packet is asking receiver to acknowledge. 313 | # 6. Or wait no time if the packet is for broadcasting or is for acknowledging 314 | # [Tx side] self.pkt_type = req ; Mode = Tx ; TxDone; RxCont 315 | # [Rx side] RxDone ; Mode = STANDBY ; send 'ACK' 316 | self.pkt_type = pkt_type 317 | if pkt_type == self.PKT_TYPE['REQ']: 318 | pkt_id = urandom.randint(1,65535) 319 | self.pkt_id = pkt_id 320 | header = struct.pack(self.header_fmt, self.src_id, dst_id, pkt_id, pkt_type) 321 | data = header + msg.encode() 322 | 323 | if pkt_type == self.PKT_TYPE['REQ']: 324 | for _ in range(retry): 325 | self.mode = 'STANDBY' 326 | self.write_fifo(data) 327 | self.mode = 'TX' # Request Standby mode so SX1276 send out payload 328 | for _ in range(timeout): 329 | if self.pkt_id == 0: 330 | break 331 | time.sleep(1) 332 | else: 333 | if debug: print('[Debug] REQ is not ACKed before timeout is triggered') # No break means no response in 5 seconds 334 | if self.pkt_id == 0: 335 | break 336 | else: 337 | if debug: print('[Debug] Resend the REQ packet {} times but it is still not ACKed'.format(retry)) # No break means no response in 5 seconds 338 | elif pkt_type in [self.PKT_TYPE['ACK'], self.PKT_TYPE['BRD']]: 339 | self.mode = 'STANDBY' 340 | self.write_fifo(data) 341 | self.mode = 'TX' 342 | else: 343 | print("Unsupported Packet Type") 344 | 345 | def _irq_handler(self, pin): 346 | irq_flags = self.spi_read('RegIrqFlags') 347 | self.spi_write('RegIrqFlags', 0xff) # write 0xff could clear all types of interrupt pkt_type 348 | # For one complete "Request for acknowledgement" communication, there are 4 critical points (CP): 349 | # Step 0: The receiver is put in RxCont mode. 350 | # Step 1: The sender Tx something then IRQ TxDone is trigger on the sender. (1st critical point) 351 | # Step 2: In the irq handler of the sender, "mode shifts from Tx to RxCont" so the sender prepares to listen the ACK response (step 8). 352 | # Step 3: An IRQ RxDone is trigger on all receivers. (2nd CP) 353 | # Step 4: In the irq handler, if dst_id matches self.src_id, the receiver know it is the right recipient. 354 | # Step 5: The right receiver will shift mode to STANDBY before Tx the ACK. 355 | # Step 6: The receiver Tx the ACK then IRQ TxDone is trigger on the RECEIVER. (3rd CP) 356 | # Step 7: In the irq handler, the receiver will be put in STANDBY mode for further use. 357 | # Step 8: The sender catch the ACK response (see step 2) when IRQ RxDone is triggered on the sender. (4th CP) 358 | # Step 9: In the irq handler, the sender's mode is shifted from RxCont to STANDBY for further use. Done 359 | if irq_flags & self.IrqFlags['TxDone']: 360 | # When Tx mode is requested and data is send out, TxDone is triggered. 361 | if self.pkt_type == self.PKT_TYPE['REQ']: 362 | # Sender's REQ Tx will meet this condition 363 | # 1st critical point (CP), mode shifts from Tx to RxCont 364 | self.mode = 'RXCONTINUOUS' 365 | elif self.pkt_type == self.PKT_TYPE['ACK']: 366 | # 3rd CP: Receiver's ACK response will meet this condition 367 | # Since we are doing two-way communication, now the receiver should be freed. 368 | #self.mode = 'STANDBY' 369 | self.is_available = True # Free the receiver 370 | elif self.pkt_type == self.PKT_TYPE['BRD']: 371 | self.is_available = True # Free the sender after broadcasting 372 | self.after_TxDone(None) 373 | 374 | elif irq_flags & self.IrqFlags['RxDone']: 375 | packet, SNR, RSSI = self.read_fifo() # read fifo 376 | if irq_flags & self.IrqFlags['PayloadCrcError']: 377 | print('[PayloadCrcError]', packet) 378 | else: 379 | if len(packet) < self.header_size: 380 | print(packet, SNR, RSSI) 381 | return 382 | header, data = packet[:self.header_size], packet[self.header_size:] # extract header 383 | src_id, dst_id, pkt_id, pkt_type = struct.unpack(self.header_fmt, header) # parse header 384 | if self.debug: print('[Debug] Rx',pkt_type) 385 | if pkt_type == self.PKT_TYPE['REQ']: # REQ Received 386 | # Receiver will get a REQ packet from the sender and meet this condition 387 | if dst_id == self.src_id: 388 | # 2nd CP 389 | self.mode = 'STANDBY' 390 | self.send(dst_id=src_id, pkt_id=pkt_id, pkt_type=self.PKT_TYPE['ACK'], msg='') # This is an ack message 391 | #print("We received a REQ packet and its dst_id matches our src_id. We are going to acknowledge it.") 392 | self.req_packet_handler(None, data, SNR, RSSI) 393 | if self.debug: print("[RxDone] Right REQ receiver") 394 | else: 395 | #self.req_packet_handler(None, data, SNR, RSSI) 396 | # Shifting from 'RXCONTINUOUS' to 'RXCONTINUOUS' is not needed but we need reset IRQ 397 | self.mode = 'RXCONTINUOUS' 398 | if self.debug: print("[RxDone] Wrong REQ receiver") # We received a REQ packet but its dst_id does not match our src_id. 399 | # We are not going to acknowledge it but we still display its content. 400 | elif pkt_type == self.PKT_TYPE['ACK']: # ACK Received 401 | if pkt_id == self.pkt_id: 402 | # 4th CP: The right sender get an ACK packet from the receiver and meet this condition 403 | self.pkt_id = 0 # clear pkt_id so waiting in send function ends 404 | self.mode = 'STANDBY' # The sender has got the ACK packet so we shift way from RxCont mode. 405 | self.is_available = True # Free the sender 406 | if self.debug: print("[RxDone] Right ACK receiver") # REQ is ACKed 407 | else: 408 | #print("We are not the original sender although we have received an ACK response. Ignore it.") 409 | self.mode = 'RXCONTINUOUS' 410 | if self.debug: print("[RxDone] Wrong ACK receiver") 411 | elif pkt_type == self.PKT_TYPE['BRD']: 412 | # BRD Received by the receiver. Do nothing. 413 | self.brd_packet_handler(None, data, SNR, RSSI) 414 | #print("We received a BRD packet whose sender does not expect an acknowledgement.") 415 | self.mode = 'RXCONTINUOUS' 416 | if self.debug: print("[RxDone] BRD receiver") 417 | else: 418 | print('[Error]', packet, SNR, RSSI) 419 | 420 | elif irq_flags & self.IrqFlags['FhssChangeChannel']: 421 | self.set_freq() 422 | else: 423 | for i, j in self.IrqFlags.items(): 424 | if irq_flags & j: 425 | print('[Sth went wrong]', i) 426 | 427 | def req_packet_handler(self, data, SNR, RSSI): 428 | pass 429 | 430 | def brd_packet_handler(self, data, SNR, RSSI): 431 | pass 432 | 433 | def after_TxDone(self, _): 434 | pass 435 | -------------------------------------------------------------------------------- /misc/airtime_calculator.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xg590/SX1276/6e552d7881bf4e92ffa798a48b0dc589bf35598a/misc/airtime_calculator.jpg -------------------------------------------------------------------------------- /misc/airtime_calculator.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xg590/SX1276/6e552d7881bf4e92ffa798a48b0dc589bf35598a/misc/airtime_calculator.zip -------------------------------------------------------------------------------- /misc/console_output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xg590/SX1276/6e552d7881bf4e92ffa798a48b0dc589bf35598a/misc/console_output.png -------------------------------------------------------------------------------- /misc/fhss.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xg590/SX1276/6e552d7881bf4e92ffa798a48b0dc589bf35598a/misc/fhss.jpg -------------------------------------------------------------------------------- /misc/issue/8/setup.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xg590/SX1276/6e552d7881bf4e92ffa798a48b0dc589bf35598a/misc/issue/8/setup.jpg -------------------------------------------------------------------------------- /misc/receiver.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "0cfb6a30", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "name": "stdout", 11 | "output_type": "stream", 12 | "text": [ 13 | "\n", 14 | "WebREPL connected\n", 15 | ">>> \n", 16 | "6\n", 17 | "paste mode; Ctrl-C to cancel, Ctrl-D to finish\n", 18 | "=== from machine import Pin\n", 19 | "=== import time, urandom as random\n", 20 | "=== from lora import SX1276\n", 21 | "=== \n", 22 | "=== # Heltec WiFi LoRa 32 V2\n", 23 | "=== LoRa_MISO_Pin = 19\n", 24 | "=== LoRa_MOSI_Pin = 27\n", 25 | "=== LoRa_SCK_Pin = 5\n", 26 | "=== LoRa_CS_Pin = 18\n", 27 | "=== LoRa_RST_Pin = 14\n", 28 | "=== LoRa_DIO0_Pin = 26\n", 29 | "=== LoRa_DIO1_Pin = 35\n", 30 | "=== LoRa_DIO2_Pin = 34\n", 31 | "=== SPI_CH = 1\n", 32 | "=== \n", 33 | "=== random.seed(11)\n", 34 | "=== channels2Hopping = [914_000_000+200_000 * random.randint(0,10) for i in range(128)] # Both sender and receiver need to know the sequence of frequences they are hopping on before the first hopping operation.\n", 35 | "=== \n", 36 | "=== LoRa_id = 0\n", 37 | "=== lora = SX1276(LoRa_RST_Pin, LoRa_CS_Pin, SPI_CH, LoRa_SCK_Pin, LoRa_MOSI_Pin, LoRa_MISO_Pin,\n", 38 | "=== LoRa_DIO0_Pin, LoRa_DIO1_Pin, LoRa_id, channels2Hopping, debug=False)\n", 39 | "=== \n", 40 | "=== def get_payload(self, data, SNR, RSSI):\n", 41 | "=== global received_payload\n", 42 | "=== received_payload = data\n", 43 | "=== \n", 44 | "=== lora.req_packet_handler = get_payload\n", 45 | "=== lora.brd_packet_handler = lambda self, data, SNR, RSSI: print(\"[BRD]\", data)\n", 46 | "=== \n", 47 | "=== ###########################################\n", 48 | "=== # #\n", 49 | "=== # Prepare to receive first REQ packet #\n", 50 | "=== # #\n", 51 | "=== ###########################################\n", 52 | "=== \n", 53 | "=== received_payload = None\n", 54 | "=== lora.mode = 'RXCONTINUOUS'\n", 55 | "=== while not lora.is_available:\n", 56 | "=== time.sleep(1)\n", 57 | "=== print(\"[Note] We will see this line after receiver ACKed the first REQ packet\")\n", 58 | "=== \n", 59 | "=== ######################################################################\n", 60 | "=== # #\n", 61 | "=== # if we receive the hello packet correctly, we reply it with Hi. #\n", 62 | "=== # #\n", 63 | "=== ######################################################################\n", 64 | "=== # if we fail, nothing will go further\n", 65 | "=== print('[Received]', received_payload)\n", 66 | "=== if received_payload[-6:] != b'Hello~': raise\n", 67 | "=== \n", 68 | "=== payload = str(random.randint(100,65536))+\") Hi ~ I have received your hello\" \n", 69 | "=== lora.send(dst_id=1, msg=payload, pkt_type=lora.PKT_TYPE['REQ'])\n", 70 | "=== print('[Sending]', payload)\n", 71 | "=== while not lora.is_available: # Stop if our reply got acknowledged. \n", 72 | "=== time.sleep(1)\n", 73 | "=== \n", 74 | "=== ##########################################\n", 75 | "=== # #\n", 76 | "=== # Prepare to receive two BRD packets #\n", 77 | "=== # #\n", 78 | "=== ##########################################\n", 79 | "=== \n", 80 | "=== received_payload = None\n", 81 | "=== lora.mode = 'RXCONTINUOUS'\n", 82 | "=== \n", 83 | "=== while not lora.is_available:\n", 84 | "=== #print(\"waiting\")\n", 85 | "=== time.sleep(1)\n", 86 | "=== \n", 87 | "=== print(\"[Note] This line will not be reached because BRD is not two-way communication\")\n", 88 | "=== \n", 89 | "F[Note] We will see this line after receiver ACKed the first REQ packet\n", 90 | "[Received] b'15267) Hello~'\n", 91 | "[Sending] &15267) Hi ~ I have received your hello\n", 92 | "[BRD] b'28805) This long BRD packet will be received'\n", 93 | "[BRD] b'10231) This long BRD packet will also be received even though a wrong dst_id is specified. It is BRD, dst_id does not matter~'\n" 94 | ] 95 | } 96 | ], 97 | "source": [ 98 | "webrepl_host_ip=\"192.168.xxx.142\"\n", 99 | "import sys\n", 100 | "sys.path.append(\"/home/a/pyWebREPL-1.2\") # https://github.com/xg590/pyWebREPL\n", 101 | "from pyWebREPL import WEBREPL\n", 102 | "\n", 103 | "webrepl = WEBREPL(host=webrepl_host_ip, password='123456')\n", 104 | "\n", 105 | "webrepl.send('''\n", 106 | "from machine import Pin\n", 107 | "import time, urandom as random\n", 108 | "from lora import SX1276\n", 109 | "\n", 110 | "# Heltec WiFi LoRa 32 V2\n", 111 | "LoRa_MISO_Pin = 19\n", 112 | "LoRa_MOSI_Pin = 27\n", 113 | "LoRa_SCK_Pin = 5\n", 114 | "LoRa_CS_Pin = 18\n", 115 | "LoRa_RST_Pin = 14\n", 116 | "LoRa_DIO0_Pin = 26\n", 117 | "LoRa_DIO1_Pin = 35\n", 118 | "LoRa_DIO2_Pin = 34\n", 119 | "SPI_CH = 1\n", 120 | "\n", 121 | "random.seed(11)\n", 122 | "channels2Hopping = [914_000_000+200_000 * random.randint(0,10) for i in range(128)] # Both sender and receiver need to know the sequence of frequences they are hopping on before the first hopping operation.\n", 123 | "\n", 124 | "LoRa_id = 0\n", 125 | "lora = SX1276(LoRa_RST_Pin, LoRa_CS_Pin, SPI_CH, LoRa_SCK_Pin, LoRa_MOSI_Pin, LoRa_MISO_Pin,\n", 126 | " LoRa_DIO0_Pin, LoRa_DIO1_Pin, LoRa_id, channels2Hopping, debug=False)\n", 127 | "\n", 128 | "def get_payload(self, data, SNR, RSSI):\n", 129 | " global received_payload\n", 130 | " received_payload = data\n", 131 | "\n", 132 | "lora.req_packet_handler = get_payload\n", 133 | "lora.brd_packet_handler = lambda self, data, SNR, RSSI: print(\"[BRD]\", data)\n", 134 | "\n", 135 | "###########################################\n", 136 | "# #\n", 137 | "# Prepare to receive first REQ packet #\n", 138 | "# #\n", 139 | "###########################################\n", 140 | "\n", 141 | "received_payload = None\n", 142 | "lora.mode = 'RXCONTINUOUS'\n", 143 | "while not lora.is_available:\n", 144 | " time.sleep(1)\n", 145 | "print(\"[Note] We will see this line after receiver ACKed the first REQ packet\")\n", 146 | "\n", 147 | "######################################################################\n", 148 | "# #\n", 149 | "# if we receive the hello packet correctly, we reply it with Hi. #\n", 150 | "# #\n", 151 | "######################################################################\n", 152 | "# if we fail, nothing will go further\n", 153 | "print('[Received]', received_payload)\n", 154 | "if received_payload[-6:] != b'Hello~': raise\n", 155 | "\n", 156 | "payload = str(random.randint(100,65536))+\") Hi ~ I have received your hello\" \n", 157 | "lora.send(dst_id=1, msg=payload, pkt_type=lora.PKT_TYPE['REQ'])\n", 158 | "print('[Sending]', payload)\n", 159 | "while not lora.is_available: # Stop if our reply got acknowledged. \n", 160 | " time.sleep(1)\n", 161 | "\n", 162 | "##########################################\n", 163 | "# #\n", 164 | "# Prepare to receive two BRD packets #\n", 165 | "# #\n", 166 | "##########################################\n", 167 | "\n", 168 | "received_payload = None\n", 169 | "lora.mode = 'RXCONTINUOUS'\n", 170 | "\n", 171 | "while not lora.is_available:\n", 172 | " #print(\"waiting\")\n", 173 | " time.sleep(1)\n", 174 | "\n", 175 | "print(\"[Note] This line will not be reached because BRD is not two-way communication\")\n", 176 | "''')\n", 177 | "print(webrepl.recv())\n", 178 | "webrepl.close()" 179 | ] 180 | } 181 | ], 182 | "metadata": { 183 | "kernelspec": { 184 | "display_name": "Python 3 (ipykernel)", 185 | "language": "python", 186 | "name": "python3" 187 | }, 188 | "language_info": { 189 | "codemirror_mode": { 190 | "name": "ipython", 191 | "version": 3 192 | }, 193 | "file_extension": ".py", 194 | "mimetype": "text/x-python", 195 | "name": "python", 196 | "nbconvert_exporter": "python", 197 | "pygments_lexer": "ipython3", 198 | "version": "3.10.6" 199 | } 200 | }, 201 | "nbformat": 4, 202 | "nbformat_minor": 5 203 | } 204 | -------------------------------------------------------------------------------- /misc/sender.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "794f3696", 7 | "metadata": {}, 8 | "outputs": [ 9 | { 10 | "name": "stdout", 11 | "output_type": "stream", 12 | "text": [ 13 | "\n", 14 | "WebREPL connected\n", 15 | ">>> \n", 16 | "6\n", 17 | "paste mode; Ctrl-C to cancel, Ctrl-D to finish\n", 18 | "=== from machine import Pin\n", 19 | "=== import time, urandom as random\n", 20 | "=== from lora import SX1276\n", 21 | "=== \n", 22 | "=== # Heltec WiFi LoRa 32 V2\n", 23 | "=== LoRa_MISO_Pin = 19\n", 24 | "=== LoRa_MOSI_Pin = 27\n", 25 | "=== LoRa_SCK_Pin = 5\n", 26 | "=== LoRa_CS_Pin = 18\n", 27 | "=== LoRa_RST_Pin = 14\n", 28 | "=== LoRa_DIO0_Pin = 26\n", 29 | "=== LoRa_DIO1_Pin = 35\n", 30 | "=== LoRa_DIO2_Pin = 34\n", 31 | "=== SPI_CH = 1\n", 32 | "=== \n", 33 | "=== random.seed(11)\n", 34 | "=== channels2Hopping = [914_000_000+200_000 * random.randint(0,10) for i in range(128)] # 914~916 MHz\n", 35 | "=== \n", 36 | "=== LoRa_id = 1\n", 37 | "=== lora = SX1276(LoRa_RST_Pin, LoRa_CS_Pin, SPI_CH, LoRa_SCK_Pin, LoRa_MOSI_Pin, LoRa_MISO_Pin,\n", 38 | "=== LoRa_DIO0_Pin, LoRa_DIO1_Pin, LoRa_id, channels2Hopping, debug=False)\n", 39 | "=== \n", 40 | "=== def get_payload(self, data, SNR, RSSI):\n", 41 | "=== global received_payload\n", 42 | "=== received_payload = data\n", 43 | "=== \n", 44 | "=== lora.req_packet_handler = get_payload\n", 45 | "=== \n", 46 | "=== ###########################################\n", 47 | "=== # #\n", 48 | "=== # First REQ packet #\n", 49 | "=== # #\n", 50 | "=== ###########################################\n", 51 | "=== \n", 52 | "=== payload = str(random.randint(100,65536))+\") Hello~\"\n", 53 | "=== print('[Sending]', payload)\n", 54 | "=== lora.send(dst_id=0, msg=payload, pkt_type=lora.PKT_TYPE['REQ']) # Sender's lora_id is 1 and receiver's is 0\n", 55 | "=== while not lora.is_available: time.sleep(1)\n", 56 | "=== \n", 57 | "=== #####################################################\n", 58 | "=== # #\n", 59 | "=== # Going to receive a Hi. Two way communication~ #\n", 60 | "=== # #\n", 61 | "=== #####################################################\n", 62 | "=== \n", 63 | "=== received_payload = None\n", 64 | "=== lora.mode = 'RXCONTINUOUS'\n", 65 | "=== \n", 66 | "=== while not lora.is_available: \n", 67 | "=== time.sleep(1)\n", 68 | "=== \n", 69 | "=== print('[Received] What we receive from the receiver is:', received_payload)\n", 70 | "=== \n", 71 | "=== #######################################################\n", 72 | "=== # #\n", 73 | "=== # Send a REQ packet but specify a wrong receiver #\n", 74 | "=== # #\n", 75 | "=== #######################################################\n", 76 | "=== \n", 77 | "=== payload = str(random.randint(100,65536))+\") You will not receive this packet because we specified a wrong dst_id\"\n", 78 | "=== print('[Sending]', payload)\n", 79 | "=== lora.send(dst_id=3, msg=payload, pkt_type=lora.PKT_TYPE['REQ']) \n", 80 | "=== \n", 81 | "=== for i in range(10):\n", 82 | "=== if lora.is_available: break\n", 83 | "=== time.sleep(1)\n", 84 | "=== else:\n", 85 | "=== print(\"[Note] you will see this line because lora.is_available is always false\")\n", 86 | "=== \n", 87 | "=== ############################\n", 88 | "=== # #\n", 89 | "=== # Send two BRD packets #\n", 90 | "=== # #\n", 91 | "=== ############################\n", 92 | "=== \n", 93 | "=== time.sleep(10)\n", 94 | "=== payload = str(random.randint(100,65536))+\") This long BRD packet will be received\" # Broadcast a large packet so many hops are generated~\n", 95 | "=== print('[Sending]', payload)\n", 96 | "=== lora.send(dst_id=0, msg=payload, pkt_type=lora.PKT_TYPE['BRD']) # A broadcast request. Do not expect respond. \n", 97 | "=== \n", 98 | "=== time.sleep(10)\n", 99 | "=== payload = str(random.randint(100,65536))+\") This long BRD packet will also be received even though a wrong dst_id is specified. It is BRD, dst_id does not matter~\" \n", 100 | "=== print('[Sending]', payload)\n", 101 | "=== lora.send(dst_id=3, msg=payload, pkt_type=lora.PKT_TYPE['BRD']) # A broadcast request. Do not expect respond.\n", 102 | "=== \n", 103 | "[Sending] \n", 104 | "15267) Hello~\n", 105 | "0[Received] What we receive from the receiver is: b'15267) Hi ~ I have received your hello'\n", 106 | "[Sending] K56627) You will not receive this packet because we specified a wrong dst_id\n", 107 | "G[Note] you will see this line because lora.is_available is always false\n", 108 | "[Sending] ,28805) This long BRD packet will be received\n", 109 | "[Sending] }10231) This long BRD packet will also be received even though a wrong dst_id is specified. It is BRD, dst_id does not matter~\n", 110 | ">>> \n" 111 | ] 112 | } 113 | ], 114 | "source": [ 115 | "webrepl_host_ip=\"192.168.xxx.164\"\n", 116 | "import sys\n", 117 | "sys.path.append(\"/home/a/pyWebREPL-1.2\") # https://github.com/xg590/pyWebREPL\n", 118 | "from pyWebREPL import WEBREPL\n", 119 | "\n", 120 | "webrepl = WEBREPL(host=webrepl_host_ip, password='123456')\n", 121 | "webrepl.send('''\n", 122 | "from machine import Pin\n", 123 | "import time, urandom as random\n", 124 | "from lora import SX1276\n", 125 | "\n", 126 | "# Heltec WiFi LoRa 32 V2\n", 127 | "LoRa_MISO_Pin = 19\n", 128 | "LoRa_MOSI_Pin = 27\n", 129 | "LoRa_SCK_Pin = 5\n", 130 | "LoRa_CS_Pin = 18\n", 131 | "LoRa_RST_Pin = 14\n", 132 | "LoRa_DIO0_Pin = 26\n", 133 | "LoRa_DIO1_Pin = 35\n", 134 | "LoRa_DIO2_Pin = 34\n", 135 | "SPI_CH = 1\n", 136 | "\n", 137 | "random.seed(11)\n", 138 | "channels2Hopping = [914_000_000+200_000 * random.randint(0,10) for i in range(128)] # 914~916 MHz\n", 139 | "\n", 140 | "LoRa_id = 1\n", 141 | "lora = SX1276(LoRa_RST_Pin, LoRa_CS_Pin, SPI_CH, LoRa_SCK_Pin, LoRa_MOSI_Pin, LoRa_MISO_Pin,\n", 142 | " LoRa_DIO0_Pin, LoRa_DIO1_Pin, LoRa_id, channels2Hopping, debug=False)\n", 143 | "\n", 144 | "def get_payload(self, data, SNR, RSSI):\n", 145 | " global received_payload\n", 146 | " received_payload = data\n", 147 | "\n", 148 | "lora.req_packet_handler = get_payload\n", 149 | "\n", 150 | "###########################################\n", 151 | "# #\n", 152 | "# First REQ packet #\n", 153 | "# #\n", 154 | "###########################################\n", 155 | "\n", 156 | "payload = str(random.randint(100,65536))+\") Hello~\"\n", 157 | "print('[Sending]', payload)\n", 158 | "lora.send(dst_id=0, msg=payload, pkt_type=lora.PKT_TYPE['REQ']) # Sender's lora_id is 1 and receiver's is 0\n", 159 | "while not lora.is_available: time.sleep(1)\n", 160 | "\n", 161 | "#####################################################\n", 162 | "# #\n", 163 | "# Going to receive a Hi. Two way communication~ #\n", 164 | "# #\n", 165 | "#####################################################\n", 166 | "\n", 167 | "received_payload = None\n", 168 | "lora.mode = 'RXCONTINUOUS'\n", 169 | "\n", 170 | "while not lora.is_available: \n", 171 | " time.sleep(1)\n", 172 | "\n", 173 | "print('[Received] What we receive from the receiver is:', received_payload)\n", 174 | "\n", 175 | "#######################################################\n", 176 | "# #\n", 177 | "# Send a REQ packet but specify a wrong receiver #\n", 178 | "# #\n", 179 | "#######################################################\n", 180 | "\n", 181 | "payload = str(random.randint(100,65536))+\") You will not receive this packet because we specified a wrong dst_id\"\n", 182 | "print('[Sending]', payload)\n", 183 | "lora.send(dst_id=3, msg=payload, pkt_type=lora.PKT_TYPE['REQ']) \n", 184 | "\n", 185 | "for i in range(10):\n", 186 | " if lora.is_available: break\n", 187 | " time.sleep(1)\n", 188 | "else:\n", 189 | " print(\"[Note] you will see this line because lora.is_available is always false\")\n", 190 | "\n", 191 | "############################\n", 192 | "# #\n", 193 | "# Send two BRD packets #\n", 194 | "# #\n", 195 | "############################\n", 196 | "\n", 197 | "time.sleep(10)\n", 198 | "payload = str(random.randint(100,65536))+\") This long BRD packet will be received\" # Broadcast a large packet so many hops are generated~\n", 199 | "print('[Sending]', payload)\n", 200 | "lora.send(dst_id=0, msg=payload, pkt_type=lora.PKT_TYPE['BRD']) # A broadcast request. Do not expect respond. \n", 201 | "\n", 202 | "time.sleep(10)\n", 203 | "payload = str(random.randint(100,65536))+\") This long BRD packet will also be received even though a wrong dst_id is specified. It is BRD, dst_id does not matter~\" \n", 204 | "print('[Sending]', payload)\n", 205 | "lora.send(dst_id=3, msg=payload, pkt_type=lora.PKT_TYPE['BRD']) # A broadcast request. Do not expect respond.\n", 206 | " \n", 207 | "\n", 208 | "''')\n", 209 | "print(webrepl.recv())\n", 210 | "webrepl.close()" 211 | ] 212 | } 213 | ], 214 | "metadata": { 215 | "kernelspec": { 216 | "display_name": "Python 3 (ipykernel)", 217 | "language": "python", 218 | "name": "python3" 219 | }, 220 | "language_info": { 221 | "codemirror_mode": { 222 | "name": "ipython", 223 | "version": 3 224 | }, 225 | "file_extension": ".py", 226 | "mimetype": "text/x-python", 227 | "name": "python", 228 | "nbconvert_exporter": "python", 229 | "pygments_lexer": "ipython3", 230 | "version": "3.10.6" 231 | } 232 | }, 233 | "nbformat": 4, 234 | "nbformat_minor": 5 235 | } 236 | -------------------------------------------------------------------------------- /receiver/lora.py: -------------------------------------------------------------------------------- 1 | ../lora.py -------------------------------------------------------------------------------- /receiver/receiver.py: -------------------------------------------------------------------------------- 1 | from machine import Pin 2 | import time, urandom as random 3 | from lora import SX1276 4 | 5 | # Heltec WiFi LoRa 32 V2 6 | LoRa_MISO_Pin = 19 7 | LoRa_MOSI_Pin = 27 8 | LoRa_SCK_Pin = 5 9 | LoRa_CS_Pin = 18 10 | LoRa_RST_Pin = 14 11 | LoRa_DIO0_Pin = 26 12 | LoRa_DIO1_Pin = 35 13 | LoRa_DIO2_Pin = 34 14 | SPI_CH = 1 15 | 16 | random.seed(11) 17 | channels2Hopping = [914_000_000+200_000 * random.randint(0,10) for i in range(128)] # Both sender and receiver need to know the sequence of frequences they are hopping on before the first hopping operation. 18 | 19 | LoRa_id = 0 20 | lora = SX1276(LoRa_RST_Pin, LoRa_CS_Pin, SPI_CH, LoRa_SCK_Pin, LoRa_MOSI_Pin, LoRa_MISO_Pin, 21 | LoRa_DIO0_Pin, LoRa_DIO1_Pin, LoRa_id, channels2Hopping, debug=False) 22 | 23 | def get_payload(self, data, SNR, RSSI): 24 | global received_payload 25 | received_payload = data 26 | 27 | lora.req_packet_handler = get_payload 28 | lora.brd_packet_handler = lambda self, data, SNR, RSSI: print("[BRD]", data) 29 | 30 | ########################################### 31 | # # 32 | # Prepare to receive first REQ packet # 33 | # # 34 | ########################################### 35 | 36 | received_payload = None 37 | lora.mode = 'RXCONTINUOUS' 38 | while not lora.is_available: 39 | time.sleep(1) 40 | print("[Note] We will see this line after receiver ACKed the first REQ packet with an ACK packet. And the receiver will stop listening, become a new sender, and send a REQ packet to the old sender (new receiver).") 41 | 42 | ###################################################################### 43 | # # 44 | # if we receive the hello packet correctly, we reply it with Hi. # 45 | # # 46 | ###################################################################### 47 | # if we fail, nothing will go further 48 | print('[Received]', received_payload) 49 | if received_payload[-6:] != b'Hello~': raise 50 | 51 | payload = str(random.randint(100,65536))+") Hi ~ I have received your hello" 52 | lora.send(dst_id=1, msg=payload, pkt_type=lora.PKT_TYPE['REQ']) 53 | print('[Sending]', payload) 54 | while not lora.is_available: # Stop if our reply got acknowledged. 55 | time.sleep(1) 56 | 57 | ########################################## 58 | # # 59 | # Prepare to receive two BRD packets # 60 | # # 61 | ########################################## 62 | 63 | received_payload = None 64 | lora.mode = 'RXCONTINUOUS' 65 | 66 | while not lora.is_available: 67 | #print("waiting") 68 | time.sleep(1) 69 | 70 | print("[Note] This line will not be reached because BRD is not two-way communication. The receiver will not stop listening") -------------------------------------------------------------------------------- /sender/lora.py: -------------------------------------------------------------------------------- 1 | ../lora.py -------------------------------------------------------------------------------- /sender/sender.py: -------------------------------------------------------------------------------- 1 | from machine import Pin 2 | import time, urandom as random 3 | from lora import SX1276 4 | 5 | # Heltec WiFi LoRa 32 V2 6 | LoRa_MISO_Pin = 19 7 | LoRa_MOSI_Pin = 27 8 | LoRa_SCK_Pin = 5 9 | LoRa_CS_Pin = 18 10 | LoRa_RST_Pin = 14 11 | LoRa_DIO0_Pin = 26 12 | LoRa_DIO1_Pin = 35 13 | LoRa_DIO2_Pin = 34 14 | SPI_CH = 1 15 | 16 | random.seed(11) 17 | channels2Hopping = [914_000_000+200_000 * random.randint(0,10) for i in range(128)] # 914~916 MHz 18 | 19 | LoRa_id = 1 20 | lora = SX1276(LoRa_RST_Pin, LoRa_CS_Pin, SPI_CH, LoRa_SCK_Pin, LoRa_MOSI_Pin, LoRa_MISO_Pin, 21 | LoRa_DIO0_Pin, LoRa_DIO1_Pin, LoRa_id, channels2Hopping, debug=False) 22 | 23 | def get_payload(self, data, SNR, RSSI): 24 | global received_payload 25 | received_payload = data 26 | 27 | lora.req_packet_handler = get_payload 28 | 29 | ########################################### 30 | # # 31 | # First REQ packet # 32 | # # 33 | ########################################### 34 | 35 | payload = str(random.randint(100,65536))+") Hello~" 36 | print('[Sending]', payload) 37 | lora.send(dst_id=0, msg=payload, pkt_type=lora.PKT_TYPE['REQ']) # Sender's lora_id is 1 and receiver's is 0 38 | while not lora.is_available: time.sleep(1) 39 | 40 | ##################################################### 41 | # # 42 | # Going to receive a Hi. Two way communication~ # 43 | # # 44 | ##################################################### 45 | 46 | received_payload = None 47 | lora.mode = 'RXCONTINUOUS' 48 | 49 | while not lora.is_available: 50 | time.sleep(1) 51 | 52 | print('[Received] What we receive from the receiver is:', received_payload) 53 | 54 | ####################################################### 55 | # # 56 | # Send a REQ packet but specify a wrong receiver # 57 | # # 58 | ####################################################### 59 | 60 | payload = str(random.randint(100,65536))+") You will not receive this packet because we specified a wrong dst_id" 61 | print('[Sending]', payload) 62 | lora.send(dst_id=3, msg=payload, pkt_type=lora.PKT_TYPE['REQ'], timeout=10, retry=3, debug=True) 63 | 64 | for i in range(10): 65 | if lora.is_available: break 66 | time.sleep(1) 67 | else: 68 | print("[Note] you will see this line because lora.is_available is always false") 69 | 70 | ############################ 71 | # # 72 | # Send two BRD packets # 73 | # # 74 | ############################ 75 | 76 | time.sleep(10) 77 | payload = str(random.randint(100,65536))+") This long BRD packet will be received" # Broadcast a large packet so many hops are generated~ 78 | print('[Sending]', payload) 79 | lora.send(dst_id=0, msg=payload, pkt_type=lora.PKT_TYPE['BRD']) # A broadcast request. Do not expect respond. 80 | 81 | time.sleep(10) 82 | payload = str(random.randint(100,65536))+") This long BRD packet will also be received even though a wrong dst_id is specified. It is BRD, dst_id does not matter~" 83 | print('[Sending]', payload) 84 | lora.send(dst_id=3, msg=payload, pkt_type=lora.PKT_TYPE['BRD']) # A broadcast request. Do not expect respond. 85 | --------------------------------------------------------------------------------