from machine import ADC import machine import utime # The inputs adc = ADC(0) # Opens the Analog pin to read stopButton = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP) #Pin D1 # LEDs led1 = machine.Pin(4, machine.Pin.OUT) #Pin D2 led2 = machine.Pin(0, machine.Pin.OUT) #Pin D3 led3 = machine.Pin(2, machine.Pin.OUT) #Pin D4 led4 = machine.Pin(14, machine.Pin.OUT) #Pin D5 #Thresholds led1_thresh = 256 led2_thresh = 512 led3_thresh = 768 led4_thresh = 1024 def updateLed(volt): if volt >= led1_thresh: led1.value(1) else: led1.value(0) if volt >= led2_thresh: led2.value(1) else: led2.value(0)
import iotine import machine import esp32 from machine import Pin, ADC PINX = 32 # needs to be a pin that supports ADC PINY = 33 # needs to be a pin that supports ADC PINSW = 0 p4 = machine.Pin(4) servo = machine.PWM(p4, freq=50) adcx = ADC(Pin(PINX)) adcx.atten(ADC.ATTN_11DB) adcy = ADC(Pin(PINY)) adcy.atten(ADC.ATTN_11DB) sw = Pin(PINSW, Pin.IN, Pin.PULL_UP) def moveServo(dty): servo.duty(dty) return dty def button_pressed(): iotine.publish([{ "name": "CORE_TEMP_ESP", "value": esp32.raw_temperature() }, { "name": "CORE_HALL", "value": esp32.hall_sensor() }], on_pub)
import time import ujson import network from umqtt.simple import MQTTClient # function to read x axis def getX(): x_higher = int.from_bytes(i2cport.readfrom_mem(24, 0x29, 1), 'little') x_lower = int.from_bytes(i2cport.readfrom_mem(24, 0x28, 1), 'little') x = (x_higher << 8) + x_lower return x # ###################### CODE BEGINS HERE ############################################## # set up i2c comm i2cport = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=100000) # enable accelerometer read at 400Hz, only x axis activated i2cport.writeto(24, bytearray([0x20, 0x77])) # connect to phone hotspot ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('Belen', 'exhibition') # give time for connection time.sleep(5) print(sta_if.isconnected())
import json import urequests #import wlan import DS1307 # APN credentials (replace with yours) GSM_APN = 'Qu3d45_ESP32' # Your APN GSM_USER = '' # Your User GSM_PASS = '' # Your Pass # Power on the GSM module GSM_PWR = machine.Pin(4, machine.Pin.OUT) GSM_RST = machine.Pin(5, machine.Pin.OUT) GSM_MODEM_PWR = machine.Pin(23, machine.Pin.OUT) GSM_PWR.value(0) GSM_RST.value(1) GSM_MODEM_PWR.value(1) # Init PPPoS # gsm.debug(True) # Uncomment this to see more logs, investigate issues, etc. gsm.start(tx=27, rx=26, apn=GSM_APN, user=GSM_USER, password=GSM_PASS) sys.stdout.write('Waiting for AT command response...') for retry in range(20):
def get(self, data): res = [] for p, d in pins.items(): val = machine.Pin(p).value() res.append({'gpio': p, 'nodemcu': d, 'value': val}) return {'pins': res}
def panic(flag=0): return machine.reset_cause() reset = machine.reset import display Image = display.Image display = display.Display() import button button_a = button.Button(35) button_b = button.Button(27) import temperature __adc = machine.ADC(machine.Pin(34, machine.Pin.IN)) __adc.atten(machine.ADC.ATTN_11DB) temperature = temperature.Temperature(__adc).temperature try: from mpu9250 import MPU9250 from mpu6500 import MPU6500 __i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=200000) __dev = __i2c.scan() # print("dev ", __dev) if 104 in __dev: print("1.4 version") __sensor = MPU9250(__i2c, MPU6500(__i2c, 0x68)) if 105 in __dev: print("1.2 version No compass") __sensor = MPU9250(__i2c, MPU6500(__i2c, 0x69))
def __init__(self, pin): self._pin = machine.ADC(machine.Pin(pin)) self._pin.atten(machine.ADC.ATTN_11DB)
import neopixel import time NEO_PIN = 15 NUM_LEDS = 60 NUM_CYCLE = 5 RED_HIGH = (255,0,0) RED_LOW = (16,0,0) GREEN_HIGH = (0,255,0) GREEN_LOW = (0,16,0) BLUE_HIGH = (0,0,255) BLUE_LOW = (0,0,16) neo = neopixel.NeoPixel(machine.Pin(NEO_PIN), NUM_LEDS) # Should be filled with 0s to start (off), but ensure that's true neo.fill((0,0,0)) neo.write() index = 0 going = True while(True): # Fill with zeros (off) to start neo.fill(RED_LOW) if (index + NUM_CYCLE >= NUM_LEDS): going = False
import machine import ujson import socket from hcsr04 import HCSR04 pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] trig_pin = 4 echo_pin = 3 sensor = HCSR04(trig_pin, echo_pin) html = """HTTP/1.1 200 OK <!DOCTYPE html> <html> <head> <title>ESP8266 Pins</title> </head> <body> <h1>ESP8266 Pins</h1> <table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table> </body> </html> """ headers = '''HTTP/1.1 200 OK Content-Type: application/json ''' addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket()
# This script uses the ssd1306 oled module: # This file was created on 15/04/2017 # Author: George Kaimakis import machine import ssd1306 import time # define the display size: width = 128 # pixels height = 64 # pixels # define i2c pins: data = machine.Pin(4) clk = machine.Pin(5) # create i2c object: i2c = machine.I2C(scl=clk, sda=data) #create oled object: oled = ssd1306.SSD1306_I2C(width, height, i2c) # blank the display: oled.fill(0) oled.show() time.sleep_ms(500) # the framebuf class contains methods for drawing rectangles # fill_rect, rect - also use these with height/width of 1 pixel to create lines:
import network import ubinascii #how many times should we try to connect before giving up? conn_tries = 2 #setup connection to the network wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect("badwolf", "17162968") wlan.ifconfig() #define the name of the board sensID = "SENSOR" + str(int(ubinascii.hexlify(machine.unique_id()), 16)) #which pin is the dht attached to? d = dht.DHT22(machine.Pin(2)) #setup the alarm so that we can deepsleep the device rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # minutes (x) * seconds (60) * microseconds (1000) rtc.alarm(rtc.ALARM0, 3 * 60 * 1000) #generic method for uploading data def uploadGenericSensorData(valType, val, unit): url = "http://faeredia.asuscomm.com/sensors/collectorGenericSensorData.php" url = url + "?sensorid=" + sensID url = url + "&valuetype=" + valType url = url + "&value=" + val url = url + "&units=" + unit
for j in range(n): if (i // 256) % 2 == 0: val = i & 0xff else: val = 255 - (i & 0xff) np[j] = (val, 0, 0) np.write() demo_clear(np) from machine import Pin, I2C import ustruct import math delay = 2 n = 220 np = neopixel.NeoPixel(machine.Pin(17), n, bpp=4, timing=True) import neopixel import time import random def t(): i2c = I2C(sda=Pin(23), scl=Pin(16)) style = bin(ustruct.unpack('>H', i2c.readfrom(87, 2))[0]) if int(style): return True else: return False def lights(fra, til):
import machine, neopixel, time np = neopixel.NeoPixel(machine.Pin(21), 1) def buzz(): buzzer_pin = machine.Pin(18, machine.Pin.OUT) buzzer = machine.PWM(buzzer_pin) buzzer.freq(1027) buzzer.duty(500) time.sleep(0.5) buzzer.duty(0) time.sleep(1) buzzer.duty(500) time.sleep(1) buzzer.duty(0) Pir = machine.Pin(18, machine.Pin.IN, machine.Pin.PULL_UP) def handle_interrupt(Pir): print(Pir.value()) if Pir.value() == 1: print("Motion Detected") buzz() np[0] = (255, 0, 0) np.write() elif Pir.value() == 0: print("Motion Stopped")
def __init__(self,trig,echo): self.trig=machine.Pin(trig) self.trig.init(machine.Pin.OUT) self.trig.low() self.echo=machine.Pin(echo) self.echo.init(machine.Pin.IN)
import os import time import machine import network import ubinascii import urequests import dht CFG_BSSID = 'SRRU-IoT' CFG_BSSID_PASS = '******' FRONT_LED = machine.Pin(2, machine.Pin.OUT) DHT_SENSOR = dht.DHT22(machine.Pin(5)) #DHT22_SENSOR = dht.DHT22(machine.Pin(4)) def __init__(): FRONT_LED.value(1) def start_ap(): ap = network.WLAN(network.AP_IF) #mac = ubinascii.hexlify(ap.config('mac'),'').decode() #ap.config(essid=CFG_APNAME+'-'+str(mac),password='******',channel=11) #ap.ifconfig(('4.4.4.4', '255.255.255.0', '4.4.4.4', '1.1.1.1')) ap.active(False) def do_connect():
with open('config_matrix.json', 'r') as infile: config = ujson.load(infile) # config: mirror_colors if (config['mirror_colors']): config['colors'] = mirror(config['colors']) # config: pixels - initialize the neopixels and turn them off numberOfPixels = config['pixels'] # print(numberOfPixels) # config: GPIO-pin at which Neopixel is attached din_pin = config['din_pin'] #DIN_PIN 15 # Feather Huzzah and Neopixel featherwing at GPIO15 #DIN_PIN 13 # NodeMCU: neopixels attached to pin D7 (GPIO13) PIXEL_PIN = machine.Pin(din_pin, machine.Pin.OUT) np = neopixel.NeoPixel(PIXEL_PIN, numberOfPixels) off() # pixels off # demo animation... def demo(): # determine the animation function to call animation = globals().get(config['animation'], blank) # ######################################################## # Main loop try: while True: animation(config, np, numberOfPixels) utime.sleep(0.01) except:
# # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # import machine import utime import ustruct pin = machine.Pin(25, machine.Pin.OUT) uart = machine.UART(1,31250) # Basic MIDI handling commands def doMidiNoteOn(note,vel): pin.value(1) print("Note On \t", note, "\t", vel) def doMidiNoteOff(note,vel): pin.value(0) print("Note Off\t", note, "\t", vel) # Implement a simple MIDI decoder. # # MIDI supports the idea of Running Status. #
'numMZ': 0 #num mezclas } # Create new modem object on the right Pins modem = sim800.Modem(MODEM_PWKEY_PIN=4, MODEM_RST_PIN=5, MODEM_POWER_ON_PIN=23, MODEM_TX_PIN=26, MODEM_RX_PIN=27) # ESP32 Pin Layout i2c = I2C(-1, sda=Pin(18), scl=Pin(19), freq=400000) # i2c Pin lcd = ulcd1602.LCD1602(i2c) # LCD1602 OBJ #serv = pca9685.Servo(18,19,0x40) #PCA9585 connted2pin18,19 serv = pca9685.pca9865(18, 19) ds_pin = machine.Pin(4) # DS18b20 Pin ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin)) # DS18B20 OBJ # rutinas SMS # ----------------------------------------------- def smslavar(): #15:19/1-2Riegos print('LV') lcd.puts("#LV", 9, 1) servicio.riego() lcd.puts(" ", 9, 1) def smsriego(): #15:19/1-2Riegos
def __init__(self, pin): ifc = onewire.OneWire(machine.Pin(pin)) self._ds18x20 = ds18x20.DS18X20(ifc) self._sensors = self._ds18x20.scan() print('Found DS devices: ', self._sensors)
# neopixelStick.py - animation for NeoPixel stick 1*8 pixels # # based upon part 2 from Tony Dicola - Adafruit # 2017-0529 PePo: DIN neopixel is D5 / GPIO14 # 2017-0121 PePo based upon neopixelMatrix.py (formely lights.py) # ------------------ import machine import neopixel import utime # import time 2017-0529: is also valid import ujson # import json 2017-0529: is also valid # standard configuration that never changes # NodeMCU: neopixels attached to pin D5 (GPIO14) NEOPIXEL_PIN = 15 #14 PIXEL_PIN = machine.Pin(NEOPIXEL_PIN, machine.Pin.OUT) # ######################################################## # helper-function: mirror the colors to make a ramp up and # ramp down with no repeated colors. def mirror(values): # Add the input values in reverse order to the end of the array # However slice off the very first and very last item (the [1:1] syntax) # to prevent the first and last values from repeating. # for example an input of: # [1, 2, 3] # returns: # [1, 2, 3, 2] # instead of returning: # [1, 2, 3, 3, 2, 1] # which would duplicate 3 and 1 as you loop through the elements values.extend(list(reversed(values))[1:-1])
import time import ubinascii import machine from umqtt.simple import MQTTClient button = machine.Pin(0, machine.Pin.IN) broker_address = '192.168.1.35' client_id = 'esp8266_{}'.format(ubinascii.hexlify(machine.unique_id())) topic = b'button' client = MQTTClient(client_id, broker_address) client.set_last_will(topic, b'dead') client.connect() while True: while True: if button.value() == 0: break time.sleep_ms(20) client.publish(topic, b'toggled') time.sleep_ms(200) client.disconnect()
import machine import uasyncio led = machine.Pin(25, machine.Pin.OUT) btn = machine.Pin(22, machine.Pin.IN) # corotuine async def blink(delay): while True: led.toggle() await uasyncio.sleep(delay) async def button(btn): btn_prev = btn.value() while True: while (btn.value() == 1) or (btn.value() == btn_prev): btn_prev = btn.value() await uasyncio.sleep_ms(40) led.toggle() async def main(): uasyncio.create_task(blink(0.2)) uasyncio.create_task(button(btn)) await uasyncio.sleep(10) uasyncio.run(main())
import uuid import ntptime import machine import sht31 #AWS MQTT client cert example for esp8266 or esp32 running MicroPython 1.9 from umqtt.robust import MQTTClient import time # SHT31 Pin Init i = machine.I2C(sda=machine.Pin(5), scl=machine.Pin(4)) s = sht31.SHT31(i) # Temperature Vals (TRUE) tempLimit = 23.0 tMax = 24.0 # Humidity Vals (TRUE) humidLimit = 90.0 hMax = 97.0 # # Temperature Vals (FALSE) # tempLimit = 30.0 # tMax = 35.0 # # Humidity Vals (FALSE) # humidLimit = 95.0 # hMax = 100.0 # 2 Relay Module Pin Init heaterPin = machine.Pin(0, machine.Pin.OUT) humidiPin = machine.Pin(2, machine.Pin.OUT)
import math COMMAND = 0x80 PROXIMITYRATE = 0x82 LIGHTSENSORRATE = 0x84 PROXIMITYDATA = 0x87 LIGHTSENSORDATA = 0x85 SLAVEADDRPROX = 19 SLAVEADDRTEMP = 64 HUMD = b'\xF5' TEMP = b'\xF3' ap_if = network.WLAN(network.AP_IF) ap_if.active(False) i2c = machine.I2C(machine.Pin(5), machine.Pin(4)) # enable periodic prox measurement i2c.writeto_mem(SLAVEADDRPROX, COMMAND, b'\x07') time.sleep(0.1) # set prox measurement rate to 7sample/sec i2c.writeto_mem(SLAVEADDRPROX, PROXIMITYRATE, b'\x02') time.sleep(0.1) i2c.writeto_mem(SLAVEADDRPROX, LIGHTSENSORRATE, b'\x07') time.sleep(0.1) p12 = machine.Pin(12) pwm12 = machine.PWM(p12) pwm12.freq(500) pwm12.duty(0) target = 1900
def exec_req(url, param_dict): """Function to execute the request This function executes the parsed request. Arguments: url: list, separated by /. So if a user comes to http://example.domain.com/read/1 this argument is ["read","1"] param_dict: dictionary, of the parameters that are sent to the server. """ print("URL:", url, param_dict) if len(url) == 0: with open("identity.json", "r") as f: identity = json.load(f) return """<html> <head> <title>NodeMCU</title> </head> <body> <b>Location: {}</b> </body> </html> """.format(identity["location"]) elif url[0] == 'write': pin_id = int(url[1]) try: pin = machine.Pin(pin_id, machine.Pin.OUT) except: return { "status": "Error, pin value {} is inaccessible".format(pin_id) } else: if url[2] == 'on': pin.on() return {"status": "Pin {} is on".format(str(pin_id))} elif url[2] == 'off': pin.off() return {"status": "Pin {} is off".format(str(pin_id))} else: return { "status": "{} is not a valid input for pin {} status".format( url[3], pin_id) } elif url[0] == 'read': try: pin_id = int(url[1]) if "pull" in param_dict.keys(): pull = param_dict["pull"] else: pull = None if pull == "up": pull = machine.Pin.PULL_UP elif pull == "down": pull = machine.Pin.PULL_DOWN pin = machine.Pin(pin_id, machine.Pin.IN, pull) #todo return {"value": pin.value()} except: return {"Status": "Error"} elif url[0] == "measure": pin_id = int(url[1]) measurement_type = param_dict.get("type") if measurement_type is None: return { "status": "measurement type is required in the query arguments!" } elif measurement_type.lower() == "dht11": # /measure/PIN_ID?type="dht11" try: import dht d = dht.DHT11(machine.Pin(pin_id)) d.measure() return { "temperature": d.temperature(), "humidity": d.humidity() } except: return {"Status": "Error"} elif measurement_type.lower() == "ds18b20": # /measure/PIN_ID?type=ds18b20 import onewire, ds18x20 temperatures = [] try: dat = machine.Pin(pin_id) ds = ds18x20.DS18X20(onewire.OneWire(dat)) roms = ds.scan() ds.convert_temp() time.sleep_ms(750) temperatures = [] for rom in roms: temperature = ds.read_temp(rom) address = hex(int.from_bytes(rom, "little")) temperatures.append({ "id": address, "temperature": round(temperature, 4) }) except Exception as e: return { "status": "{} error while attempting to measure ds18b20 temperature!" .format(repr(e)) } return {"temperatures": [temperatures], "unit": "celsius"} else: return { "status": "{} measurement not implemented.".format( measurement_type.lower()) } elif url[0] == "whoami": with open("identity.json", "r") as f: identity = json.load(f) return identity else: return {"Status": "No Action"}
def __init__(self, port): self.pin = machine.Pin(port[0]) self.pin.init(mode=machine.Pin.OUT, pull=machine.Pin.PULL_DOWN, value=0)
def main(): global device device = next(chromecast) enc = Encoder(12, 13, clicks=2, reverse=False) np = volume.NeoPixelRing(4, device, machine.Pin(15), 16) button = machine.Pin(5, machine.Pin.IN) cast = connect2device(np) current_vol = cast.get_volume print('Connected to:', cast_name[device], device, 'current vol:', current_vol) enc.set_val(current_vol) last_enc_val = current_vol last_change_tick = time.ticks_ms() np.change_device(device, current_vol) while True: val = enc.value if last_enc_val != val: print(val) np.set_vol(val) last_enc_val = val last_change_tick = time.ticks_ms() #CHANGING VOLUME if (time.ticks_diff(time.ticks_ms(), last_change_tick) > 200) and (last_enc_val != current_vol): cast.set_volume(val) current_vol = cast.get_volume print('current volume:', current_vol) #SLEEP AFTER DELAY if (time.ticks_diff(time.ticks_ms(), last_change_tick) > 10000): #10 sec cast.disconnect() np.turn_off() print("SLEEP") esp.deepsleep() #CHANGING CHROMECAST WITH ENCODER BUTTON if button.value(): print('BUTTON PRESSED') b_start = time.ticks_ms() while button.value(): if (time.ticks_diff(time.ticks_ms(), b_start) > 2000): print('STOPPING PLAYBACK') np.stop() cast.stop_playback() time.sleep_ms(1500) np.set_vol(current_vol) last_change_tick = time.ticks_ms() break if time.ticks_diff(time.ticks_ms(), b_start) < 2000: cast.disconnect() prev_device = device device = next(chromecast) if device is not prev_device: cast = connect2device(np) current_vol = cast.get_volume enc.set_val(current_vol) np.change_device(device, current_vol) print('switched to:', cast_name[device], device, 'current vol:', current_vol) last_change_tick = time.ticks_ms() time.sleep_ms(100)
import machine, time, bme280_float, config, wifitools i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22)) bme = bme280_float.BME280(i2c=i2c) ssid = config.ssid password = config.password api_key = config.API_KEY MAC_address = config.MAC_ADDRESS wifitools.connect(ssid, password) time.sleep(5) while True: reading = bme.read_compensated_data() temperature = reading[0] pressure = reading[1] / 100 humidity = reading[2] data = str(temperature) + ',' + str(humidity) + ',' + str(pressure) try: wifitools.flaskiot_post(api_key, MAC_address, data) print('sent data') except: pass time.sleep(60)
import machine import time import dht DHT = dht.DHT11(machine.Pin(13)) while True: DHT.measure() print('Temp:', DHT.temperature(), 'Hum:', DHT.humidity()) time.sleep_ms(1000)
# ejemplo basado en http://docs.micropython.org/en/latest/esp8266/tutorial/onewire.html?highlight=onewire import onewire import ds18x20 import machine datos = machine.Pin(13) ds = ds18x20.DS18X20(onewire.OneWire(datos)) ids = ds.scan() # ids [bytearray(b'(\xf4\xe9\x00\x00\x00\x80\x15')] ds.convert_temp() ds.read_temp(ids[0])