def initialize_sensors(): print("\n--- Sensors initializing...") try: #For a raspberry pi, for example, to set up pins 4 and 5, you would add #GPIO.setmode(GPIO.BCM) #GPIO.setup(4, GPIO.IN) #GPIO.setup(5, GPIO.IN) # Turn off the hearbeat LED pycom.heartbeat(False) # Sync the clock! print("Syncing clock...") rtc.ntp_sync("pool.ntp.org") time.sleep(5) print("Clock set to: " + getCurrentTimestampString()); print("--- Sensors initialized!") # In short, in this example, by default, # this function is called but doesn't do anything (it's just a placeholder) except Exception as ex: # Log any error, if it occurs #print(str(datetime.datetime.now()) + " Error when initializing sensors: " + str(ex)) print(getCurrentTimestampString() + " Error when initializing sensors: " + str(ex))
import pycom import micropython import network import machine import time pycom.heartbeat(False) pycom.rgbled(0x000000) while True: # https://forum.pycom.io/topic/226/lopy-adcs adc = machine.ADC() apin = adc.channel(pin='P16') value = apin.value() # read value, 0-4095 ris=str(value) print(ris) #---------------------------------------------- # write on file f = open('/flash/battery_level.txt', 'a+') f.write("batt[{}]\n".format(ris)) f.close() pycom.rgbled(0xff0000) time.sleep(1) pycom.rgbled(0x00ff00) time.sleep(1) #----------------------------------------------
import time import pycom import ubinascii from network import LoRa pycom.heartbeat(False) #Disable pycom rgbled heartbeat function # Initialise LoRa in LORAWAN mode. # Please pick the region that matches where you are using the device: # Asia = LoRa.AS923 # Australia = LoRa.AU915 # Europe = LoRa.EU868 # United States = LoRa.US915 lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # create an OTAA authentication parameters app_eui = ubinascii.unhexlify('70B3D57ED0031434') app_key = ubinascii.unhexlify('7F50EB5FAEF6B8FE857C1D5FA27AFF8B') # join a network using OTAA (Over the Air Activation) lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # wait until the module has joined the network while not lora.has_joined(): time.sleep(2.5) print('Not yet joined...') print('Joined') # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate
import socket import time import ubinascii import struct import pycom from network import LoRa import machine import config # ------------------------------------------------------------------------------ # Enable LED heartbeat pycom.heartbeat(True) # Initialize GPIO adc = machine.ADC() temperature_pin = adc.channel(pin='G31') relay_pin = machine.Pin('G15', mode=machine.Pin.OUT) # Initialize LoRa in LORAWAN mode. lora = LoRa(mode=LoRa.LORAWAN, adr=True) # Welcome message print("[INFO] @ttncat thermostat example for the LoPy"); print("[INFO] DevEUI: %s" % (ubinascii.hexlify(lora.mac()).decode('ascii'))) # ------------------------------------------------------------------------------ # join a network using OTAA (Over the Air Activation)
def __init__(self, brightness): pycom.heartbeat(False) self.brightness = brightness self.saturation = 100
def pled(): pycom.heartbeat(False) pycom.rgbled(0xff00) time.sleep(5) pycom.heartbeat(True)
def onClientDisconnect(self): print("[" + self._name + "]: Client disconnected") pycom.heartbeat(True)
def start(self): """ Starts the LoRaWAN nano gateway. """ pycom.heartbeat(False) self._log('Starting LoRaWAN nano gateway with id: {}', self.id) # # setup WiFi as a station and connect # self.wlan = WLAN(mode=WLAN.STA) # self._connect_to_wifi() # setup LTE CATM1 connection self.lte = LTE(carrier="verizon") self._connect_to_LTE() # get a time sync self._log('Syncing time with {} ...', self.ntp_server) self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period) while not self.rtc.synced(): utime.sleep_ms(50) self._log("RTC NTP sync complete") # get the server IP and create an UDP socket self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1] self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1]) self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP) self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1) self.sock.setblocking(False) # push the first time immediatelly self._push_data(self._make_stat_packet()) # create the alarms self.stat_alarm = Timer.Alarm( handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True) self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True) # start the UDP receive thread self.udp_stop = False _thread.start_new_thread(self._udp_thread, ()) # initialize the LoRa radio in LORA mode self._log('Setting up the LoRa radio at {} Mhz using {}', self._freq_to_float(self.frequency), self.datarate) self.lora = LoRa(mode=LoRa.LORA, frequency=self.frequency, bandwidth=self.bw, sf=self.sf, preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True) # create a raw LoRa socket self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW) self.lora_sock.setblocking(False) self.lora_tx_done = False self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb) self._log('LoRaWAN nano gateway online')
n.send(lecturas) #Envío de las lecturas print("Data Sent, sleeping ...") print('- ' * 20) n.py.setup_int_wake_up(rising=1,falling=0) #Activa la interrupcion por Botón n.py.setup_sleep(sleep_time-ajuste) n.py.go_to_sleep(False) #Dispositivo enviado a Deepsleep elif (py.get_wake_reason() == WAKE_REASON_PUSH_BUTTON): uart = UART(0, 115200) #Se activa la UART os.dupterm(uart) wlan = WLAN() wlan.init(mode=WLAN.AP, ssid='lopy-pysense', auth=(network.WLAN.WPA2,'lopy-pysense'), channel=7,antenna=WLAN.INT_ANT) #Init Wi-Fi server = network.Server() #Init FTP Server print("Device entered into debugging mode") print("Please do not connect to battery") pycom.heartbeat(True) #Se activa el Heartbeat while(1): if py.button_pressed(): print("Resetting") machine.reset() else: #Si viene de Boot o Hard Reset print('Power on or hard reset') sleep_time = 100 #Valor por defecto de sleep_time (Minimo segun Fair Acess Policy TTN) data_rate = 5 pycom.wifi_on_boot(False) # disable WiFi on boot TODO: Intentar en versiones posteriores, da un Core Error. pycom.heartbeat_on_boot(False) try: pycom.nvs_set('sleep_time', sleep_time) #Guarda el valor por defecto de sleep_time en NVRAM pycom.nvs_set('data_rate', data_rate) except (Exception):
# load variables with open('config.json', 'r') as f: config = json.load(f) wifi_ssid = config["wifi_ssid"] wifi_key = config["wifi_key"] mqtt_server = config["mqtt_server"] mqtt_port = config["mqtt_port"] subscribe_key = config["subscribe_key"] publish_key = config["publish_key"] client_id = config["client_id"] channel_name = config["channel_name"] lux_threshold = config["lux_threshold"] meas_frequency = config["meas_frequency"] pycom.heartbeat(False) # disable periodic LED flashing # setup wifi client wlan = WLAN(mode=WLAN.STA) wlan.connect(wifi_ssid, auth=(WLAN.WPA2, wifi_key), timeout=5000) while not wlan.isconnected(): machine.idle() # clock gating to reduce power consumption print("Connected to WiFi\n") pycom.rgbled(0x00FF00) # green LED to confirm wifi connection time.sleep(1) pycom.rgbled(0x000000) #disable LED # create our Pysense instance py = Pysense() # deep sleep mode of the board disables USB
from time import ticks_ms if nvs_get('AlarmSlp') * 1000 < ticks_ms(): runMySense() # reboot from deepsleep except: pass # arrived from power cycle runMySense() # go into REPL mode, wifi On print( "No auto MySense start\nTo start MySense loop (reset config, cleanup nvs):" ) print(" import MySense; MySense.runMe(debug=False,reset=True)") try: from pycom import heartbeat, rgbled from time import sleep heartbeat(False) for x in range(3): rgbled(0xf96015) sleep(0.1) rgbled(0x0) sleep(0.1) rgbled(0x0000ff) sleep(0.1) rgbled(0x0) sleep(0.4) heartbeat(True) except: pass
def main(): pycom.heartbeat(False) sensor = Sensor("P21", "P22") print(sensor.listen())
def __init__(self): pycom.heartbeat(False)
def InitiateConnection(): pyc.rgbled(0xFFFFFF) time.sleep(5) #Send end of transsmission signal def SignalEndText(): pyc.rgbled(0x000000) time.sleep(8) def Wait(): time.sleep(1) pyc.heartbeat(False) isRunning = True ledColor = "" while (isRunning): print('*** Main Menu ***') print("Type the text that you want to send: ") print("Type 'Exit' to EndProgram") text = input() if (text == 'Exit'): break if (text != ""): bitString = textToBits(text) print(bitString) InitiateConnection() for bit in str(bitString):
def __init__(self): self.color = 0x000000 pycom.heartbeat(False)
# REPL duplication on UART0 for serial connection from machine import UART import os usb = UART(0, 115200) os.dupterm(usb) # Disable heartbeat LED from pycom import heartbeat heartbeat(False) # Disable WiFi radio from pycom import wifi_on_boot wifi_on_boot(False)
# main.py = Script to read 3 Watermark sensors import pycom, machine from machine import Pin import watermark # module needed in library for reading Watermark sensors (written by Jan D) import time, ubinascii from onewire import OneWire, DS18X20 from machine import RTC from network import LoRa import socket import binascii import struct import ustruct import config pycom.heartbeat(False) # stop the heartbeat # Set up the Real Time Clock (RTC) rtc = RTC() print(rtc.now()) # This will print date and time if it was set before going # to deepsleep. The RTC keeps running in deepsleep. #WAKE UP print("wake reason (wake_reason, gpio_list):", machine.wake_reason()) ''' PWRON_WAKE -- 0 PIN_WAKE -- 1 RTC_WAKE -- 2 ULP_WAKE -- 3 ''' for cycle in range(1): # initialize LoRa in LORAWAN mode.
def onClientConnect(self): events = self._bt.events() print("[" + self._name + "]: Client connected") pycom.heartbeat(False) pycom.rgbled(0x110011)
def led(color): pycom.heartbeat(False) pycom.rgbled(color)
def set_led_to(color=GREEN): pycom.heartbeat(False) # Disable the heartbeat LED pycom.rgbled(color)
import machine import pycom import time import binascii from network import WLAN pycom.heartbeat(False) # turn off the heartbeat LED so that it can be reused deviceID = binascii.hexlify( machine.unique_id()) # get device unique id and save to file on device print(deviceID[8:12]) f_wifi = open('/flash/homewifi/wifi_name.txt', 'r') # read wifi SSID and password from file # file format is: SSID, WLAN.WPA2, password wifi_setting = f_wifi.readline() wifi_strings = [i.strip() for i in wifi_setting.split(',')] f_wifi.close() print(wifi_strings[0], wifi_strings[1], wifi_strings[2]) f = open('/flash/device_name', 'w' '') f.write(deviceID[8:12]) f.close() print('led on') pycom.rgbled(0x7f0000) # red time.sleep(2) wlan = WLAN(mode=WLAN.STA) wlan.connect(wifi_strings[0], auth=(WLAN.WPA2, wifi_strings[2]), timeout=5000)
def __init__(self): pycom.heartbeat(False) self.value = 0x000000 pycom.rgbled(self.value)
def heartbeat(state): heartbeat(state)
""" OTAA Node example compatible with the LoPy Nano Gateway """ from machine import UART from network import LoRa import pycom import socket import binascii import struct import time import config # UART Data Transmission (Raspberry Pi) pycom.heartbeat(False) # turn off heartbeat uart1 = UART(1, 115200, bits=8, parity=None, stop=1) uart1.init(baudrate=115200, bits=8, parity=None, stop=1, timeout_chars=2, pins=("P3", "P4")) uart1.write("Connected...") # initialize LoRa in LORAWAN mode. lora = LoRa(mode=LoRa.LORAWAN) # create an OTA authentication params dev_eui = binascii.unhexlify('00 6D 13 E0 C6 53 09 5F'.replace( ' ', '')) ## Parameters have altrady been replaced with the ones in TTN app_eui = binascii.unhexlify('70 B3 D5 7E D0 00 78 55'.replace(' ', '')) app_key = binascii.unhexlify(
from machine import UART from os import dupterm from network import Bluetooth from pycom import heartbeat from pycom import wifi_on_boot uart = UART(0, baudrate=115200) dupterm(uart) if heartbeat() == True: heartbeat(False) if wifi_on_boot() == True: wifi_on_boot(False) bluetooth = Bluetooth() bluetooth.deinit()
import os import socket import time import struct from network import LoRa import pycom from machine import Pin from onewire import DS18X20 from onewire import OneWire import json pycom.heartbeat(False) print("DS18X20") #DS18B20 data line connected to pin P10 ow = OneWire(Pin('P10')) temp = DS18X20(ow) # A basic package header, B: 1 byte for the deviceId, B: 1 byte for the pkg size _LORA_PKG_FORMAT = "BB%ds" _LORA_PKG_ACK_FORMAT = "BBB" DEVICE_ID = 0x01 pycom.heartbeat(False) # disable the blue blinking # Open a Lora Socket, use tx_iq to avoid listening to our own messages # Please pick the region that matches where you are using the device: # Asia = LoRa.AS923 # Australia = LoRa.AU915 # Europe = LoRa.EU868 # United States = LoRa.US915 lora = LoRa(mode=LoRa.LORA, tx_iq=True, region=LoRa.US915) lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora_sock.setblocking(False)
sigfox = False if SERVER == "LORAWAN": from network import LoRa lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # mac = lora.mac() print('devEUI: ', binascii.hexlify(mac)) # create an OTAA authentication parameters app_eui = binascii.unhexlify('0000000000000000'.replace(' ', '')) app_key = binascii.unhexlify( '11223344556677881122334455667788'.replace(' ', '')) # Acklio lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) pycom.heartbeat(False) # turn led to white pycom.rgbled(0x101010) # white # wait until the module has joined the network while not lora.has_joined(): time.sleep(2.5) print('Not yet joined...') pycom.rgbled(0x000000) # black s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False) MTU = 200 # Maximun Transmission Unit, for DR 0 should be set to less than 50
#!/usr/bin/env python import pycom from helper import blink_led #Disable default wifi from network import WLAN wlan = WLAN() wlan.deinit() pycom.heartbeat(False) # disable the heartbeat LED pycom.rgbled(0x552000) # flash orange to indicate startup # Try to mount SD card, if this fails, keep blinking red and do not proceed try: from machine import SD, Pin, reset import os import time from loggingpycom import DEBUG from LoggerFactory import LoggerFactory from UserButton import UserButton # Initialise LoggerFactory and status logger logger_factory = LoggerFactory() status_logger = logger_factory.create_status_logger( 'status_logger', level=DEBUG, terminal_out=True, filename='status_log.txt') # Initialise button interrupt on pin 14 for user interaction user_button = UserButton(status_logger) pin_14 = Pin("P14", mode=Pin.IN, pull=Pin.PULL_DOWN)
import ubinascii #Used to pack/unpack byte segments for sending data to LoRa import struct #Used to pack/unpack byte segments for sending data to LoRa import time #used for sleep commands import utime #used for timing commands import os import math import lorakeys #store the active LoRa private keys to send data to TheThingsNetwork import pycom #Used to publish data to PyBytes thru Send_Signal import ustruct #Used to pack/unpack byte segments for sending data to LoRa import si1132 from machine import UART, I2C,Pin #enable the I2C bus adc = machine.ADC() # create an ADC object adc.init(bits=12) apin = adc.channel(pin='P13',attn=3) # create an analog pin on P13 to measure incoming battery voltage thru a 2Mohm / 178kohm divider network, scaling 40v to 3.3v pycom.heartbeat(False) #needs to be disabled for LED functions to work pycom.rgbled(0x7f0000) #red def getBattery(): Batt=0 i=0 while (i<20):#take 20 readings and average it to get a more consistent value val = apin()*0.01278#calculated based on testing. Voltage divider with 2Mohm resistor on high side and 178kohm with a parallelled 100nF cap on low side #this scales the 40v max input voltage down to 3.3v Batt+=val i+=1 BattAverage=Batt/20.0 print('Battery Voltage = ',BattAverage) return BattAverage #get online using known nets if available
import machine import pycom import time from micropyGPS import MicropyGPS from machine import RTC, I2C from machine import SD import os """ SET UP """ # Heartbeat LED flashes in blue colour once every 4s to signal that the system # is alive. Turn off firmware blinking pycom.heartbeat(False) time_searching_GPS = 60 data_gps = {} data_gps['latitude'] = None data_gps['longitude'] = None data_gps['altitude'] = None data_gps['hdop'] = None # declare colour leds led_off = 0x000000 led_green = 0x007f00 pycom.rgbled(led_green) time.sleep_ms(1000) pycom.rgbled(led_off) # RTC rtc = RTC()
import pycom # Base library for Pycom devices. Here used for the onboard LED. import time # Allows use of time.sleep() for delays. import machine # To be able to use the deepsleep. from machine import Timer # To be able to use the timer. from network import LTE # To be able to deinitialize the lte modem before going into deepsleep. # lib file imports. Files you manually have to put in the project lib folder if not already there. import keys # Imports all passwords. Should be erased if you paste your Ubidots Token straight into main.py. from pysense import Pysense # For communication to the Pysense shield. from telenor import StartIoT # To establish the internet connection. This might need to be changed if not on a Telenor SIM card. from umqtt import MQTTClient # For connection with MQTT protocol. from LTR329ALS01 import LTR329ALS01 # Light sensor library. from SI7006A20 import SI7006A20 # Humidity and Temperature sensor library. from MPL3115A2 import MPL3115A2, PRESSURE # Barometric pressure sensor library. pycom.heartbeat(False) # Turns the blinking LED (heartbeat) off. # Global variables. Creates them without giving them a value. To be used later. chrono = '' CLIENT_ID = '' client = '' def resetTimer(): # Starts a timer counting the elapsed time since startup. # This is used so the board always starts every 300 seconds (5 minutes). global chrono chrono = Timer.Chrono() chrono.reset() chrono.start()
from pytrack import Pytrack #from pysense import Pysense from LIS2HH12 import LIS2HH12 import pycom import time pycom.heartbeat(False) py = Pytrack() # py = Pysense() # enable activity and also inactivity interrupts, using the default callback handler py.setup_int_wake_up(True, True) acc = LIS2HH12() # enable the activity/inactivity interrupts # set the accelereation threshold to 2000mG (2G) and the min duration to 200ms acc.enable_activity_interrupt(2000, 200) # check if we were awaken due to activity if acc.activity(): pycom.rgbled(0xFF0000) else: pycom.rgbled(0x00FF00) # timer wake-up time.sleep(0.1) # go to sleep for 5 minutes maximum if no accelerometer interrupt happens py.setup_sleep(300) py.go_to_sleep()
# ************************************************************************ # Helper function: run any code needed to initialize local sensors, if necessary for this hardware # ************************************************************************ # Below is where you can initialize any global variables that are needed by your applicatio; # certain sensors, for example, will require global interface or sensor variables # myExampleInterfaceKitGlobalVar = None py = Pysense() lightSensor = LTR329ALS01(py) # In lux accelerometer = LIS2HH12(py) # In Gs tempHumiditySensor = SI7006A20(py) # in % and C barometer = MPL3115A2(py, mode=ALTITUDE) # in Pa or meters # Enable the heartbeat LED pycom.heartbeat(True) # Prepare to sync the clock rtc = machine.RTC() # The following helper function prepends a zero to a number if it is less than # 10, in order to guarantee two-digit hour, month, day, and minute, and second def prependZeroIfNeeded(number): if (number >= 10): return ("" + str(number)) else: return ("0" + str(number)) # The following helper function pretty-prints out the current time from the rtc # in the ISO format needed by OMFv1 def getCurrentTimestampString():