if self.explicit: PM10 = PM_sample["pm10_cnt"] for pmCnt in PM_sample.keys(): if pmCnt.find('_cnt') < 0: continue if pmCnt.find('03_cnt') > 0: PM_sample['pm03_cnt'] = PM10 else: PM_sample[pmCnt] = PM10 - PM_sample[pmCnt] return PM_sample if __name__ == "__main__": from time import time, sleep interval = 5 * 60 sample = 60 debug = True try: from machine import UART, Pin pins = ('P4', 'P3', 'P19') print("Using pins: %s" % str(pins)) Pin(pins[2], mode=Pin.OUT).value(1) sleep(1) port = UART(1, baudrate=115200, pins=pins[:2], timeout_chars=20) except: import sys port = sys.argv[1] sps30 = SPS30(port=port, debug=debug, sample=sample, interval=interval) for i in range(4): lastTime = time() print(sps30.getData(debug=debug)) now = interval + time() - lastTime if now > 0: sleep(now)
def __init__(self,pin): from machine import Pin self.pin=Pin(pin,Pin.IN)
# Tested on M5Stack Gray # DHT11 sensor module. see https://www.switch-science.com/catalog/818/ from m5stack import lcd from machine import DHT, Pin import time dht = DHT(Pin(22)) lcd.clear() lcd.font(lcd.FONT_Default, fixedwidth=True) while True: result, temperature, humidity = dht.read() if result: lcd.println('Temperature: {} degrees'.format(temperature), 0, 0, color=lcd.GREEN) lcd.println('Humidity: {} %'.format(humidity), color=lcd.GREEN) time.sleep(60)
def write_analog(self,val): id=int(str(self)[4:-1]) self=PWM(Pin(id),duty=val)
def read_analog(self): id=int(str(self)[4:-1]) self=ADC(Pin(id)) return self.read()
from machine import Pin, I2C import network import json import time import machine from umqtt.simple import MQTTClient # setup sensor and ESP8266 and the needed variables i2cport = I2C(scl=Pin(5), sda=Pin(4), freq=100000) i2cport.writeto(0x1E, bytearray([0x02, 0x00])) # set the register in the continous measurement mode ledgreen1 = Pin(13, Pin.OUT) # right led/mum led ledred = Pin(14, Pin.OUT) # middle led/dad led ledgreen2 = Pin(12, Pin.OUT) # left led/kid led threshold = 0 # detect a change only if the value of the change is bigger than the average fluctation (=threshold) sensitivity = 5 # how much bigger is set by sensitivity mumhome = False dadhome = False kidhome = False mum_dict = {} dad_dict = {} kid_dict = {} nokeys_dict = {} def datapull(): # datapull updates the data_dictionary with the last readings from the x,z,y axes registers and returns it xMSB = i2cport.readfrom_mem(0x1E, 0x03, 1) xLSB = i2cport.readfrom_mem(0x1E, 0x04, 1) zMSB = i2cport.readfrom_mem(0x1E, 0x05, 1) zLSB = i2cport.readfrom_mem(0x1E, 0x06, 1) yMSB = i2cport.readfrom_mem(0x1E, 0x07, 1)
from machine import Pin, ADC import time print("Initialiseer ADC: adc1, ch0") # see # - https://docs.micropython.org/en/latest/esp32/quickref.html # - https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/adc # # esp32: Vout from microphone/pre-amp to ADC2 ch0 = GPIO4, pin 24. # Note: channel 2 kan alleen worden gebruikt als WiFi is uitgeschakeld. adc = ADC(Pin(36, Pin.IN), unit=1) # ADC1, ch0 # configureer bereik van 0-3.3 V (3.6 max) adc.atten(adc.ATTN_11DB) # 12 bits resolutie adc.width(adc.WIDTH_12BIT) print(adc.read()) print("ADC klaar voor gebruik") # create list for storing adc-values N = 4096 v_adc = [0] * N # utility-functions for reading adc-values def read_adc(n): r = range(n) for i in r: v_adc[i] = adc.read() v_avg = get_average(v_adc) return v_avg
import uasyncio import picoweb import network import time import gc import tsys01,ms5837 import sdcard, os from machine import Pin from machine import SPI from machine import I2C filename='data1.txt' led = Pin(13,Pin.OUT) #SCL=21 # Green BR cable #SDA=19 # White BR cable SCL=14 # Green BR cable SDA=2 # White BR cable i2c = I2C(-1, Pin(SCL), Pin(SDA)) p=ms5837.MS5837(model='MODEL_30BA',i2c=i2c) t=tsys01.TSYS01(i2c) p.init()
# Input only pins #GPIO36 = 36 # input only #GPIO39 = 39 # input only # Demo of initialisation procedure designed to minimise risk of memory fail # when instantiating the frame buffer. The aim is to do this as early as # possible before importing other modules. from machine import Pin, SPI, ADC import gc from drivers.st7789.st7789_4bit import * SSD = ST7789 pdc = Pin(TFT_DC, Pin.OUT, value=0) # Arbitrary pins pcs = Pin(TFT_CS, Pin.OUT, value=1) prst = Pin(TFT_RST, Pin.OUT, value=1) pbl = Pin(TFT_BL, Pin.OUT, value=1) gc.collect() # Precaution before instantiating framebuf # Conservative low baudrate. Can go to 62.5MHz. spi = SPI(1, 30_000_000, sck=Pin(TFT_SCLK), mosi=Pin(TFT_MOSI)) ''' TTGO v +----------------+ 40 | | | ^ | +------+ | pin 36 | | | | | | | | | | 240 | | | | | | | | | |
# This code reads the distance using HC-SR04P (3-5V) ultrasonic sensor # via default (trig-echo) mode and print out on serial. # --- # Connection: TRIG = GP3, ECHO = GP2 # --- # Hardware: # 1. Cytron Maker Pi RP2040 (www.cytron.io/p-MAKER-PI-RP2040) # - Any RP2040 boards should work too. # 2. HC-SR04P (3-5V) ultrasonic (www.cytron.io/p-SN-HC-SR04P) # --- from machine import Pin import utime trigger = Pin(15, Pin.OUT) echo = Pin(14, Pin.IN) distance = 0 def ultrasound(): global distance trigger.low() utime.sleep_us(2) trigger.high() utime.sleep_us(5) trigger.low() while echo.value() == 0: signaloff = utime.ticks_us() while echo.value() == 1: signalon = utime.ticks_us() timepassed = signalon - signaloff
from machine import Pin, PWM from time import sleep # lower right pins with USB on top RIGHT_FORWARD_PIN = 19 RIGHT_REVERSE_PIN = 18 LEFT_FORWARD_PIN = 20 LEFT_REVERSE_PIN = 21 right_forward = PWM(Pin(RIGHT_FORWARD_PIN)) right_reverse = PWM(Pin(RIGHT_REVERSE_PIN)) left_forward = PWM(Pin(LEFT_FORWARD_PIN)) left_reverse = PWM(Pin(LEFT_REVERSE_PIN)) POWER_LEVEL = 65025 # while True: def spin_wheel(pwm): pwm.duty_u16(POWER_LEVEL) sleep(2) pwm.duty_u16(0) sleep(1) while True: print('right forward') spin_wheel(right_forward) print('right reverse') spin_wheel(right_reverse)
# history: # V1.1 add oled draw function,add buzz.freq(). by tangliufeng # V1.2 add servo/ui class,by tangliufeng from machine import I2C, PWM, Pin, ADC, TouchPad from ssd1106 import SSD1106_I2C import esp, math, time, network import ustruct, array from neopixel import NeoPixel # from esp import dht_readinto from time import sleep_ms, sleep_us, sleep import framebuf import calibrate_img i2c = I2C(0, scl=Pin(Pin.P19), sda=Pin(Pin.P20), freq=400000) class Font(object): def __init__(self, font_address=0x400000): self.font_address = font_address buffer = bytearray(18) esp.flash_read(self.font_address, buffer) self.header, \ self.height, \ self.width, \ self.baseline, \ self.x_height, \ self.Y_height, \ self.first_char,\ self.last_char = ustruct.unpack('4sHHHHHHH', buffer)
from network import LoRa import socket import time import ubinascii import cayenneLPP from machine import Pin from onewire import DS18X20 from onewire import OneWire #DS18B20 data line connected to pin P10 ow = OneWire(Pin('P10')) temp = DS18X20(ow) # 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) print("DevEUI: " + ubinascii.hexlify(lora.mac()).decode('utf-8').upper()) # create an OTAA authentication parameters ### App ID: lnu-iot-workshop ### device name: sensor01 app_eui = ubinascii.unhexlify('70B3D57ED0022279') ## app key app_key = ubinascii.unhexlify('54B318775807C8ED3A33E323EB867E6F')
elif pos >= 240 and pos < 300: self.red = int(255 * (pos - 240) / 60) self.green = 0 self.blue = 255 else: self.red = 255 self.green = 0 self.blue = 255 - int(255 * (pos - 300) / 60) # print("red: {:03d}, green: {:03d}, blue: {:03d}".format(self.red, # self.green, # self.blue)) return (self.red, self.green, self.blue) pin = Pin(NEO_PIXEL_PIN, Pin.OUT) np = NeoPixel(pin, NO_OF_LEDS) brightness = 0.1 wheel = ColorWheel() wheel_pos = [None] * NO_OF_LEDS print("Each led shows all colors of the color wheel") print("The color wheel starting position of led i is i * 360° / no of leds") for led in range(NO_OF_LEDS): wheel_pos[led] = int(360 / NO_OF_LEDS * led) # print("wheel pos for led {:d}: {:d}".format(led,wheel_pos[led])) while True:
def __init__(self,pin1=2,pin2=4): self.pin_1 = Pin(pin1, Pin.OUT) self.pin_2 = Pin(pin2, Pin.OUT)
import time import network import config from umqtt.simple import MQTTClient from machine import Pin from neopixel import NeoPixel wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(config.essid, config.passwd) # your local wifi credentials np = NeoPixel(Pin(15, Pin.OUT), 32) # which pin your NeoPixels are connected to # keep trying to connect to the wifi until we suceed while not wlan.isconnected(): np.fill((10, 0, 0)) np.write() time.sleep_ms(200) np.fill((0, 0, 0)) np.write() time.sleep_ms(300) wlan.ifconfig() def set_led(topic, msg): print("topic:'", topic, "' msg:'", msg, "'") np.fill((int(msg), int(msg), int(msg))) np.write() # if topic == button or if topic == led
from machine import ADC,SPI,PWM,Pin import time,network import BlynkLib sta_if=network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("Wifi 基地台", "Wifi 密碼") while not sta_if.isconnected(): pass print('wifi connect') token="Blynk 權杖" blynk=BlynkLib.Blynk(token) # sound D7 sound=Pin(4,Pin.IN) count=0 while True : if sound.value()==1 : count+=1 if sound.value()==0 : count=0 if count==5 : print('嬰兒房有聲響,快去查看') blynk.notify("嬰兒房有聲響,快去查看") count=0 print(sound.value(),count) time.sleep(.2)
buffer = buffer+ch if buffer: for i in range(len(buffer)): if buffer[i] == 'T': break buffer = buffer[i:] if buffer[:1] == 'T': if buffer[1:11].isdigit(): syncTime = int(buffer[1:11]) if syncTime > 1609459201: # Thursday 1st January 2021 00:00:01 timeDelta = syncTime - int(time()) else: syncTime = 0 return timeDelta led_onboard = Pin(25, Pin.OUT) lastTime = timeNow(timeDelta) while True: timeDelta = checkTimeSyncUSB(timeDelta) correctedRTC = timeNow(timeDelta) # # every second do the following ... # if correctedRTC != lastTime: lastTime=correctedRTC if timeDelta == 0: for i in range(5): led_onboard.toggle()
from time import sleep from servo import Servo from machine import Pin, ADC import otacli import config if otacli.check(): print("this line will be never reached") servo = None servo = Servo(config.SERVO_PIN) adc = ADC(Pin(config.ADAC_PIN)) while True: sleep(0.1) v = adc.read() / 4096 vr = round(v, 1) print("vr=", vr, "v=", v) # servo.set(v) servo.set(v - 0.5)
def draw_white(pin): clear_screen = True print("clear_screen: ", clear_screen) import gc import framebuf gc.collect() fb = framebuf.FrameBuffer(buf, w, h, framebuf.MONO_HLSB) black = 0 white = 1 fb.fill(white) e.display_frame(buf) sleep_time_ms = 60000 try: boot_button= Pin(0) # boot # SPIV on ESP32 sck = Pin(18) # CLK miso = Pin(19) # mosi = Pin(23) # DIN dc = Pin(32) # DC cs = Pin(33) # Chip Select rst = Pin(19) # RST busy = Pin(35) # BUSY spi = SPI(2, baudrate=20000000, polarity=0, phase=0, sck=sck, miso=miso, mosi=mosi) e = epaper7in5_V2.EPD(spi, cs, dc, rst, busy) e.init() w = 800
self.vline(x,y,l,c) self.show() def show_line(self,x1,y1,x2,y2,c): self.line(x1,y1,x2,y2,c) self.show() def show_circle(self,x0,y0,radius,c): self.circle(x0,y0,radius,c) self.show() def show_fill_circle(self,x0,y0,radius,c): self.fill_circle(x0,y0,radius,c) self.show() def show_triangle(self,x0,y0,x1,y1,x2,y2,c): self.triangle(x0,y0,x1,y1,x2,y2,c) self.show() def show_fill_triangle(self,x0,y0,x1,y1,x2,y2,c): self.fill_triangle(x0,y0,x1,y1,x2,y2,c) self.show() i2c=I2C(scl=Pin(22),sda=Pin(23),freq=400000) accelerometer=Accelerometer() oled=OLED() button_a=Button(0) button_b=Button(2) rgb=NeoPixel(Pin(17,Pin.OUT),3,3,1) rgb.write() touch1=MyPin(27) touch2=MyPin(14) touch3=MyPin(12) touch4=MyPin(13) touch5=MyPin(15) touch6=MyPin(14)
#Written by Andi Dinata #September 2018 import socket import websocket_helper from machine import Pin led = Pin(2, Pin.OUT) html = """<!DOCTYPE html> <html> <head> <title>ESP8266 Micropython Webserver</title> </head> <meta content='width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no;' name='viewport'/> <form> <center> This is demo for IoT implementation to remotely turn on/off light using internet Press the button to toggle on and off the on-board led <button style="font-size:14px;background-color:cyan; height:50px;width:90px" name="BUTTON" value="TOGGLE" type="submit">try me..</button> </center> </form> </html> """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: conn, addr = s.accept() request = conn.recv(1024) request = str(request)
def dac_write(self,val): id=int(str(self)[4:-1]) self=DAC(Pin(id)).write(val)
# octopusLAB simple example # HW: ESP32board + button 0 (boot) interupt # import octopus.ps_button_irq from machine import Pin import pubsub counter=0 @pubsub.publisher("btn_value") def irq_handler(v): global counter counter += 1 print("IRQ ", counter) return counter button0 = Pin(0, Pin.IN) # default BOOT btn button0.irq(trigger=Pin.IRQ_FALLING, handler=irq_handler) # while True: # pass
def set_frequency(self,val): id=int(str(self)[4:-1]) self=PWM(Pin(id),freq=val)
from machine import Pin import utime #1B #pins = [36,39,34,35] #1C pins = [36,39,34,35] keys = [] for p in pins: keys.append(Pin(p,Pin.IN)) while True: result = "" for k in keys: if k.value(): result += "Up\t" else: result += "Press\t" result += "\t" print(result) utime.sleep_ms(1000)
from machine import Pin from time import sleep from lib.tm1638 import TM1638 from utils.bits import neg, reverse, set_bit, get_bit from components.led import Led import _thread # right OCTOBUS SCI: # STB = MOSI 23 # CLK = MISO 19 # DIO = SCLK 18 keys = 0 led = Led(2) tm = TM1638(stb=Pin(23), clk=Pin(19), dio=Pin(18)) print("TM1638_thread example") tm.leds(0b01010101) tm.show("octopus") sleep(1.5) for i in range(8): tm.leds(set_bit(0b00000000, i, 1)) # snake sleep(0.2) tm.leds(0) def readKeys():
from time import sleep import network import urequests as requests import json with open('config.json') as config_file: credentials = json.load(config_file) # ESP8266 Pin assignment i2c = I2C(-1, scl=Pin(4), sda=Pin(5)) oled_width = 128 oled_height = 64 oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c) #-------------------------------- def draw_circle( x0, y0, radius): x = radius y = 0 err = 0 while x >= y: oled.pixel(x0 + x, y0 + y, 1)
def __init__(self, pinnumber): self.light = Pin(pinnumber, mode=Pin.OUT, value=1) self.light(0)
# Main creado con la intencion de tomar muestras de imu from gps import GPS from sd import * from imu import * from time import sleep, ticks_ms from machine import Timer, deepsleep, Pin, RTC, ADC import uos from drivers.direccionCollar import * import lora import utime ################# Sensado de bateria LOW_BAT_LEVEL = 1600 pinvext = Pin(21, Pin.OUT) pinvext.value(0) adc = ADC(Pin(32)) adc.atten(adc.ATTN_11DB) adc.read() # se consume la primera lectura, ya que da una medicion erronea # promedio de muestras de adc ################### # Modulo SD sd = initSD() # Modulo GPS gps = GPS() gps.attachSD(sd) #gps.write2sd() gps_time = None while gps_time is None: print("[debug] solicitando hora al GPS") gps_time = gps.req_time() print("[debug] hora solicitada exitosamente")