# more params can also be given, like frequency, tx power and spreading factor lora = LoRa(mode=LoRa.LORA) # create a raw LoRa socket nMsgTx = 1 tStartMsec = time.ticks_ms() LoraStats = "" # get lora stats # ----------------------------- tstgps5.py # expansion board user led user_led = Pin("G16", mode=Pin.OUT) # expansion board button button = Pin("G17", mode=Pin.IN, pull=Pin.PULL_UP) pycom.heartbeat(False) pycom.rgbled(0x007f00) # green # --------------------------------- # setup wypy/lopy as a station wlan = network.WLAN(mode=network.WLAN.STA) wlan.connect('mrandroid', auth=(network.WLAN.WPA2, 'eatmenow')) while not wlan.isconnected(): time.sleep_ms(50) print(wlan.ifconfig()) # --------------------------------- # create directory log if not exist try: os.mkdir('/flash/log') except OSError: pass
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 pycom import time #Initial print("Initializing") pycom.heartbeat(False) # Display blue for intializing pycom.rgbled(0x0000FF) time.sleep(2) # Go red for attempting to connect to lora pycom.rgbled(0xFF0000) time.sleep(5) while true: #Go green for connected pycom.rgbled(0x00FF00) time.sleep(15) # go yellow for attempting to send pycom.rgbled(0xFFC100)
# create an ABP authentication params #dev_addr = struct.unpack(">l", binascii.unhexlify('0ab8142f'))[0] #nwk_swkey = binascii.unhexlify('00112c72b32e0a1c5da9bf6a5f2eae3f') #app_swkey = binascii.unhexlify('c05b8f1a03130f7bebd588586110362e') dev_addr = config.dev_addr nwk_swkey = config.nwk_swkey app_swkey = config.app_swkey # join a network using ABP activation lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey), timeout=0) # wait until the module has joined the network while not lora.has_joined(): pycom.rgbled(0x140000) time.sleep(2.5) pycom.rgbled(0x000000) time.sleep(1.0) print('Not yet joined...') print('LoraWan ABP joined...') pycom.rgbled(0x001400) # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) while True:
# ************************************************************************ # Finally, loop indefinitely, sending random events # conforming to the value type that we defined earlier # ************************************************************************ print( '\n--- Now sending live data every ' + str(NUMBER_OF_SECONDS_BETWEEN_VALUE_MESSAGES) + ' second(s) for device "' + NEW_AF_ELEMENT_NAME + '"... (press CTRL+C to quit at any time)\n' ) if not SEND_DATA_TO_OSISOFT_CLOUD_SERVICES: print( '--- (Look for a new AF Element named "' + NEW_AF_ELEMENT_NAME + '".)\n' ) while True: # Turn on the hearbeat LED! pycom.rgbled(0x050000); # Call the custom function that builds a JSON object that # contains new data values; see the beginning of this script VALUES_MESSAGE_JSON = create_data_values_message() # Send the JSON message to the target URL; send_omf_message_to_endpoint("create", "Data", VALUES_MESSAGE_JSON) # Turn off the hearbeat LED! pycom.rgbled(0); # Send the next message after the required interval time.sleep(NUMBER_OF_SECONDS_BETWEEN_VALUE_MESSAGES)
def receive_data(): global index global guard global slot global packet_size lora = LoRa(mode=LoRa.LORA, rx_iq=True, frequency=freqs[my_sf - 5], region=LoRa.EU868, power_mode=LoRa.ALWAYS_ON, bandwidth=my_bw, sf=my_sf) lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora_sock.setblocking(False) guard = 1000 * guard (overall_received, overall_sent) = (0, 0) airt = int(airtime_calc(my_sf, 1, packet_size + 2, my_bw_plain) * 1000) duty_cycle_limit_slots = math.ceil(100 * airt / (airt + 2 * guard)) print("duty cycle slots:", duty_cycle_limit_slots) print("packet airtime (ms):", airt / 1000) print("guard time (ms):", guard / 1000) chrono = Timer.Chrono() chrono.start() i = 1 while (True): print(i, "----------------------------------------------------") print("Net size is:", index + 1) chrono.reset() round_start = chrono.read_us() received = 0 acks = [] if (int(index) > duty_cycle_limit_slots): round_length = math.ceil(int(index) * (airt + 2 * guard)) else: round_length = math.ceil(duty_cycle_limit_slots * (airt + 2 * guard)) lora.init(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868, frequency=freqs[my_sf - 5], power_mode=LoRa.ALWAYS_ON, bandwidth=my_bw, sf=my_sf) rec_start = chrono.read_us() pycom.rgbled(green) while ((chrono.read_us() - round_start) < round_length - 66000): # the following line may take up to 66ms recv_pkg = lora_sock.recv(256) if (len(recv_pkg) > 2): recv_pkg_len = recv_pkg[1] recv_pkg_id = recv_pkg[0] if (int(recv_pkg_id) <= 35) and (int(recv_pkg_len) == int(packet_size)): dev_id, leng, msg = struct.unpack( _LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg) if (len(msg) == packet_size): # format check received += 1 # print('Received from: %d' % dev_id) # print(lora.stats()) acks.append(str(int(dev_id))) pycom.rgbled(off) print(received, "packets received") rec_lasted = chrono.read_us() - rec_start if (rec_lasted < round_length): print("I'll sleep a bit to align with the round length") time.sleep_us(int(round_length - rec_lasted)) print("Receiving lasted (ms):", (chrono.read_us() - rec_start) / 1000) print("...should last (ms):", round_length / 1000) proc_t = chrono.read_us() ack_msg = "" for n in range(int(index) + 1): if n in slot: id = str(slot[n]) if id in acks: ack_msg = ack_msg + "1" else: ack_msg = ack_msg + "0" if (ack_msg != ""): ack_msg = str(hex(int(ack_msg, 2)))[2:] print("proc time (ms):", (chrono.read_us() - proc_t) / 1000) proc_t = chrono.read_us() - proc_t if (i % sync_rate == 0): # SACK sync_start = chrono.read_us() pycom.rgbled(white) time.sleep_us(int(guard * 3 / 2)) # let's make it long so all the nodes are up lora.init(mode=LoRa.LORA, tx_iq=True, frequency=freqs[my_sf - 5], region=LoRa.EU868, power_mode=LoRa.ALWAYS_ON, bandwidth=my_bw, sf=my_sf, tx_power=14) data = str(index + 1) + ":" + str(int( proc_t / 1000)) + ":" + ack_msg pkg = struct.pack(_LORA_PKG_FORMAT % len(data), MY_ID, len(data), data) pycom.rgbled(red) lora_sock.send(pkg) print("Sent sync: " + data) pycom.rgbled(off) time.sleep_ms(13) # node time after sack print("sync lasted (ms):", (chrono.read_us() - sync_start) / 1000) print("round lasted (ms):", (chrono.read_us() - round_start) / 1000) i += 1
distance_samples.append(int(distance_measure())) # sort the list distance_samples = sorted(distance_samples) # take the center list row value (median average) distance_median = distance_samples[int(len(distance_samples) / 2)] # apply the function to scale to volts print(distance_samples) return int(distance_median) # disable LED heartbeat (so we can control the LED) pycom.heartbeat(False) # set LED to red pycom.rgbled(0x7f0000) # United States = LoRa.US915 lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) print("DevEUI: " + ubinascii.hexlify(lora.mac()).decode('utf-8').upper()) # access info app_eui = binascii.unhexlify('70B3D57ED00222DB') app_key = binascii.unhexlify('095D815ABAD620C5F56896C0FCA865C4') # attempt join - continues attempts background lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # wait for a connection print('Waiting for LoRaWAN network connection...') while not lora.has_joined():
import pycom import time pycom.heartbeat(False) for cycles in range(1): # stop after 10 cycles pycom.rgbled(0x007f00) # green time.sleep(1) pycom.rgbled(0x7f7f00) # yellow time.sleep(1) pycom.rgbled(0x7f0000) # red time.sleep(1)
app_swkey = binascii.unhexlify('FC212CD2F15509CE2218F30A7380F58A') lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setsockopt(socket.SOL_LORA, socket.SO_DR, 0) print("LoRa Initialized") #Accelerometer wake-up settings: py.setup_int_pin_wake_up(False) py.setup_int_wake_up(True, True) acc.enable_activity_interrupt(150, 160) while True: #wake_s = ds.get_wake_status() #print(wake_s) time.sleep(0.1) if (acc.activity()): pycom.rgbled(0x11fff1) s.setblocking(True) lpp = cayenneLPP.CayenneLPP( size=100, sock=s) #create socket to send messages to server pitch = acc.pitch() roll = acc.roll() x, y, z = acc.acceleration() #if (x > y) and (x > z): # largest = x #elif (y > x) and (y > z): # largest = y #else: # largest = z time.sleep(0.02) x1, y1, z1 = acc.acceleration()
def led(): pycom.rgbled(led_green) time.sleep_ms(1000) pycom.rgbled(led_off)
#limitations under the License. #The above copyright notice and this permission notice shall be #included in all copies or substantial portions of the Software. # boot.py -- run on boot-up import os import pycom from machine import UART from network import WLAN uart = UART(0, 115200) os.dupterm(uart) pycom.heartbeat(False) # wlan access ssid_ = '###SSID###' wp2_pass = '******' # configure the WLAN subsystem in station mode (the default is AP) wlan = WLAN(mode=WLAN.STA) wlan.scan() # scan for available networks wlan.connect(ssid=ssid_, auth=(WLAN.WPA2, wp2_pass)) while not wlan.isconnected(): pycom.rgbled(0xFF0000) pass pycom.rgbled(0x050505)
def set_led_to(color=GREEN): pycom.heartbeat(False) # Disable the heartbeat LED pycom.rgbled(color)
def solid(color): disable_heartbeat() if alarm: alarm.cancel() pycom.rgbled(color)
def _led_timer(alarm): global rgbled_value rgbled_value ^= rgbled_color pycom.rgbled(rgbled_value)
deviceID = "1" py = Pysense() li = LIS2HH12(py) # This part connects the board to Wifi wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() pycom.heartbeat(False) antenna = WLAN.EXT_ANT for net in nets: if net.ssid == 'Gronnemarken18': print('Network found!') wlan.connect(net.ssid, auth=(WLAN.WPA2, 'toofan2204'), timeout=10000) while not wlan.isconnected(): print('Not connected') time.sleep(1) print('WLAN connection succeeded!') pycom.rgbled(0x007f00) # green break #Sending the data to a server while True: acc = li.acceleration() x = acc[0] y = acc[1] z = acc[2] mydata = {"ID": deviceID, "x": x, "y": y, "z": z} urequests.post("http://192.168.0.8/update", json=mydata).close() time.sleep(0.5)
# # See https://docs.pycom.io for more information regarding library specifics import time import pycom from pycoproc_2 import Pycoproc import machine from LIS2HH12 import LIS2HH12 from SI7006A20 import SI7006A20 from LTR329ALS01 import LTR329ALS01 from MPL3115A2 import MPL3115A2,ALTITUDE,PRESSURE pycom.heartbeat(False) pycom.rgbled(0x0A0A08) # white py = Pycoproc() if py.read_product_id() != Pycoproc.USB_PID_PYSENSE: raise Exception('Not a Pysense') mp = MPL3115A2(py,mode=ALTITUDE) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals print("MPL3115A2 temperature: " + str(mp.temperature())) print("Altitude: " + str(mp.altitude())) mpp = MPL3115A2(py,mode=PRESSURE) # Returns pressure in Pa. Mode may also be set to ALTITUDE, returning a value in meters print("Pressure: " + str(mpp.pressure())) si = SI7006A20(py) print("Temperature: " + str(si.temperature())+ " deg C and Relative Humidity: " + str(si.humidity()) + " %RH") print("Dew point: "+ str(si.dew_point()) + " deg C")
def finishCalibration(none): msg = 'Finish wifi LoPy' pycom.rgbled(False) return False, msg
def rgb_led(rgb): if not (_config.get_value('general', 'general', 'button_ap_enabled') and _config.get_value('general', 'general', 'button_ap_pin') == 2): pycom.rgbled(rgb)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) if config and not radio: s.setblocking(False) while True: # Listen on socket light = 0. # Light % temp = 0. # Temperature C humi = 0. # Humidity pres = 0. # Pressure gas = 0. # Gas data = s.recv(64) if data != b'': pycom.rgbled(0x00FF00) utime.sleep(0.2) pycom.rgbled(0x000000) utime.sleep(0.2) pycom.rgbled(0x00FF00) utime.sleep(0.2) pycom.rgbled(0x000000) utime.sleep(0.2) vals = data.split() light = str(vals[0], 'utf-8') temp = str(vals[1], 'utf-8') humi = str(vals[2], 'utf-8') pres = str(vals[3], 'utf-8') gas = str(vals[4], 'utf-8')
def t3_publication(topic, msg): print(topic, ';', msg) pycom.rgbled(0xff00)
coding_rate=LoRa.CODING_4_7) tx_p = randomize_tx_power() bw = randomize_bandwith() s_f = randomize_sf() c_r = randomize_coding_rate() # time.sleep(1) """ Broadcast new parameters to nodes """ for i in range(0, 5): lora_params = str(5-i) + "|" + str(tx_p) + "|" + str(bw) + "|" + \ str(s_f) + "|" + str(c_r) # print("NEW PARAMETERS: ", lora_params) lora_sock.send(lora_params) pycom.rgbled(0x0000ff) # blue = transmit new channel parameters time.sleep(1) """ Get into receive mode to receive data from nodes """ lora.init(mode=LoRa.LORA, tx_power=tx_p, bandwidth=bw, sf=s_f, coding_rate=c_r) time.sleep(1) """ Receive data for 30 seconds and write it to UART """ timeout = time.time() + 30 * 1 while True:
sf=7, frequency=903900000) #remove all channels gateway doesn't use for channel in range(16, 72): lora.remove_channel(channel) for channel in range(0, 7): lora.remove_channel(channel) #create an OTAA authentication parameters for ring lopy dev_eui = ubinascii.unhexlify( '70B3D54990435DFE') # these settings can be found from TTN app_eui = ubinascii.unhexlify('70B3D57ED0028A4F') app_key = ubinascii.unhexlify('CE46C01958A612D102F0D106AB415862') if not lora.has_joined(): lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) pycom.rgbled(green) time.sleep(2.5) handshk_time = Timer.Chrono() handshk_time.start() # wait until the module has joined the network while not lora.has_joined(): pycom.rgbled(off) time.sleep(0.1) pycom.rgbled(red) time.sleep(2.4) print('Not yet joined...') lora.nvram_save() handshk_time.stop() print("Total handshake time: {0}".format(handshk_time.read())) print('Joined!') pycom.rgbled(blue)
import machine import pycom import utime from network import WLAN pycom.heartbeat(False) pycom.rgbled(0x7f00000) def setTime(): rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") while not rtc.synced(): utime.sleep_ms(50) print(utime.time()) print(rtc.now()) print(int(utime.time() * 1000)) if utime.time() < 1000: wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == 'SDU-GUEST': print('Network found!') wlan.connect(net.ssid, auth=(net.sec, ''), timeout=5000) while not wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!')
_LORA_PKG_FORMAT = "BB%ds" _LORA_PKG_ACK_FORMAT = "BBB" _LORA_ACKNOWLEDGEMENT_TIMEOUT = 3 # seconds DEVICE_ID = 0x01 DEVICE_NAME = "node1" DEVICE_COLOUR = "red" DEVICE_COLOUR_CODE = 0xFF0000 # RGBLED # Disable the on-board heartbeat (blue flash every 4 seconds) # We'll use the LED to identify each unit with different colours pycom.heartbeat(False) time.sleep(0.1) # Workaround for a bug. # Above line is not actioned if another # process occurs immediately afterwards pycom.rgbled(DEVICE_COLOUR_CODE) print("{} is {}".format(DEVICE_NAME, DEVICE_COLOUR)) # 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.AU915) lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora_sock.setblocking(False) while (True): print("{} ({}) ".format(DEVICE_NAME, DEVICE_COLOUR), end='') # Package send containing a simple string
# configure it as uplink only s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False) pycom.heartbeat(False) ow = OneWire(Pin('G17')) temp = DS18X20(ow) temp.start_convertion() time.sleep(1) result = temp.read_temp_async() wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() nets = sorted(nets, key=lambda x:x.rssi, reverse=True) wifi = [] print(str(result)) pycom.rgbled(0x003300) s.send(str(result)) pycom.rgbled(0x000000) if len(nets) >= 2: wifi = nets[0].bssid + nets[1].bssid print(wifi) pycom.rgbled(0x003300) s.send(wifi.decode()) pycom.rgbled(0x000000) machine.deepsleep(60*1000*10)
count = 0 while (count < numADCreadings): adcint = adcread() samplesADC[count] = adcint meanADC += adcint count += 1 meanADC /= numADCreadings varianceADC = 0.0 for adcint in samplesADC: varianceADC += (adcint - meanADC)**2 varianceADC /= (numADCreadings - 1) mV = meanADC*1400/1024 return mV pycom.heartbeat(False) #needs to be disabled for LED functions to work pycom.rgbled(0x0f0000) #red #Set AppEUI and AppKey - use your values from the device settings --> https://console.thethingsnetwork.org/ dev_eui = binascii.unhexlify('xxxxxxxxxxxxxxxx') app_eui = binascii.unhexlify('xxxxxxxxxxxxxxxx') app_key = binascii.unhexlify('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') #Set LoRa to Australia ready to reset the channels lora = LoRa(mode=LoRa.LORAWAN, public=1, adr=0, tx_retries=0, region=LoRa.AU915) # Remove default channels for index in range(0, 72): lora.remove_channel(index) # Set AU ISM 915 channel plan for TTN Australia for index in range(0, 7):
# main.py -- put your code here! import pycom import time import sendData from machine import RTC pycom.heartbeat(False) try: sendData.connectLocalBox('/flash/config.json') rtc = RTC() rtc.ntp_sync('fr.pool.ntp.org') pycom.rgbled(0x00FF00) time.sleep(0.2) pycom.rgbled(0) time.sleep(0.2) pycom.rgbled(0x00FF00) time.sleep(0.2) pycom.rgbled(0) except Exception as e: print(e) pycom.rgbled(0xFF0000) time.sleep(0.2) pycom.rgbled(0) time.sleep(0.2) pycom.rgbled(0xFF0000) time.sleep(0.2) pycom.rgbled(0)
from machine import Pin import pycom import time sensor = Pin('P8', mode=Pin.IN) pycom.heartbeat(False) pycom.rgbled(0x007f00) blocked = False print('lets go') def sensorCallback(argument): # global blocked # if blocked: # return # blocked=True if argument.value() == 1: print('Something is blocking me.') pycom.rgbled(0x7f0000) time.sleep(2) # global blocked # # if not blocked: # # return # blocked = False else: print('Yay! im free.') pycom.rgbled(0x007f00) sensor.callback(Pin.IRQ_RISING or Pin.IRQ_FALLING, sensorCallback)
import pycom import time pycom.heartbeat(False) for cycles in range(10): # stop after 10 cycles pycom.rgbled(0x007f00) # green time.sleep(5) pycom.rgbled(0x7f7f00) # yellow time.sleep(5) pycom.rgbled(0x7f0000) # red time.sleep(5)
def blink(seconds, rgb): pycom.rgbled(rgb) time.sleep(seconds / 2) pycom.rgbled(0x000000) # off time.sleep(seconds / 2)
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()
# Broker settings SERVER = "165.22.79.210" PORT = 65020 CLIENT_ID = ubinascii.hexlify(machine.unique_id()) # Can be anything TEMP_TOPIC = "temp" # END SETTINGS # RGBLED # Disable the on-board heartbeat (blue flash every 4 seconds) # We'll use the LED to respond to messages from Adafruit IO pycom.heartbeat(False) time.sleep(0.1) # Workaround for a bug. # Above line is not actioned if another # process occurs immediately afterwards pycom.rgbled(0xff0000) # Status red = not working # WIFI # We need to have a connection to WiFi for Internet access # Code source: https://docs.pycom.io/chapter/tutorials/all/wlan.html wlan = WLAN(mode=WLAN.STA) wlan.connect(WIFI_SSID, timeout=5000) time.sleep(3) #while not wlan.isconnected(): # Code waits here until WiFi connects # machine.idle() print("Connected to Wifi") pycom.rgbled(0xffd7000) # Status orange: partially working