Search code examples
pythoniotmicropythonraspberry-pi-picolora

How to check out if SX1276 module is working properly?


I want to find out if my LoRa module is working properly with Raspberry Pi Pico W.

I am using an SX1276 module, a Raspberry Pi Pico W and this is the connection scheme:

Raspberry Pi Pico --------------> LoRa SX1276
SCK (GP10) -------------------> SCK
MOSI (GP11) ------------------> MOSI
MISO (GP8) -------------------> MISO
GP1 ----------------------------> Reset
GND ----------------------------> GND

I asked ChatGPT the same question and it gave me some code ideas. The current code state is:

import machine
import time
from machine import Pin
from machine import SPI

# SPI initialization
spi = SPI(1, sck=Pin(10), mosi=Pin(11), miso=Pin(8))

# Reset initialization
rst = Pin(1, Pin.OUT)

# LoRa module boot up
rst.value(0)
time.sleep(0.01)
rst.value(1)

# Waiting for LoRa initialization
time.sleep(0.5)

# The function responsible for sending data and receiving responses from the LoRa module
def send_recv(data, length):
    rx_buf = bytearray(length)
    print(rx_buf)
    spi.readinto(rx_buf, length)
    return rx_buf

# A function to send a command and receive a response
def get_version():
    tx_buf = bytearray([0x42, 0x00, 0x00, 0x00])
    rx_buf = send_recv(tx_buf, 4)
    return rx_buf[3]

# Download the version of the LoRa module
version = get_version()
print('LoRa module version: ', version)

if version == 0x12:
    print('LoRa module working!')
else:
    print('LoRa module, not working properly')

I am also not sure about the correctness of this MicroPython code.

When I run this script, the output is:

>>> %Run -c $EDITOR_CONTENT
bytearray(b'\x00\x00\x00\x00')
LoRa module version:  0
LoRa module, not working properly

I am expecting something more than an empty bytearray...


Solution

  • You should REALLY use a library instead of hacking your own... As it is now your code has a few issues, the main one being that you are using spi.readinto wrong.

    rxdata = bytearray(1)
    try:
      cs(0) # Select peripheral.
      spi.readinto(rxdata, 0x42) # Read **1** byte in place while writing 0x42.
    finally:
      cs(1) # Deselect peripheral.
    

    The version register is one byte, 0x42, and returns one byte, 0x12. Not four each.

    What is this cs you ask? Well yeah, you need a Chip Select pin, so that the LoRa module knows you are talking to it... With your current code you shouldn't be expecting anything but an empty bytearray, since you're not talking to any device.

    No, but really, use a library...