class Ultrasonic(object): def __init__(self, trigger_pin, echo_pin, timeout_us=30000): # WARNING: Don't use PA4-X5 or PA5-X6 as echo pin without a 1k resistor # Default timeout is a bit more than the HC-SR04 max distance (400 cm): # 400 cm * 29 us/cm (speed of sound ~340 m/s) * 2 (round-trip) self.timeout = timeout_us # Init trigger pin (out) self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None) self.trigger.off() # Init echo pin (in) self.echo = Pin(echo_pin, mode=Pin.IN, pull=None) def distance_in_inches(self): return (self.distance_in_cm() * 0.3937) def distance_in_cm(self): # Send a 10us pulse self.trigger.on() sleep_us(10) self.trigger.off() # Wait for the pulse and calc its duration time_pulse = time_pulse_us(self.echo, 1, self.timeout) if time_pulse < 0: raise MeasurementTimeout(self.timeout) # Divide the duration of the pulse by 2 (round-trip) and then divide it # by 29 us/cm (speed of sound = ~340 m/s) return (time_pulse / 2) / 29
from machine import Pin from time import sleep LED = Pin(16, Pin.OUT) while (True): LED.on() sleep(0.2) LED.off() sleep(0.2)
def callback(p): print('pin change', p) from machine import Pin p0 = Pin(5, Pin.IN) p0.on() p2 = Pin(2, Pin.IN) p0.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback) p2.irq(trigger=Pin.IRQ_FALLING, handler=callback)
from machine import Pin import mch22 SPI_ID = 2 #ESP32 spi bus connected to fpga PIN_CS = 27 #GPIO27 on esp32 pin_cs = Pin(PIN_CS, Pin.OUT) pin_cs.on() def reset(state): """Reset the fpga Parameters: state (bool): True reset fpga, False release reset Returns: None """ mch22.fpga_reset(not state) def chip_select(state): """Set CS of the fpga Parameters: state (bool): True cs high, False cs low Returns: None """ pin_cs.value(state)
class Keleido: def __init__(self, wifiName, wifiPasswd, flexTopic, accTopic, BrokerIP, flexSclPin=5, flexSdaPin=4, accSclPin=0, accSdaPin=16, wifiLEDPin=2): # constants declaration self.BrokerIP = BrokerIP self.flexTopic = flexTopic self.accTopic = accTopic # connnect Wifi (self.apIf, self.staIf) = self.connectToWifi(wifiName, wifiPasswd) # init flex sensor self.i2c_flex = self.initFlexSensor(flexSclPin, flexSdaPin) # init accelerometer self.lis3dh = LIS3DH(accSclPin, accSdaPin) # init WiFi LED indicator, active low self.wifiLED = Pin(wifiLEDPin, Pin.OUT) self.wifiLED.on() while (self.staIf.isconnected() != True): pass # turn on WiFi LED self.wifiLED.off() self.printWifiStatus() # mqtt client init self.mqttClient = MQTTClient(machine.unique_id(), self.BrokerIP) self.mqttClient.connect() self.enableWebREPL() def initFlexSensor(self, flexSclPin, flexSdaPin): i2c_flex = I2C(scl=Pin(flexSclPin), sda=Pin(flexSdaPin), freq=100000) i2cportNo = i2c_flex.scan() self.ADSAddr = i2cportNo[0] # write to config register 0x01 # CONTINUOUS_READ=0000 010 0 100 0 0 0 11 CONTINUOUS_READ = bytearray([0b01000100, 0b10000011]) #CONTINUOUS_READ=bytearray([0b00100100, 0b10000011]) #CONTINUOUS_READ=bytearray([0x24, 0x83]) print(CONTINUOUS_READ) i2c_flex.writeto_mem(self.ADSAddr, 1, CONTINUOUS_READ) return i2c_flex def readFlexData(self): # read 2 bytes from conversion register return self.i2c_flex.readfrom_mem(self.ADSAddr, 0, 2) def readAccData(self): """ output acceleration in x y z direction """ return self.lis3dh.acceleration() def convertData(self): """ read raw data and convert into somthing meaningful """ data = self.readFlexData() intData = int.from_bytes(data, 'big') print(intData) # """ # if intData >= 26800: # #angleOfFlex = 200 # elif intData > 25000: # #angleOfFlex = int (((intData-25000)/90)+180) # elif intData > 12500: # #angleOfFlex = int (((intData-12500)/138)+90) # elif intData > 8600: # angleOfFlex = int ((intData-8600)/43) # temperature has some effect??? not very much though # else: # angleOfFlex = 0 # """ # """ # if intData >= 15500: # angleOfFlex = 200 # elif intData > 14700: # angleOfFlex = int (((intData-14700)/40)+180) # elif intData > 9500: # angleOfFlex = int (((intData-9500)/57)+90) # elif intData > 7200: # angleOfFlex = int ((intData-7200)/25) # else: # angleOfFlex = 0 # """ if intData >= 2330: angleOfFlex = 180 elif intData > 1700: angleOfFlex = int((intData - 1700) / 3.5) else: angleOfFlex = 0 print(angleOfFlex) #print(i2cportNo) #print(data) #print(intData) #print(angleOfFlex) return angleOfFlex def connectToWifi(self, wifiName, password): 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(wifiName, password) # print wifi info print("WiFi connecting... ") return (ap_if, sta_if) def printWifiStatus(self): print("wiFi is connected? ", self.staIf.isconnected()) print("WiFi status: ", self.staIf.status(), "WiFi config: ", self.staIf.ifconfig()) def enableWebREPL(self): webrepl.start() def broadcastData(self, topic, data=bytes("random data heyheyhey", 'utf-8')): """ publish data in bytes """ self.mqttClient.publish(topic, data) def broadcastString(self, inString="No input string\n"): """ publish data in string """ data = bytes(inString, 'utf-8') self.broadcastData(data) def doBatchJob(self): # flex sensor flexData = {} flexData["angle"] = self.convertData() #print(flexData) flexDataJsonString = ujson.dumps(flexData) flexDataByte = bytes(flexDataJsonString, 'utf-8') self.broadcastData(self.flexTopic, flexDataByte) # accelerometer accData = {} (x, y, z) = self.readAccData() accData['x'] = x accData['y'] = y accData['z'] = z accDataByte = bytes(ujson.dumps(accData), 'utf-8') self.broadcastData(self.accTopic, accDataByte)
class Lancha(object): DIR_MIN = 25 DIR_MAX = 125 DIR_CENTER = 75 def __init__(self): self.wifi = None self.mqtt = None self.config = ujson.load(open("settings.json")) self.motor = Pin(4, Pin.OUT) self.servo = PWM(Pin(5), freq=50) self.current_dir = Lancha.DIR_CENTER # duty for servo is between 40 - 115 # servo.duty(100) def wifi_connect(self): self.wifi = network.WLAN(network.STA_IF) self.wifi.active(True) if not self.wifi.isconnected(): print("connect to {} {}".format(self.config["wifi"]["ssid"], self.config["wifi"]["pass"])) self.wifi.connect(self.config["wifi"]["ssid"], self.config["wifi"]["pass"]) while not self.wifi.isconnected(): print("waiting for internet") time.sleep(1) return self.wifi.isconnected() def mqtt_connect(self): cfg = self.config["mqtt"] self.mqtt = MQTTClient(cfg["client_id"], cfg["host"], port=cfg["port"], user=cfg["user"], password=cfg["pass"]) self.mqtt.set_callback(self.message_received) status = self.mqtt.connect() if status == 0: return True return False def mqtt_subscribe(self): cfg = self.config["mqtt"] self.mqtt.subscribe(cfg["topic"]) def message_received(self, topic, msg): print("{}--> {}".format(topic, msg)) payload = ujson.loads(msg) if payload.get("type") == "motor": val = payload.get("value") if val == 1: self.motor.on() print("prender motor") else: self.motor.off() print("apagar motor") elif payload.get("type") == "direction": val = payload.get("value") if val == -1: self.set_left() elif val == 1: self.set_right() elif val == 0: self.set_center() def set_center(self): self.servo.duty(Lancha.DIR_CENTER) def set_left(self): self.servo.duty(Lancha.DIR_MAX - 25) def set_right(self): self.servo.duty(Lancha.DIR_MIN + 25) def run(self): # Blocking wait for message #self.mqtt.wait_msg() print("RUN!") while True: self.mqtt.check_msg() time.sleep(.1)
class ATM90e32: ############################################################################## def __init__(self, linefreq, pgagain, ugain, igainA, igainB, igainC): self._linefreq = linefreq self._pgagain = pgagain self._ugain = ugain self._igainA = igainA self._igainB = igainB self._igainC = igainC # HSPI Pins mosi_pin = Pin(13) miso_pin = Pin(12) sck_pin = Pin(14) cs_pin = 15 # Chip select pin self.cs = Pin(cs_pin, Pin.OUT) # not using SPI, set to HIGH self.cs.on() # Setting SPI for what works for SAMD.... # Doc on esp8266 SPI hw init: http://bit.ly/2ZhqeRB self.device = SPI(1, baudrate=200000, sck=sck_pin, mosi=mosi_pin, miso=miso_pin, polarity=1, phase=1) self.num_write_failed = 0 self._init_config() if self.num_write_failed > 0: # Can't write to registers..probably not connected. print(self.num_write_failed) raise OSError(NoMonitor().number, NoMonitor().explanation) def _init_config(self): # CurrentGainCT2 = 25498 #25498 - SCT-013-000 100A/50mA if (self._linefreq == 4485 or self._linefreq == 5231): # North America power frequency FreqHiThresh = 61 * 100 FreqLoThresh = 59 * 100 sagV = 90 else: FreqHiThresh = 51 * 100 FreqLoThresh = 49 * 100 sagV = 190 # calculation for voltage sag threshold - assumes we do not want to go under 90v for split phase and 190v otherwise # sqrt(2) = 1.41421356 fvSagTh = (sagV * 100 * 1.41421356) / (2 * self._ugain / 32768) # convert to int for sending to the atm90e32. vSagTh = self._round_number(fvSagTh) self._spi_rw(SPI_WRITE, SoftReset, 0x789A) # Perform soft reset # enable register config access self._spi_rw(SPI_WRITE, CfgRegAccEn, 0x55AA) self._spi_rw(SPI_WRITE, MeterEn, 0x0001) # Enable Metering self._spi_rw(SPI_WRITE, SagTh, vSagTh) # Voltage sag threshold # High frequency threshold - 61.00Hz self._spi_rw(SPI_WRITE, FreqHiTh, FreqHiThresh) # Lo frequency threshold - 59.00Hz self._spi_rw(SPI_WRITE, FreqLoTh, FreqLoThresh) self._spi_rw(SPI_WRITE, EMMIntEn0, 0xB76F) # Enable interrupts self._spi_rw(SPI_WRITE, EMMIntEn1, 0xDDFD) # Enable interrupts self._spi_rw(SPI_WRITE, EMMIntState0, 0x0001) # Clear interrupt flags self._spi_rw(SPI_WRITE, EMMIntState1, 0x0001) # Clear interrupt flags # ZX2, ZX1, ZX0 pin config self._spi_rw(SPI_WRITE, ZXConfig, 0x0A55) # Set metering config values (CONFIG) # PL Constant MSB (default) - Meter Constant = 3200 - PL Constant = 140625000 self._spi_rw(SPI_WRITE, PLconstH, 0x0861) # PL Constant LSB (default) - this is 4C68 in the application note, which is incorrect self._spi_rw(SPI_WRITE, PLconstL, 0xC468) # Mode Config (frequency set in main program) self._spi_rw(SPI_WRITE, MMode0, self._linefreq) # PGA Gain Configuration for Current Channels - 0x002A (x4) # 0x0015 (x2) # 0x0000 (1x) self._spi_rw(SPI_WRITE, MMode1, self._pgagain) # Active Startup Power Threshold - 50% of startup current = 0.9/0.00032 = 2812.5 # self._spi_rw(SPI_WRITE, PStartTh, 0x0AFC) # Testing a little lower setting...because readings aren't hapenng if power is off then # turned on.... # Startup Power Threshold = .4/.00032 = 1250 = 0x04E2 # Just checking with 0. self._spi_rw(SPI_WRITE, PStartTh, 0x0000) # Reactive Startup Power Threshold # self._spi_rw(SPI_WRITE, QStartTh, 0x0AEC) self._spi_rw(SPI_WRITE, QStartTh, 0x0000) # Apparent Startup Power Threshold self._spi_rw(SPI_WRITE, SStartTh, 0x0000) # Active Phase Threshold = 10% of startup current = 0.06/0.00032 = 187.5 # self._spi_rw(SPI_WRITE, PPhaseTh, 0x00BC) self._spi_rw(SPI_WRITE, PPhaseTh, 0x0000) self._spi_rw(SPI_WRITE, QPhaseTh, 0x0000) # Reactive Phase Threshold # Apparent Phase Threshold self._spi_rw(SPI_WRITE, SPhaseTh, 0x0000) # Set metering calibration values (CALIBRATION) self._spi_rw(SPI_WRITE, PQGainA, 0x0000) # Line calibration gain self._spi_rw(SPI_WRITE, PhiA, 0x0000) # Line calibration angle self._spi_rw(SPI_WRITE, PQGainB, 0x0000) # Line calibration gain self._spi_rw(SPI_WRITE, PhiB, 0x0000) # Line calibration angle self._spi_rw(SPI_WRITE, PQGainC, 0x0000) # Line calibration gain self._spi_rw(SPI_WRITE, PhiC, 0x0000) # Line calibration angle # A line active power offset self._spi_rw(SPI_WRITE, PoffsetA, 0x0000) # A line reactive power offset self._spi_rw(SPI_WRITE, QoffsetA, 0x0000) # B line active power offset self._spi_rw(SPI_WRITE, PoffsetB, 0x0000) # B line reactive power offset self._spi_rw(SPI_WRITE, QoffsetB, 0x0000) # C line active power offset self._spi_rw(SPI_WRITE, PoffsetC, 0x0000) # C line reactive power offset self._spi_rw(SPI_WRITE, QoffsetC, 0x0000) # Set metering calibration values (HARMONIC) # A Fund. active power offset self._spi_rw(SPI_WRITE, POffsetAF, 0x0000) # B Fund. active power offset self._spi_rw(SPI_WRITE, POffsetBF, 0x0000) # C Fund. active power offset self._spi_rw(SPI_WRITE, POffsetCF, 0x0000) # A Fund. active power gain self._spi_rw(SPI_WRITE, PGainAF, 0x0000) # B Fund. active power gain self._spi_rw(SPI_WRITE, PGainBF, 0x0000) # C Fund. active power gain self._spi_rw(SPI_WRITE, PGainCF, 0x0000) # Set measurement calibration values (ADJUST) self._spi_rw(SPI_WRITE, UgainA, self._ugain) # A Voltage rms gain # A line current gain self._spi_rw(SPI_WRITE, IgainA, self._igainA) self._spi_rw(SPI_WRITE, UoffsetA, 0x0000) # A Voltage offset self._spi_rw(SPI_WRITE, IoffsetA, 0x0000) # A line current offset self._spi_rw(SPI_WRITE, UgainB, self._ugain) # B Voltage rms gain # B line current gain self._spi_rw(SPI_WRITE, IgainB, self._igainB) self._spi_rw(SPI_WRITE, UoffsetB, 0x0000) # B Voltage offset self._spi_rw(SPI_WRITE, IoffsetB, 0x0000) # B line current offset self._spi_rw(SPI_WRITE, UgainC, self._ugain) # C Voltage rms gain # C line current gain self._spi_rw(SPI_WRITE, IgainC, self._igainC) self._spi_rw(SPI_WRITE, UoffsetC, 0x0000) # C Voltage offset self._spi_rw(SPI_WRITE, IoffsetC, 0x0000) # C line current offset self._spi_rw(SPI_WRITE, CfgRegAccEn, 0x0000) # end configuration # In order to get correct results, I needed to insert a 'significant' delay. time.sleep(1) ##################################################################################### @property def lastSpiData(self): reading = self._spi_rw(SPI_READ, LastSPIData, 0xFFFF) return reading ##################################################################################### @property def sys_status0(self): reading = self._spi_rw(SPI_READ, EMMIntState0, 0xFFFF) return reading ##################################################################################### @property def sys_status1(self): reading = self._spi_rw(SPI_READ, EMMIntState1, 0xFFFF) return reading ##################################################################################### @property def meter_status0(self): reading = self._spi_rw(SPI_READ, EMMState0, 0xFFFF) return reading ##################################################################################### @property def en_status0(self): reading = self._spi_rw(SPI_READ, ENStatus0, 0xFFFF) return reading ##################################################################################### @property def meter_status1(self): reading = self._spi_rw(SPI_READ, EMMState1, 0xFFFF) return reading ##################################################################################### @property def line_voltageA(self): reading = self._spi_rw(SPI_READ, UrmsA, 0xFFFF) return reading / 100.0 ##################################################################################### @property def line_voltageB(self): reading = self._spi_rw(SPI_READ, UrmsB, 0xFFFF) return reading / 100.0 ##################################################################################### @property def line_voltageC(self): reading = self._spi_rw(SPI_READ, UrmsC, 0xFFFF) return reading / 100.0 ##################################################################################### @property def line_currentA(self): reading = self._spi_rw(SPI_READ, IrmsA, 0xFFFF) return reading / 1000.0 ##################################################################################### @property def line_currentC(self): reading = self._spi_rw(SPI_READ, IrmsC, 0xFFFF) return reading / 1000.0 ##################################################################################### @property def frequency(self): reading = self._spi_rw(SPI_READ, Freq, 0xFFFF) return reading / 100.0 ##################################################################################### @property def total_active_power(self): reading = self._read32Register(PmeanT, PmeanTLSB) return reading * 0.00032 ##################################################################################### @property def active_power_A(self): reading = self._read32Register(PmeanA, PmeanALSB) return reading * 0.00032 ##################################################################################### @property def active_power_C(self): reading = self._read32Register(PmeanC, PmeanCLSB) return reading * 0.00032 ##################################################################################### @property def total_reactive_power(self): reading = self._read32Register(QmeanT, PmeanTLSB) return reading * 0.00032 ##################################################################################### @property def reactive_power_A(self): reading = self._read32Register(QmeanA, PmeanALSB) return reading * 0.00032 ##################################################################################### @property def reactive_power_C(self): reading = self._read32Register(QmeanC, PmeanCLSB) return reading * 0.00032 ###################################################### # Support reading a register ###################################################### def read(self, address): reading = self._spi_rw(SPI_READ, address, 0xFFFF) return reading ###################################################### # Support writing to a register ###################################################### def write(self, address, val): print('in write') return self._spi_rw(SPI_WRITE, address, val) ##################################################################################### # do the SPI read or write request. ##################################################################################### def _spi_rw(self, rw, address, val): address |= rw << 15 if (rw): # read return self._readSPI(address) else: for i in range(3): # for robustness try a few times. bWriteSuccess = self._writeSPI(address, val) if (bWriteSuccess or address == SoftReset): # time.sleep_us(3000) # start = time.ticks_us() # print( # 'reading = value. Write successful. It took {} tries.'.format(i)) # print('us ticks: {}'.format( # time.ticks_diff(time.ticks_us(), start))) return True # Write to register didn't work. self.num_write_failed += 1 # print( # 'Calibration write to address {:#04x} not successful.'.format(address)) return False ################################################################################### def _readSPI(self, address): self.cs.off() time.sleep_us(4) # pack the address into a the bytearray. It is an unsigned short(H) that needs to be in MSB(>) two_byte_buf = bytearray(2) results_buf = bytearray(2) struct.pack_into('>H', two_byte_buf, 0, address) self.device.write(two_byte_buf) time.sleep_us(4) self.device.readinto(results_buf) result = struct.unpack('>H', results_buf)[0] self.cs.on() return result ################################################################################## def _writeSPI(self, address, val): self.cs.off() time.sleep_us(4) four_byte_buf = bytearray(4) # pack the address into a the bytearray. It is an unsigned short(H) that needs to be in MSB(>) struct.pack_into('>H', four_byte_buf, 0, address) struct.pack_into('>H', four_byte_buf, 2, val) self.device.write(four_byte_buf) self.cs.on() time.sleep_us(4) reading = self._spi_rw(SPI_READ, LastSPIData, 0xFFFF) if (reading == val): return True return False ################################################################################## def _round_number(self, f_num): if f_num - math.floor(f_num) < 0.5: return math.floor(f_num) return math.ceil(f_num) ################################################################################### def _read32Register(self, regh_addr, regl_addr): val_h = self._spi_rw(SPI_READ, regh_addr, 0xFFFF) val_l = self._spi_rw(SPI_READ, regl_addr, 0xFFFF) val = val_h << 16 val |= val_l # concatenate the 2 registers to make 1 32 bit number if ((val & 0x80000000) != 0): # if val is negative, val = (0xFFFFFFFF - val) + 1 # 2s compliment + 1 return (val)
from machine import Pin import time p_out = Pin(5, Pin.OUT) while True: p_out.on() time.sleep(1) p_out.off() time.sleep(1)
class WebServer: TITLE = "LED Control" GPIO_NUM = 5 def __init__(self): self.pin = Pin(self.GPIO_NUM) self.pin.init(Pin.OUT) self.led_off() def led_off(self): self.pin.on() def led_on(self): self.pin.off() def ok(self, socket, query): socket.write("HTTP/1.1 OK\r\n\r\n") socket.write("<!DOCTYPE html><title>" + self.TITLE + "</title><body>") socket.write(self.TITLE + " status: ") if not self.pin.value(): socket.write("<span style='color:green'>ON</span>") else: socket.write("<span style='color:red'>OFF</span>") socket.write("<br>") if not self.pin.value(): socket.write("<form method='POST' action='/off?" + query.decode() + "'>" + "<input type='submit' value='turn OFF'>" + "</form>") else: socket.write("<form method='POST' action='/on?" + query.decode() + "'>" + "<input type='submit' value='turn ON'>" + "</form>") def err(self, socket, code, message): socket.write("HTTP/1.1 " + code + " " + message + "\r\n\r\n") socket.write("<h1>" + message + "</h1>") def handle(self, socket): (method, url, version) = socket.readline().split(b" ") if b"?" in url: (path, query) = url.split(b"?", 2) else: (path, query) = (url, b"") while True: header = socket.readline() if header == b"": return if header == b"\r\n": break if version != b"HTTP/1.0\r\n" and version != b"HTTP/1.1\r\n": self.err(socket, "505", "Version Not Supported") elif method == b"GET": if path == b"/": self.ok(socket, query) else: self.err(socket, "404", "Not Found") elif method == b"POST": if path == b"/on": self.led_on() self.ok(socket, query) elif path == b"/off": self.led_off() self.ok(socket, query) else: self.err(socket, "404", "Not Found") else: self.err(socket, "501", "Not Implemented") def run(self): server = socket.socket() server.bind(('0.0.0.0', 80)) server.listen(1) while True: try: (sckt, sockaddr) = server.accept() self.handle(sckt) except: sckt.write("HTTP/1.1 500 Internal Server Error\r\n\r\n") sckt.write("<h1>Internal Server Error</h1>") sckt.close()
from machine import Pin # GPIO Table for ESP8266 NodeMCU # 2020/04/12 IN1 = 14 # D5/SCLK/GPIO14 IN2 = 12 # D6/MISO/GPIO12 IN3 = 13 # D7/MOSI/GPIO13 IN4 = 15 # D8/CS/GPIO15 ENA = 5 # D1 ENB = 4 # D2 p14 = Pin(14, Pin.OUT) p14.on() p14.value(1) p14.value()
class spiram: def __init__(self): self.led = Pin(5, Pin.OUT) self.led.off() self.rom="48.rom" #self.rom="opense.rom" #self.rom="/sd/zxspectrum/48.rom" self.spi_channel = const(2) self.init_pinout_sd() self.spi_freq = const(4000000) self.hwspi=SPI(self.spi_channel, baudrate=self.spi_freq, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(self.gpio_sck), mosi=Pin(self.gpio_mosi), miso=Pin(self.gpio_miso)) @micropython.viper def init_pinout_sd(self): self.gpio_sck = const(16) self.gpio_mosi = const(4) self.gpio_miso = const(12) # read from file -> write to SPI RAM def load_stream(self, filedata, addr=0, maxlen=0x10000, blocksize=1024): block = bytearray(blocksize) # Request load self.led.on() self.hwspi.write(bytearray([0,(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF])) bytes_loaded = 0 while bytes_loaded < maxlen: if filedata.readinto(block): self.hwspi.write(block) bytes_loaded += blocksize else: break self.led.off() # read from SPI RAM -> write to file def save_stream(self, filedata, addr=0, length=1024, blocksize=1024): bytes_saved = 0 block = bytearray(blocksize) # Request save self.led.on() self.hwspi.write(bytearray([1,(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF, 0])) while bytes_saved < length: self.hwspi.readinto(block) filedata.write(block) bytes_saved += len(block) self.led.off() def ctrl(self,i): self.led.on() self.hwspi.write(bytearray([0, 0xFF, 0xFF, 0xFF, 0xFF, i])) self.led.off() def cpu_halt(self): self.ctrl(2) def cpu_continue(self): self.ctrl(0) def load_z80_compressed_stream(self, filedata, length=0xFFFF): b=bytearray(1) escbyte=bytearray([0xED]) s=0 repeat=0 bytes_loaded=0 while bytes_loaded < length: if filedata.readinto(b): nexts=s if s==0: if b[0]==escbyte[0]: nexts=1 else: self.hwspi.write(b) if s==1: if b[0]==escbyte[0]: nexts=2 else: self.hwspi.write(escbyte) self.hwspi.write(b) nexts=0 if s==2: repeat=b[0] if repeat==0: print("end") break nexts=3 if s==3: self.hwspi.read(repeat,b[0]) nexts=0 s=nexts bytes_loaded += 1 else: break print("bytes loaded %d" % bytes_loaded) def load_z80_v1_compressed_block(self, filedata): self.led.on() self.hwspi.write(bytearray([0,0,0,0x40,0])) # from 0x4000 self.load_z80_compressed_stream(filedata) self.led.off() def load_z80_v23_block(self, filedata): header = bytearray(3) if filedata.readinto(header): length,page = unpack("<HB",header) print("load z80 block: length=%d, page=%d" % (length,page)) else: return False addr = -1 if page==4: addr=0x8000 if page==5: addr=0xC000 if page==8: addr=0x4000 if addr < 0: print("unsupported page ignored") filedata.seek(length,1) return True if length==0xFFFF: compress=0 length=0x4000 else: compress=1 #print("addr=%04X compress=%d" % (addr,compress)) if compress: # Request load self.led.on() self.hwspi.write(bytearray([0,(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF])) self.load_z80_compressed_stream(filedata,length) self.led.off() else: print("uncompressed v2/v3 may need FIXME") self.load_stream(filedata,addr,16384) return True def patch_rom(self,pc,header): # overwrite tape saving code in original ROM # with restore code and data from header code_addr = 0x4C2 header_addr = 0x500 self.led.on() self.hwspi.write(bytearray([0, 0,0,0,0, 0xF3, 0xAF, 0x11, 0xFF, 0xFF, 0xC3, code_addr&0xFF, (code_addr>>8)&0xFF])) # overwrite start of ROM to JP 0x04C2 self.led.off() self.led.on() self.hwspi.write(bytearray([0, 0,0,(code_addr>>8)&0xFF,code_addr&0xFF])) # overwrite 0x04C2 # Z80 code that POPs REGs from header as stack data at 0x500 # z80asm restore.z80asm; hexdump -v -e '/1 "0x%02X,"' a.bin # restores border color, registers I, AFBCDEHL' and AFBCDEHL self.hwspi.write(bytearray([0x31,(header_addr+9)&0xFF,((header_addr+9)>>8)&0xFF,0xF1,0xED,0x47,0xF1,0x1F,0xD3,0xFE,0xD1,0xD9,0xC1,0xD1,0xE1,0xD9,0xF1,0x08,0xFD,0xE1,0xDD,0xE1,0x21,0xE5,0xFF,0x39,0xF9,0xF1,0xC1,0xE1])); self.hwspi.write(bytearray([0x31])) # LD SP, ... self.hwspi.write(header[8:10]) self.hwspi.write(bytearray([0xED])) # IM ... imarg = bytearray([0x46,0x56,0x5E,0x5E]) self.hwspi.write(bytearray([imarg[header[29]&3]])) # IM mode if header[27]: self.hwspi.write(bytearray([0xFB])) # EI header[6]=pc&0xFF header[7]=(pc>>8)&0xFF self.hwspi.write(bytearray([0xC3])) # JP ... self.hwspi.write(header[6:8]) # PC address of final JP self.led.off() self.led.on() self.hwspi.write(bytearray([0, 0,0,(header_addr>>8)&0xFF,header_addr&0xFF])) # overwrite 0x0500 with header # header fix: exchange A and F, A' and F' to become POPable x=header[0] header[0]=header[1] header[1]=x x=header[21] header[21]=header[22] header[22]=x if header[12]==255: header[12]=1 #header[12] ^= 7<<1 # FIXME border color self.hwspi.write(header) # AF and AF' now POPable self.led.off() def loadz80(self,filename): z=open(filename,"rb") header1 = bytearray(30) z.readinto(header1) pc=unpack("<H",header1[6:8])[0] self.cpu_halt() self.load_stream(open(self.rom, "rb"), addr=0) if pc: # V1 format print("Z80 v1") self.patch_rom(pc,header1) if header1[12] & 32: self.load_z80_v1_compressed_block(z) else: self.load_stream(z,0x4000) else: # V2 or V3 format word = bytearray(2) z.readinto(word) length2 = unpack("<H", word)[0] if length2 == 23: print("Z80 v2") else: if length2 == 54 or length2 == 55: print("Z80 v3") else: print("unsupported header2 length %d" % length2) return header2 = bytearray(length2) z.readinto(header2) pc=unpack("<H",header2[0:2])[0] self.patch_rom(pc,header1) while self.load_z80_v23_block(z): pass self.ctrl(3) # reset and halt self.ctrl(1) # only reset self.cpu_continue() # restore original ROM after image starts self.cpu_halt() self.load_stream(open(self.rom, "rb"), addr=0) self.cpu_continue() # release reset
import time from machine import Pin motorA1 = Pin(14, Pin.OUT) motorA2 = Pin(12, Pin.OUT) while True: motorA1.on() motorA2.off() time.sleep_ms(2000) motorA1.off() motorA2.on() time.sleep_ms(2000)
def print_Gyro(): ax, ay, az, gx, gy, gz = imu.read_accelerometer_gyro_data() oled.text('Gyroscope:', 25, 35) oled.text(str(gx), 25, 45) return gx p19 = Pin(19, Pin.IN) p18 = Pin(18, Pin.OUT) p19.irq(trigger = Pin.IRQ_RISING, handler = handle_interrupt) i2c = I2C(-1, scl=Pin(21), sda=Pin(22)) #sets I2C bus at pins 22 and 21 oled_width = 128 oled_height = 64 oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c) #oled object of class SSD1306 rtc = RTC() rtc.datetime((2019,1,1,0,11,20,0,0)) #2019 January first zero hours zero seconds ect imu = ICM20948() while True: if button: print('interrupt') p18.on() sdelay(3) p18.off() button = False print_time() gx = print_Gyro() oled.show()
class BMEserver(WebSocketServer): """ Initialize the server to listen on port 8080 (the 80 port is used by the HTTP server) The default address mask allows connections from anywhere. Use 127.0.0.1 if you want to restrict connection to the local host. 'password' is the password that will be required by the webrepl stuff to connect to the websocket. 'ledpin' is the number of the pin for the builtin LED. If 'debug' is True, a transcript of the communications with the clients will be printed in the console. """ def __init__(self, port=8080, address="0.0.0.0", password='', ledpin=2, debug=False): super().__init__(port, address, password) self._debug = debug self._altitude = 0 self._led = Pin(ledpin, Pin.OUT) self._bme = BME280(Pin(22), Pin(21), 0x76) self._bme.normalmode(BME280.TWENTY_MS) # One measure every 20ms self._bme.filtering( BME280.IIR_8) # average measures in an 8 sample sliding window def buildStatus(self, meas): return "UPDATE %d %d %d %d %d" % (self._led.value(), meas['temp'], meas['press'], meas['hum'], self._altitude) """ Process requests from the client: - LED_ON requests to switch the builtin LED on - LED_OFF requests to switch the builtin LED off - STAT requests to send the status of the LED The only possible answer is "UPDATE X T P H", where X is the status of the LED, T is the temperature in 1/100 °C, P is the pressure in Pascal, H is the relative humidity in 1/100 of percent """ def process_request(self, message): if message is None: # Close server return None meas = self._bme.measure() meas['press'] = BME280.sealevel_pressure(meas, self._altitude) message = message.strip().split() if self._debug: print("# Received: " + str(message)) if message[0] == "LED_ON": self._led.on() answer = self.buildStatus(meas) elif message[0] == "LED_OFF": self._led.off() answer = self.buildStatus(meas) elif message[0] == "SET_ALT": self._altitude = int(message[1]) meas = self._bme.measure() meas['press'] = BME280.sealevel_pressure(meas, self._altitude) answer = self.buildStatus(meas) elif message[0] == "STAT": answer = self.buildStatus(meas) else: answer = "UNKNOWN REQUEST: " + message if self._debug: print("# Answered: " + answer) return answer """ Redefined method to install process_request as the request handler """ def do_accept(self, address): h = super().do_accept(address) # Reuse the superclass behavior if h is None: if self._debug: print("# Rejecting connection from: ", address) else: # if the connection is accepted if self._debug: print("# Accepting connection from: ", address) return self.process_request # return our request handler """ Redefined method to print a message when a connection is closed """ def close_handler(self, wsreader): if self._debug: print("# Closing connection from", self.getClientFromReader(wsreader)[0]) super().close_handler( wsreader ) # Reuse superclass behavior to really close the connection
def ledLoop(): print("Led Loop") yield np_len = 200 np = neopixel.NeoPixel(machine.Pin(0), np_len) for i in range(np_len): np[i] = (0, 0, 0) np.write() adc = ADC(Pin(33)) rst_pin = Pin(13, mode=Pin.OUT, value=False) strobe_pin = Pin(12, mode=Pin.OUT, value=False) # Init sequence rst_pin.on() utime.sleep_us(5) # 100ns Minimum rst_pin.off() octave = [0] * 7 lower_bound = 20 # We'll use only: # - octave[0] = 63 Hz Low # - octave[3] = 1000 Hz Mid # - octave[5] = 6250 Hz Treble bands_array = [0, 3, 5] while True: yield for i in range(7): strobe_pin.off() utime.sleep_us(36) # minimum pulse width = 18us octave[i] = adc.read_u16() strobe_pin.on() utime.sleep_us(100) # Strobe to strobe # Save Octave result to LED # 7 bands, np_led LEDs bands = len(bands_array) led_per_band = math.floor(np_len / bands) average_octave = octave offset = 0 for b in range(bands): # Each octave i = bands_array[b] if octave[i] != 0: threshold = math.floor(led_per_band * (average_octave[i] - lower_bound) / (65535 - lower_bound)) else: threshold = led_per_band octave[i] = 65536 if threshold < 0: threshold = 0 for j in range(led_per_band): if j <= threshold: rc_index = (offset * 256 // np_len) + j np[offset + j] = brightness(0.2, wheel(rc_index & 255)) else: np[offset + j] = (0, 0, 0) offset = offset + led_per_band # print(octave) np.write() utime.sleep_us(10)
def on_message(service, message): print(message) client = blesync_client.BLEClient(blesync_uart.client.UARTService) def connect(): while True: for device in blesync_client.scan(): if device.adv_name == 'octopus_led': services = client.connect(addr_type=device.addr_type, addr=device.addr) return services[blesync_uart.client.UARTService][0] uart_service = connect() built_in_led.on() sleep(1) built_in_led.off() @led_button.on_press def on_press_top_button(): uart_service.send(b'!B516') @led_button.on_release def on_release_top_button(): uart_service.send(b'!B507')
* 日 期:2018年5月14日 * 历 史: 日期 编辑 版本 记录 2018年5月14日 Robin Chen V0.10 创建文件 ******************************************************************************''' from PYBNano.DisplayModule.LCD.HT1621B.GDC03849 import viewTemp, viewRH from machine import Pin from dht import DHT11 from time import sleep from pyb import LED # DHT11引脚设置 dhtgnd = Pin('Y10', Pin.OUT, Pin.PULL_DOWN) dhtvcc = Pin('Y9', Pin.OUT, Pin.PULL_UP) dhts = Pin('Y8') dhtgnd.off() dhtvcc.on() sleep(2) dt = DHT11(dhts) while True: LED(4).on() dt.measure() LED(4).off() LED(3).on() te = dt.temperature() # 温度 dh = dt.humidity() # 湿度 viewTemp(te) viewRH(dh) LED(3).off() print('当前温度:', te, ' | 当前湿度:', dh) sleep(2)
import bme280
class Tempstation(): """Tempstation according to the Tempstation API.""" MAC_ADDRESS = str(hexlify(WLAN().config('mac')).decode()) SENSOR = None ID = 0 TEMP_MIN = 0 TEMP_MAX = 0 HUM_MIN = 0 HUM_MAX = 0 INTERVAL = 0 LED_BLUE = None LED_RED = None LED_GREEN = None def set_up_pins(self): """Set up all necessary pins on the board.""" self.SENSOR = dht.DHT22(Pin(4)) self.LED_BLUE = Pin(2, Pin.OUT) self.LED_BLUE.on() self.LED_RED = Pin(13, Pin.OUT) self.LED_RED.on() self.LED_GREEN = Pin(12, Pin.OUT) self.LED_GREEN.on() print("Pins are set up.") def initialize_controller_data(self): """Assign controller values given by the API.""" api_data = urequests.get( credentials.get_controller_data.format( hardware_id=self.MAC_ADDRESS)).json() print("Received following API data: ", api_data) self.ID = api_data['id'] critical_values = api_data['location']['criticalValues'] for values in critical_values: if (values['id'] == 1): self.TEMP_MIN = values['minValue'] self.TEMP_MAX = values['maxValue'] if (values['id'] == 2): self.HUM_MIN = values['minValue'] self.HUM_MAX = values['maxValue'] self.INTERVAL = api_data['settings']['measureDuration'] print("Assigned controller values from the API.") def _give_led_signal(self, values): """Light the LED to signal if measured data breaks critical values.""" if ((values['temperature'][0] > self.TEMP_MAX) or (values['humidity'][0] > self.HUM_MAX) or (values['temperature'][0] < self.TEMP_MIN) or (values['humidity'][0] < self.HUM_MIN)): for i in range(0, 3): self.LED_RED.off() sleep(1) self.LED_RED.on() sleep(1) else: for i in range(0, 3): self.LED_GREEN.off() sleep(1) self.LED_GREEN.on() sleep(1) def measure_and_post(self): """Measure data and post to the API.""" self.LED_BLUE.off() values = {} self.SENSOR.measure() values['temperature'] = [self.SENSOR.temperature(), 1] values['humidity'] = [self.SENSOR.humidity(), 2] print("Measured the following: ", values) for key in values: data_dict = {} data_dict['value'] = values[key][0] data_dict['unitId'] = values[key][1] resp = urequests.post( credentials.post_data.format(station_ID=self.ID), data=ujson.dumps(data_dict), headers={'Content-Type': 'application/json'}) print("Sending", key, resp.status_code, resp.text) self.LED_BLUE.on() sleep(2) self._give_led_signal(values)
class LED: """Define a LED on a defined pin""" def __init__(self, LEDPin=2): self.LEDPin = Pin(LEDPin, Pin.OUT) print("New LED defined on Pin %s" % LEDPin) def Blink(self, number, timeon=0.2, timeoff=0.2): """Blinks the LED (number) times, (timeon) and (timeoff) are self explanatory""" for x in range(number): self.LEDPin.off() sleep(timeon) self.LEDPin.on() sleep(timeoff) def Pulse(self, seconds, Speed=1): """Helper function for Morse Code""" self.LEDPin.off() sleep(seconds) self.LEDPin.on() sleep(0.1 * Speed) def Morse(self, text, Speed=1): """Blinks (text) in morse code. Speed is around 60 cpm at 1 and proportional""" Speed = 1 / Speed Dot = 0.1 * Speed Dash = 0.3 * Speed SpaceInLetter = 0.1 * Speed SpaceBetweenLetters = 0.3 * Speed Space = 0.7 * Speed alphabet = { ' ': ' ', 'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '.': '.-.-.-', } print("morsing %s" % text) for c in text: for m in alphabet[c.lower()]: if m == '.': self.Pulse(Dot, Speed) if m == '-': self.Pulse(Dash, Speed) if m == ' ': sleep(Space) sleep(SpaceBetweenLetters)
from receiver2 import * from machine import Pin s = Pin(15, Pin.OUT) s.on() if s.value() == 1: receiver() else: pass #download
from machine import Pin, I2C, UART from ssd1306 import SSD1306_I2C import utime #uart = UART(2, 9600) pin16 = Pin(16, Pin.OUT) pin16.on() i2c = I2C(scl=Pin(15), sda=Pin(4)) oled = SSD1306_I2C(128, 64, i2c) oled.fill(1) #def print_oled(value): # #led.on() # #pin16.init(mode=pin16.OUT) # #pin16.on() # utime.sleep_ms(500) # oled.fill(1) # oled.text('Wert ist: {}'.format(value), 10, 10, 1) # pin16.init(mode=pin16.IN) # #led.off() while True: #counter = uart.readline() #if counter is not None: for counter in range(10): # print_oled(counter) utime.sleep(1)
class osd: def __init__(self): self.screen_x = const(64) self.screen_y = const(20) self.cwd = "/" self.init_fb() self.exp_names = " KMGTE" self.mark = bytearray([32,16,42]) # space, right triangle, asterisk self.read_dir() self.spi_read_irq = bytearray([1,0xF1,0,0,0,0,0]) self.spi_read_btn = bytearray([1,0xFB,0,0,0,0,0]) self.spi_result = bytearray(7) self.spi_enable_osd = bytearray([0,0xFE,0,0,0,1]) self.spi_write_osd = bytearray([0,0xFD,0,0,0]) self.spi_channel = const(2) self.spi_freq = const(3000000) self.init_pinout_sd() #self.spi=SPI(self.spi_channel, baudrate=self.spi_freq, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(self.gpio_sck), mosi=Pin(self.gpio_mosi), miso=Pin(self.gpio_miso)) self.init_spi() alloc_emergency_exception_buf(100) self.enable = bytearray(1) self.timer = Timer(3) self.irq_handler(0) self.irq_handler_ref = self.irq_handler # allocation happens here self.spi_request = Pin(0, Pin.IN, Pin.PULL_UP) self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref) def init_spi(self): self.spi=SPI(self.spi_channel, baudrate=self.spi_freq, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=Pin(self.gpio_sck), mosi=Pin(self.gpio_mosi), miso=Pin(self.gpio_miso)) self.cs=Pin(self.gpio_cs,Pin.OUT) self.cs.off() # init file browser def init_fb(self): self.fb_topitem = 0 self.fb_cursor = 0 self.fb_selected = -1 @micropython.viper def init_pinout_sd(self): self.gpio_cs = const(5) self.gpio_sck = const(16) self.gpio_mosi = const(4) self.gpio_miso = const(12) @micropython.viper def irq_handler(self, pin): p8result = ptr8(addressof(self.spi_result)) self.cs.on() self.spi.write_readinto(self.spi_read_irq, self.spi_result) self.cs.off() btn_irq = p8result[6] if btn_irq&0x80: # btn event IRQ flag self.cs.on() self.spi.write_readinto(self.spi_read_btn, self.spi_result) self.cs.off() btn = p8result[6] p8enable = ptr8(addressof(self.enable)) if p8enable[0]&2: # wait to release all BTNs if btn==1: p8enable[0]&=1 # clear bit that waits for all BTNs released else: # all BTNs released if (btn&0x78)==0x78: # all cursor BTNs pressed at the same time self.show_dir() # refresh directory p8enable[0]=(p8enable[0]^1)|2; self.osd_enable(p8enable[0]&1) if p8enable[0]==1: if btn==9: # btn3 cursor up self.start_autorepeat(-1) if btn==17: # btn4 cursor down self.start_autorepeat(1) if btn==1: self.timer.deinit() # stop autorepeat if btn==33: # btn6 cursor left self.updir() if btn==65: # btn6 cursor right self.select_entry() def start_autorepeat(self, i:int): self.autorepeat_direction=i self.move_dir_cursor(i) self.timer_slow=1 self.timer.init(mode=Timer.PERIODIC, period=500, callback=self.autorepeat) def autorepeat(self, timer): if self.timer_slow: self.timer_slow=0 self.timer.init(mode=Timer.PERIODIC, period=30, callback=self.autorepeat) self.move_dir_cursor(self.autorepeat_direction) self.irq_handler(0) # catch stale IRQ def select_entry(self): if self.direntries[self.fb_cursor][1]: # is it directory oldselected = self.fb_selected - self.fb_topitem self.fb_selected = self.fb_cursor try: self.cwd = self.fullpath(self.direntries[self.fb_cursor][0]) except: self.fb_selected = -1 self.show_dir_line(oldselected) self.show_dir_line(self.fb_cursor - self.fb_topitem) self.init_fb() self.read_dir() self.show_dir() else: self.change_file() def updir(self): if len(self.cwd) < 2: self.cwd = "/" else: s = self.cwd.split("/")[:-1] self.cwd = "" for name in s: if len(name) > 0: self.cwd += "/"+name self.init_fb() self.read_dir() self.show_dir() def fullpath(self,fname): if self.cwd.endswith("/"): return self.cwd+fname else: return self.cwd+"/"+fname def change_file(self): oldselected = self.fb_selected - self.fb_topitem self.fb_selected = self.fb_cursor try: filename = self.fullpath(self.direntries[self.fb_cursor][0]) except: filename = False self.fb_selected = -1 self.show_dir_line(oldselected) self.show_dir_line(self.fb_cursor - self.fb_topitem) if filename: if filename.endswith(".bit"): self.spi_request.irq(handler=None) self.timer.deinit() self.enable[0]=0 self.osd_enable(0) self.spi.deinit() tap=ecp5.ecp5() tap.prog_stream(open(filename,"rb"),blocksize=1024) if filename.endswith("_sd.bit"): os.umount("/sd") for i in bytearray([2,4,12,13,14,15]): p=Pin(i,Pin.IN) a=p.value() del p,a result=tap.prog_close() del tap gc.collect() #os.mount(SDCard(slot=3),"/sd") # BUG, won't work self.init_spi() # because of ecp5.prog() spi.deinit() self.spi_request.irq(trigger=Pin.IRQ_FALLING, handler=self.irq_handler_ref) self.irq_handler(0) # handle stuck IRQ if filename.endswith(".nes") \ or filename.endswith(".snes") \ or filename.endswith(".smc") \ or filename.endswith(".sfc"): import ld_nes s=ld_nes.ld_nes(self.spi,self.cs) s.ctrl(1) s.ctrl(0) s.load_stream(open(filename,"rb")) del s gc.collect() self.enable[0]=0 self.osd_enable(0) if filename.startswith("/sd/ti99_4a/") and filename.endswith(".bin"): import ld_ti99_4a s=ld_ti99_4a.ld_ti99_4a(self.spi,self.cs) s.load_rom_auto(open(filename,"rb"),filename) del s gc.collect() self.enable[0]=0 self.osd_enable(0) if (filename.startswith("/sd/msx") and filename.endswith(".rom")) \ or filename.endswith(".mx1"): import ld_msx s=ld_msx.ld_msx(self.spi,self.cs) s.load_msx_rom(open(filename,"rb")) del s gc.collect() self.enable[0]=0 self.osd_enable(0) if filename.endswith(".z80"): self.enable[0]=0 self.osd_enable(0) import ld_zxspectrum s=ld_zxspectrum.ld_zxspectrum(self.spi,self.cs) s.loadz80(filename) del s gc.collect() if filename.endswith(".ora") or filename.endswith(".orao"): self.enable[0]=0 self.osd_enable(0) import ld_orao s=ld_orao.ld_orao(self.spi,self.cs) s.loadorao(filename) del s gc.collect() if filename.endswith(".vsf"): self.enable[0]=0 self.osd_enable(0) import ld_vic20 s=ld_vic20.ld_vic20(self.spi,self.cs) s.loadvsf(filename) del s gc.collect() if filename.endswith(".prg"): self.enable[0]=0 self.osd_enable(0) import ld_vic20 s=ld_vic20.ld_vic20(self.spi,self.cs) s.loadprg(filename) del s gc.collect() if filename.endswith(".cas"): self.enable[0]=0 self.osd_enable(0) import ld_trs80 s=ld_trs80.ld_trs80(self.spi,self.cs) s.loadcas(filename) del s gc.collect() if filename.endswith(".cmd"): self.enable[0]=0 self.osd_enable(0) import ld_trs80 s=ld_trs80.ld_trs80(self.spi,self.cs) s.loadcmd(filename) del s gc.collect() @micropython.viper def osd_enable(self, en:int): pena = ptr8(addressof(self.spi_enable_osd)) pena[5] = en&1 self.cs.on() self.spi.write(self.spi_enable_osd) self.cs.off() @micropython.viper def osd_print(self, x:int, y:int, i:int, text): p8msg=ptr8(addressof(self.spi_write_osd)) a=0xF000+(x&63)+((y&31)<<6) p8msg[2]=i p8msg[3]=a>>8 p8msg[4]=a self.cs.on() self.spi.write(self.spi_write_osd) self.spi.write(text) self.cs.off() @micropython.viper def osd_cls(self): p8msg=ptr8(addressof(self.spi_write_osd)) p8msg[3]=0xF0 p8msg[4]=0 self.cs.on() self.spi.write(self.spi_write_osd) self.spi.read(1280,32) self.cs.off() # y is actual line on the screen def show_dir_line(self, y): if y < 0 or y >= self.screen_y: return mark = 0 invert = 0 if y == self.fb_cursor - self.fb_topitem: mark = 1 invert = 1 if y == self.fb_selected - self.fb_topitem: mark = 2 i = y+self.fb_topitem if i >= len(self.direntries): self.osd_print(0,y,0,"%64s" % "") return if self.direntries[i][1]: # directory self.osd_print(0,y,invert,"%c%-57s D" % (self.mark[mark],self.direntries[i][0])) else: # file mantissa = self.direntries[i][2] exponent = 0 while mantissa >= 1024: mantissa >>= 10 exponent += 1 self.osd_print(0,y,invert,"%c%-57s %4d%c" % (self.mark[mark],self.direntries[i][0], mantissa, self.exp_names[exponent])) def show_dir(self): for i in range(self.screen_y): self.show_dir_line(i) def move_dir_cursor(self, step): oldcursor = self.fb_cursor if step == 1: if self.fb_cursor < len(self.direntries)-1: self.fb_cursor += 1 if step == -1: if self.fb_cursor > 0: self.fb_cursor -= 1 if oldcursor != self.fb_cursor: screen_line = self.fb_cursor - self.fb_topitem if screen_line >= 0 and screen_line < self.screen_y: # move cursor inside screen, no scroll self.show_dir_line(oldcursor - self.fb_topitem) # no highlight self.show_dir_line(screen_line) # highlight else: # scroll if screen_line < 0: # cursor going up screen_line = 0 if self.fb_topitem > 0: self.fb_topitem -= 1 self.show_dir() else: # cursor going down screen_line = self.screen_y-1 if self.fb_topitem+self.screen_y < len(self.direntries): self.fb_topitem += 1 self.show_dir() def read_dir(self): self.direntries = [] ls = sorted(os.listdir(self.cwd)) for fname in ls: stat = os.stat(self.fullpath(fname)) if stat[0] & 0o170000 == 0o040000: self.direntries.append([fname,1,0]) # directory else: self.direntries.append([fname,0,stat[6]]) # file gc.collect() # NOTE: this can be used for debugging #def osd(self, a): # if len(a) > 0: # enable = 1 # else: # enable = 0 # self.cs.on() # self.spi.write(bytearray([0,0xFE,0,0,0,enable])) # enable OSD # self.cs.off() # if enable: # self.cs.on() # self.spi.write(bytearray([0,0xFD,0,0,0])) # write content # self.spi.write(bytearray(a)) # write content # self.cs.off() def ctrl(self,i): self.cs.on() self.spi.write(bytearray([0, 0xFF, 0xFF, 0xFF, 0xFF, i])) self.cs.off() def peek(self,addr,length): self.ctrl(2) self.cs.on() self.spi.write(bytearray([1,(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF, 0])) b=bytearray(length) self.spi.readinto(b) self.cs.off() self.ctrl(0) return b def poke(self,addr,data): self.ctrl(2) self.cs.on() self.spi.write(bytearray([0,(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF])) self.spi.write(data) self.cs.off() self.ctrl(0)
pin_out = Pin(2, Pin.OUT) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 11000)) s.listen(5) while True: try: conn, addr = s.accept() print('Nueva conexion %s' % str(addr)) request = conn.recv(1024) comando = str(request, 'utf-8') if comando[0:5] == "final": print("Comando fianl") conn.send("Final del proceso" + "\n") break elif comando[0:5] == "ledon": print("Comando ledon") conn.send("Led encendido" + "\n") pin_out.off() elif comando[0:5] == "ledof": print("Comando ledoff") conn.send("Led apagado" + "\n") pin_out.on() else: print("Envio un comando no reconocido") conn.send("Comando:" + comando + " comando no contemplado" + "\n") conn.close() except: print("Error") conn.close() s.close()
def flash(n=3): for i in range(n): led.on() time.sleep(0.2) led.off() time.sleep(0.2) def beep(tone=440): beeper = PWM(buzzer, freq=tone, duty=512) time.sleep(0.5) beeper.deinit() flash() while True: # Read one command from the sender msg = sys.stdin.readline() if msg != "": if msg == "on\n": led.on() elif msg == "off\n": led.off() elif msg == "beep\n": beep() else: flash()
import sys import ssd1306 from struct import unpack as unp led = Pin(14, Pin.OUT) pump = Pin(13, Pin.OUT) btnLeft = Pin(12, Pin.IN, Pin.PULL_UP) btnDown = Pin(2, Pin.IN, Pin.PULL_UP) btnA = Pin(0, Pin.IN, Pin.PULL_UP) buzzer = Pin(15, Pin.OUT) i2c = I2C(-1, Pin(5), Pin(4)) # SCL, SDA display = ssd1306.SSD1306_I2C(128, 64, i2c) # turn off everything led.on() pump.on() def pressed(btn, wait_release=False): if not btn.value(): sleep_ms(30) if btn.value(): return False #wait for key release while wait_release and not btn.value(): sleep_ms(5) return True return False
# best for relay module is GPIO5, GPIO4, GPIO12, GPIO13, GPIO14 rtc = RTC() # init module realtime hour = rtc.datetime()[4] + 2 # hours, Kiev +2 mint = rtc.datetime()[5] # minut TIME_ON_FRESH_WIND = [0, 0] # [hour, min] FRESH_WIND_POS = 1 # OFF pin print(TIME_ON_FRESH_WIND) TIME_ON_INSIDE_WIND = [0, 0] # [hour, min] INSIDE_WIND_POS = 1 # OFF pin # fresh_wind = Pin(16, Pin.OUT) # init pin 5, GPIO5 fresh_wind.on() # off pin inside_wind = Pin(2, Pin.OUT) # init pin 4, GPIO4 inside_wind.on() # off pin if len(str(rtc.datetime()[5])) == 1: print('{0}:0{1}'.format(hour, mint)) # print to format 00:00 else: print('{0}:{1}'.format(hour, mint)) # print to format 00:00 def inside_wind_on_off(tmr_pause=1, tmr_work=1): mit = rtc.datetime()[5] hou = rtc.datetime()[4] + 2 global INSIDE_WIND_POS, TIME_ON_INSIDE_WIND if INSIDE_WIND_POS == 1: print(mit, TIME_ON_INSIDE_WIND[1])
justification=ugfx.Label.CENTER) ugfx.set_default_font(ugfx.FONT_SMALL) status = ugfx.Label(0, ugfx.height() - info_height * 2 - status_height, ugfx.width(), status_height, "", justification=ugfx.Label.CENTER) # update loop while True: text = "" value_wifi_strength = wifi_strength() value_battery = battery() if value_wifi_strength: text += "Wi-Fi: %s%%, " % int(value_wifi_strength) if value_battery: text += "Battery: %s%%" % int(value_battery) status.text(text) if Buttons.is_pressed(Buttons.BTN_Star): if torch_on: torch_on = False torch.off() neo.display([0, 0]) else: torch_on = True torch.on() neo.display([0xffffff, 0xffffff]) sleep_or_exit(0.5)
# It makes the onboard LED blink # ref: https://docs.micropython.org/en/latest/rp2/quickref.html from typing import Any, Optional import utime as time from machine import Pin # Blink led = Pin(6, Pin.OUT) led = Pin() led = Pin(1, value=2) for i in [1, 2]: # no infinite loop led.on() time.sleep_ms(250) led.off() time.sleep_ms(250) # Timers from machine import Timer tim = Timer(period=5000, mode=Timer.ONE_SHOT, callback=lambda t: print(1)) tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t: print(2)) # Pins and GPIO p0 = Pin(0, Pin.OUT) # create output pin on GPIO0 p0.on() # set pin to "on" (high) level p0.off() # set pin to "off" (low) level
# pinJoystickDown.irq(handler=callbackJoystickDown) ##### PHONE ##### print("INIT PHONE START") sim800.poweron() sim800.btpoweron() # Start the Bluetooth Headset IF necessary if (not sim800.btconnected()): print("BT Headset not connected") pinBTHeadsetOnOff = Pin(Pin.GPIO_FET, Pin.OUT) pinBTHeadsetOnOff.off( ) # take that Pin DOWN same as if someone was pressing the power button on the headset utime.sleep(3) #wait 3 secs for the BT Headset to start pinBTHeadsetOnOff.on() #that was all now sim800.btconnect(sim800.btPairedIdForName("S6"), 6) print("INIT PHONE DONE") def updatePhone(): global ringBell, hookStatus, calling if sim800.isringing(): ringBell = True if hookStatus: sim800.answer() else: ringBell = False # status == 4 means call in progress
# NeoPixelをいくつか(1セグ4個くらい)つないで7セグにし、大会用のタイマーにする。 # 7セグのaからbcdefgと順番に信号線で一直列につなぐ。7セグ1桁のタイマー。 # 残10分から表示し、時間ぎれで点滅+ブザー鳴らす。 # 2017-03-21 by penkich # from machine import Pin,I2C,Timer from neopixel import NeoPixel import time npix = 4 # 1セグを構成するNeoPixelの個数 t = 50 # 時間設定(分) pin = Pin(4,Pin.OUT) # NeoPixelの信号線を接続 np = NeoPixel(pin, 7 * npix) buz = Pin(5,Pin.OUT) # 圧電ブザーを接続 buz.on() # 起動時に少し鳴らす time.sleep(1) buz.off() def seg7(n,rgb): data = [0xfc,0x60,0xda,0xf2,0x66,0xb6,0xbe,0xe4,0xfe,0xe6,0xee] x = data[n] >> 1 out = [] for i in range(7): if x % 2: out.append(rgb) else: out.append(blank) x = x >> 1 out.reverse() tmp = []
oled.framebuf.hline(0, 12, 128, 1) oled.text("A+", 0, 16) oled.text(res["1.8.0_Wh"], 35, 16) oled.text("Wh", 110, 16) oled.text("P:", 0, 31) oled.text(res["16.7.0_W"], 35, 32) oled.text("W", 110, 32) oled.framebuf.hline(0, 48, 128, 1) oled.show() return res ############################################################# onbled.on() # on icon = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 1, 1, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], ] oled.fill(0) # Clear the display for y, row in enumerate(icon):