code.py
 1  # SPDX-FileCopyrightText: 2019 Brent Rubell for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """
 6  lora_device.py
 7  
 8  CircuitPython LoRa Device w/BME280
 9  """
10  import time
11  import busio
12  import digitalio
13  import board
14  
15  # Import LoRa Library
16  import adafruit_rfm9x
17  
18  # Import BME280 Sensor Library
19  import adafruit_bme280
20  
21  # Device ID
22  FEATHER_ID = 0x01
23  
24  # Delay between sending radio data, in minutes.
25  SENSOR_SEND_DELAY = 1
26  
27  # Create library object using our Bus I2C port
28  i2c = busio.I2C(board.SCL, board.SDA)
29  bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c)
30  
31  # Define radio frequency, MUST match gateway frequency.
32  RADIO_FREQ_MHZ = 905.5
33  
34  # Define pins connected to the chip, use these if wiring up the breakout according to the guide:
35  # pylint: disable=c-extension-no-member
36  CS = digitalio.DigitalInOut(board.RFM9X_CS)
37  # pylint: disable=c-extension-no-member
38  RESET = digitalio.DigitalInOut(board.RFM9X_RST)
39  
40  # Define the onboard LED
41  LED = digitalio.DigitalInOut(board.D13)
42  LED.direction = digitalio.Direction.OUTPUT
43  
44  # Initialize SPI bus.
45  spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
46  
47  # Initialze RFM radio
48  rfm9x = adafruit_rfm9x.RFM9x(spi, CS, RESET, RADIO_FREQ_MHZ)
49  
50  # Set transmit power to max
51  rfm9x.tx_power = 23
52  
53  # sensor data
54  bme280_data = bytearray(8)
55  
56  while True:
57      # Get sensor readings
58      temp_val = int(bme280.temperature * 100)
59      print("\nTemperature: %0.1f C" % bme280.temperature)
60      humid_val = int(bme280.humidity * 100)
61      print("Humidity: %0.1f %%" % bme280.humidity)
62      pres_val = int(bme280.pressure * 100)
63      print("Pressure: %0.1f hPa" % bme280.pressure)
64  
65      # Build packet with float data and headers
66  
67      # packet header with feather node ID
68      bme280_data[0] = FEATHER_ID
69      # Temperature data
70      bme280_data[1] = (temp_val >> 8) & 0xff
71      bme280_data[2] = temp_val & 0xff
72  
73      # Humid data
74      bme280_data[3] = (humid_val >> 8) & 0xff
75      bme280_data[4] = humid_val & 0xff
76  
77      # Pressure data
78      bme280_data[5] = (pres_val >> 16) & 0xff
79      bme280_data[6] = (pres_val >> 8) & 0xff
80      bme280_data[7] = pres_val & 0xff
81  
82      # Convert bytearray to bytes
83      bme280_data_bytes = bytes(bme280_data)
84      # Send the packet data
85      print('Sending data...')
86      LED.value = True
87      rfm9x.send(bme280_data_bytes)
88      print('Sent data!')
89      LED.value = False
90  
91      # Wait to send the packet again
92      time.sleep(SENSOR_SEND_DELAY * 60)