def _raw_temp_humi(self, temp_acc=RES_14_BIT, humi_acc=RES_14_BIT): """ Initiate a temperature and humidity sensor reading in one operation. This safes time (and thereby energy). Accuracy for both sensors can be specified. Same valid accuracy values apply to both seonsors. """ if not temp_acc in (RES_11_BIT, RES_14_BIT): raise ValueError('Temperature measure accuracy invalid!') if not temp_acc in (RES_8_BIT, RES_11_BIT, RES_14_BIT): raise ValueError('Humidity measure accuracy invalid!') config = C_MODE_BOTH if temp_acc == RES_11_BIT: config = config | C_TEMP_11BIT elif temp_acc == RES_14_BIT: config = config | C_TEMP_14BIT if humi_acc == RES_8_BIT: config = config | C_HUMI_8BIT elif humi_acc == RES_11_BIT: config = config | C_HUMI_11BIT elif humi_acc == RES_14_BIT: config = config | C_HUMI_14BIT self._config(config) self._send(R_TEMP) sleep_ms(20) raw = self._recv(4) return (raw[1] + (raw[0] << 8), raw[3] + (raw[2] << 8))
def readAltitude(): toggleOneShot() # Toggle the OST bit causing the sensor to immediately take another reading # Wait for PDR bit, indicates we have new data counter = 0 while( (IIC_Read(STATUS) & 0x02) == 0): counter = counter + 1 if(counter > 600): # Error out after max of 512ms for a read return(-1) time.sleep_ms(1) # Read pressure registers data = bytearray(3) counter = 0 nBytes = 0 while True: nBytes = i2c.readfrom_mem_into(MPL3115Address, OUT_P_MSB, data) if nBytes == 3: break counter = counter + 1 if(counter > 500): # Error out after max of 512ms for a read return(0x00) time.sleep_ms(1) # wait 1msec msb = data[0] csb = data[1] lsb = data[2] value = (msb << 16) | (csb << 8) | lsb value = value >> 4 Height = float(value) / 16.0 return(Height)
def __init__(self, i2c=None, sda='P22', scl='P21'): if i2c is not None: self.i2c = i2c else: self.i2c = I2C(0, mode=I2C.MASTER, pins=(sda, scl)) self.sda = sda self.scl = scl self.clk_cal_factor = 1 self.reg = bytearray(6) self.wake_int = False try: self.read_fw_version() except Exception: time.sleep_ms(2) try: # init the ADC for the battery measurements self.poke_memory(ANSELC_ADDR, 1 << 2) self.poke_memory(ADCON0_ADDR, (0x06 << _ADCON0_CHS_POSN) | _ADCON0_ADON_MASK) self.poke_memory(ADCON1_ADDR, (0x06 << _ADCON1_ADCS_POSN)) # enable the pull-up on RA3 self.poke_memory(WPUA_ADDR, (1 << 3)) # make RC5 an input self.set_bits_in_memory(TRISC_ADDR, 1 << 5) # set RC6 and RC7 as outputs and enable power to the sensors and the GPS self.mask_bits_in_memory(TRISC_ADDR, ~(1 << 6)) self.mask_bits_in_memory(TRISC_ADDR, ~(1 << 7)) if self.read_fw_version() < 6: raise ValueError('Pytrack firmware out of date') except Exception: raise Exception('Pytrack board not detected')
def set_amp(n): global act_amp print('Change Amp from ',act_amp,' to ',n) if n == 2: amp1l.low() amp1r.low() ledl.low() time.sleep_ms(200) amp2l.high() amp2r.high() ledr.high() act_amp = 2 try: mqtt.publish(MQTT_TOPIC_STATE, b"2") except: print('send state to MQTT failed!') else: amp2l.low() amp2r.low() ledr.low() time.sleep_ms(200) amp1l.high() amp1r.high() ledl.high() act_amp = 1 try: mqtt.publish(MQTT_TOPIC_STATE, b"1") except: print('send state to MQTT failed!')
def connectWiFi(self,ssid,passwd): self.sta.active(True) self.sta.connect(ssid,passwd) while(self.sta.ifconfig()[0]=='0.0.0.0'): sleep_ms(200) print('Connecting to network...') print('WiFi Connection Successful,Network Config:%s'%str(self.sta.ifconfig()))
def waitSecs(n,debug=False): s = "wait " + str(n) + " seconds..." print(s) if debug: time.sleep(n) else: time.sleep_ms(int(1000*n))
def do_connect(): import network sta_if = network.WLAN(network.STA_IF) start = time.ticks_ms() # get millisecond counter if not sta_if.isconnected(): print('Connecting to network...') sta_if.active(True) sta_if.connect(WIFI_SSID, WIFI_PASSWORD) while not sta_if.isconnected(): print('Waiting for connection...') time.sleep_ms(500) pin.value(not pin.value()) # Toggle the LED while trying to connect # compute time difference since we started looking for the network # If it's greater than 10s, we'll time out and just start up as # an access point. delta = time.ticks_diff(time.ticks_ms(), start) if delta > 10000: print('\r\nTimeout on network connection. Please:') print(' * check the SSID and password \r\n * connect to the esp8266 Access Point\r\n') break print('Network Configuration:', sta_if.ifconfig()) pin.high() # Turn off the LED connected
def begin( self ): """ Init the Gameduino """ self.ssel.value(1) # disable SSEL sleep_ms( 400 ) # wait 400ms for initialization self.wr( J1_RESET, 1) # HALT coprocessor # Hide all sprites (move them out id the view area) self.__wstart(RAM_SPR) # start Write transaction @ add = RAM_SPR for i in range( 512 ): self.xhide() self.__end() self.fill( RAM_PIC , 0x00, 1024 * 10) # Zero all character RAM self.fill( RAM_SPRPAL, 0x00, 2048) # Sprite palletes black self.fill( RAM_SPRIMG, 0x00, 64 * 256) # Clear all sprite data self.fill( VOICES , 0x0, 256) # Silence self.fill( PALETTE16A, 0x0, 128) # Black 16-, 4-palletes and COMM self.wr16( SCROLL_X , 0) self.wr16( SCROLL_Y , 0) self.wr ( JK_MODE , 0) self.wr ( SPR_DISABLE, 0) self.wr ( SPR_PAGE , 0) self.wr ( IOMODE , 0) self.wr16( BG_COLOR , 0) self.wr16( SAMPLE_L , 0) self.wr16( SAMPLE_R , 0) self.wr16( SCREENSHOT_Y, 0) self.wr ( MODULATOR , 64)
def activity(self): if not self.debounced: time.sleep_ms(self.act_dur) self.debounced = True if self.int_pin(): return True return False
def __init__(self, i2c_bus): # create i2c obect _bmp_addr = self._bmp_addr self._bmp_i2c = i2c_bus self._bmp_i2c.start() self.chip_id = self._bmp_i2c.readfrom_mem(_bmp_addr, 0xD0, 2) # read calibration data from EEPROM self._AC1 = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xAA, 2))[0] self._AC2 = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xAC, 2))[0] self._AC3 = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xAE, 2))[0] self._AC4 = unp('>H', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xB0, 2))[0] self._AC5 = unp('>H', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xB2, 2))[0] self._AC6 = unp('>H', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xB4, 2))[0] self._B1 = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xB6, 2))[0] self._B2 = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xB8, 2))[0] self._MB = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xBA, 2))[0] self._MC = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xBC, 2))[0] self._MD = unp('>h', self._bmp_i2c.readfrom_mem(_bmp_addr, 0xBE, 2))[0] # settings to be adjusted by user self.oversample_setting = 3 self.baseline = 101325.0 # output raw self.UT_raw = None self.B5_raw = None self.MSB_raw = None self.LSB_raw = None self.XLSB_raw = None self.gauge = self.makegauge() # Generator instance for _ in range(128): next(self.gauge) time.sleep_ms(1)
def main(): # Executed on boot global switchPin global switchstate global lightstate switchPin = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP) cm.setAP(False) # We don't want AP in work mode by default savedData = boot.readSession() lightstate = int(savedData[1]) switchstate = int(savedData[2]) triac.activate(lightstate) print("Bulb reinitialised") attemptConnect() # Main program while(MainLoop): global compareTime time.sleep_ms(checkFrequency) if time.ticks_diff(time.ticks_ms(), compareTime) > reconnAttemptInterval: attemptConnect() print("Done MQTT connect") compareTime = time.ticks_ms() if not emergencyMode: checkInputChange(0) if cm.mqttActive: mqtt.check_msg() else: checkInputChange(1)
def blink_all_timed(self, color, blink_duration, brightness=1): """ Blink the entire stand at 2Hz for blink_duration, turns off afterwards Arguments: color : can be 'red', 'green', 'blue', or a tuple of (r,g,b) where r, g, and b are between 0 and 255 blink_duration : duration to blink for in seconds brightness : between 0 and 1, 0 is off, 1 is full brightness """ start_time = time.ticks_ms() run_time = time.ticks_diff(time.ticks_ms(), start_time) while run_time/1000 < blink_duration: if run_time % 500 < 250: self.turn_all_to_color(color, brightness) else: self.turn_all_off() time.sleep_ms(1) run_time = time.ticks_diff(time.ticks_ms(), start_time) # Ensure that all are off self.turn_all_off()
def get_SHT_relative_humidity(self): self._bus.writeto(self._address,TRI_RH_MEASURE_NO_HOLD) sleep_ms(150) origin_data=self._bus.readfrom(self._address,2) origin_value=unp('>H',origin_data)[0] value=-6+125*(origin_value/65536) return value
def get_SHT_temperature(self): self._bus.writeto(self._address,TRI_T_MEASURE_NO_HOLD) sleep_ms(150) origin_data=self._bus.readfrom(self._address,2) origin_value=unp('>h',origin_data)[0] value=-46.85+175.72*(origin_value/65536) return value
def cycle(r, g, b, wait): for i in range(n): for j in range(n): np[j] = (0, 0, 0) np[i % n] = (r, g, b) np.write() time.sleep_ms(wait)
def cycle(iterations, speed): for i in range(0, iterations): for i in range(0, np.n): np[(i-1) % np.n] = (0, 0, 0) np[i] = (10, 10, 10) np.write() time.sleep_ms(speed)
def test_main(): """Test function for verifying basic functionality.""" print("Running test_main") i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16) lcd.putstr("It Works!\nSecond Line") sleep_ms(3000) lcd.clear() count = 0 while True: lcd.move_to(0, 0) lcd.putstr("%7d" % (ticks_ms() // 1000)) sleep_ms(1000) count += 1 if count % 10 == 3: print("Turning backlight off") lcd.backlight_off() if count % 10 == 4: print("Turning backlight on") lcd.backlight_on() if count % 10 == 5: print("Turning display off") lcd.display_off() if count % 10 == 6: print("Turning display on") lcd.display_on() if count % 10 == 7: print("Turning display & backlight off") lcd.backlight_off() lcd.display_off() if count % 10 == 8: print("Turning display & backlight on") lcd.backlight_on() lcd.display_on()
def rainbow_cycle(wait): for j in range(255): for i in range(n): rc_index = (i * 256 // n) + j np[i] = wheel(rc_index & 255) np.write() time.sleep_ms(wait)
def knight_rider(loop=100, delay=50): """ Show Knight Rider animation loop = number of loops delay = sleep time between steps based on sin function """ periods = 16 # syncrhonize the two cos waves # this math is based on measurements vs. understanding what's going on np_div = np.n / 3.3 t = 0 for i in range(0, loop): t += 1 for p in range(0, np.n): # this controls speed - higher is faster f = t * 3.2 v1 = math.cos(f / periods + p/np_div) - 0.7 v1 = max(0, v1) v2 = math.cos(-f / periods + p/np_div) - 0.7 v2 = max(0, v2) b = int(v1 * 50) + int(v2 * 50) np[p] = (b, 0, 0) np.write() time.sleep_ms(delay)
def cylon(*, start=0, end=0, colors=(b'\xff\x22\x33\x40',), sleep_ms=250, verbose=False): """All this has happened before and all this will happen again.""" assert len(colors) in (1,2), 'only 1 or 2 colors allowed' end = _default_num_leds(end) byte_end = end*4 byte_start = start*4 direction = 4 pos = byte_start led_data = bytearray(led_off*end) while True: led_data[pos:pos+4] = colors[0] if len(colors) > 1: led_data[byte_end-pos-4:byte_end-pos] = colors[1] test(led_data, num_leds=end, rotate=0) if verbose: print('LED #', pos//4) time.sleep_ms(sleep_ms) led_data[pos:pos+4] = led_off if len(colors) > 1: led_data[byte_end-pos-4:byte_end-pos] = led_off pos += direction if pos >= byte_end or pos < byte_start: direction = -direction pos += direction*2 # Undo and go back.
def bin_walk_2(): """ Display incrementing binary digit Only make neopixel changes that are necessary - faster 16 lights = 00:03:17 39 lights ~ 100 years """ b = 0 while True: # find the first OFF bit # probably a better way to do this with log() etc t = 0 while (b & pow(2, t)): t += 1 # is this the last bit on the strip if (t == np.n): b = 0 time.sleep(1) else: np[t] = (5, 5, 5) # np[t] = (uos.urandom(1)[0], uos.urandom(1)[0], uos.urandom(1)[0]) for i in range(0, t): np[i] = (0, 0, 0) np.write() b += 1 # time.sleep_ms(168750) # 8 bits = 6 hours time.sleep_ms(14063) # 8 bits = 30min
def playmusic(): for i in range(0, len(musiclist), 1): display.show(str(musiclist[i])) music.pitch(round(round(tonelist[musiclist[i]])), PWM(Pin(27))) time.sleep_ms(round(500 * rhythmlist[i])) music.stop(PWM(Pin(27))) time.sleep_ms(10)
def test(t): publish("test 1.3") for i in range(0, lights, 3): np[i] = (100,100,100) np[(i-3) % lights] = (0,0,0) np.write() time.sleep_ms(100)
def diagnostic(): n = np.n print("Count = ", n) cycle(3, 1000) cycle(10, 100) cycle(10, 50) cycle(10, 30) for j in range(0, 40): for i in range(0, n): r = 10 if uos.urandom(1) <= b'\x30': r = 255 np[(i-1) % n] = (0, 0, 0) np[i] = (r, 10, 10) np.write() time.sleep_ms(30) for j in range(255, 0, -5): for i in range(0, n): np[i] = (j, 0, 0) np.write() time.sleep_ms(10)
def read_raw_data(self, result): """ Reads the raw (uncompensated) data from the sensor. Args: result: array of length 3 or alike where the result will be stored, in temperature, pressure, humidity order Returns: None """ self._l1_barray[0] = self._mode self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL_HUM, self._l1_barray) self._l1_barray[0] = self._mode << 5 | self._mode << 2 | 1 self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL, self._l1_barray) # Wait for conversion to complete while self.i2c.readfrom_mem(self.address, BME280_REGISTER_STATUS, 1)[0] & 0x08: time.sleep_ms(5) # burst readout from 0xF7 to 0xFE, recommended by datasheet self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray) readout = self._l8_barray # pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4 raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4 # temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4 raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4 # humidity(0xFD): (msb << 8) | lsb raw_hum = (readout[6] << 8) | readout[7] result[0] = raw_temp result[1] = raw_press result[2] = raw_hum
def get_dht_tempandhum(sensetype,pin): if (sensetype=='dht11'): d = dht.DHT11(machine.Pin(pin)) else: d = dht.DHT22(machine.Pin(pin)) d.measure() time.sleep_ms(1) return d.temperature(),d.humidity()
def lcd_init(): sleep_ms(DELAY) lcd_byte(0x33, CMD) lcd_byte(0x32, CMD) lcd_byte(0x06, CMD) lcd_byte(0x0C, CMD) lcd_byte(0x28, CMD) lcd_clear()
def get_dht_temperature(sensetype,pin): if (sensetype=='dht11'): d = dht.DHT11(machine.Pin(pin)) else: d = dht.DHT22(machine.Pin(pin)) d.measure() time.sleep_ms(1) return d.temperature() # eg. 23 (°C)
def get_dht_relative_humidity(sensetype,pin): if (sensetype=='dht11'): d = dht.DHT11(machine.Pin(pin)) else: d = dht.DHT22(machine.Pin(pin)) d.measure() time.sleep_ms(1) return d.humidity()
def result( self ) : '''Wait for result and return # of bytes read. Result is in _readbuffer.''' for i in range(1, 100) : if self.any() : return self.readinto(self._readbuffer) sleep_ms(_WAIT) return 0
boat5 = Image("00000:" "00000:" "00000:" "00000:" "05050") boat6 = Image("00000:" "00000:" "00000:" "00000:" "00000") all_boats = [boat1, boat2, boat3, boat4, boat5, boat6] display.scroll('hello,world', Yellow) sleep_ms(1000) display.scroll(454545) sleep_ms(1000) display.scroll('Goodbye-My-Loneliness', [Purple, Yellow, Green, Blue]) sleep_ms(1000) display.show(all_boats, Yellow) sleep_ms(1000) display.clear() display.show(boat1, Purple) sleep_ms(1000) display.clear() sleep_ms(1000) display.show('9', Green) sleep_ms(1000) display.show(Image.DUCK) sleep_ms(1000)
number = n_copy.pop(0) hexes.append(Hex(coords, resource, number, number == 7)) return hexes # List of resources (pre-randomised to combat the not-very random number # generator) and dice rolls (these have a strict order) for 2-4 player games resources = [4, 0, 1, 4, 4, 2, 5, 3, 2, 1, 2, 2, 1, 0, 3, 0, 3, 1, 0] numbers = [5, 2, 6, 3, 8, 10, 9, 12, 11, 4, 8, 10, 9, 4, 5, 6, 3, 11] def draw(): hexes = board_setup(resources, numbers) for h in hexes: h.clear() time.sleep_ms(100) h.draw() ugfx.text(5, 5, 'Press A to generate another ', ugfx.WHITE) draw() # Main Loop while True: if buttons.is_triggered(tilda.Buttons.BTN_A): draw() elif buttons.is_triggered(tilda.Buttons.BTN_Menu): break time.sleep_ms(5) restart_to_default()
# creat lora socket lora = LoRa(mode=LoRa.LORA, region=LoRa.US915, frequency=902000000, tx_power=20, sf=12, power_mode=LoRa.TX_ONLY) sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 3) # provide distance when readings vary > 6 inches def distance_generator(): '''This function will provide a distance when it varies''' last_dist = 0 while True: time.sleep_ms(500) new_dist_raw = uart.read() new_dist = int(str(new_dist_raw).split('\\rR')[-2]) if abs(last_dist - new_dist) > 6: last_dist = new_dist yield(last_dist) return # create and send lora packet for distance in distance_generator(): msg = '{ "id":"%s", "type":"%s", "activity":"new distance: %din" }' % (id, type, distance) print(msg) time.sleep_ms(300) sock.send(msg)
def read_sensors(hw, flash_count=0): rtime = time.gmtime() chrono = machine.Timer.Chrono() chrono.start() # Notes # # Temperature: Reading temperature is asynchronous. You call a method to # start it, and then read it later. Spec says 750 ms max. # # CO2: The sensor needs a little time to boot after power-off before it # will start responding to UART commands. In tests, about 165 ms seems to # work. But even after that, it will return wild readings at first. Need to # take a few readings until they settle. # # Experience shows that it's the first two that are way off, either 0 (min) # or 200010 (the max) etemp_reading = None etemp_ms = None co2_readings = [None] * 10 co2_i = 0 co2_ms = None # Start temperature readings try: _logger.debug("Starting external temp read. Can take up to 750ms.") etemp = hw.etemp etemp.start_conversion() except Exception as e: _logger.error("Unexpected error starting etemp reading. %s: %s", type(e).__name__, e) # Give CO2 sensor time to boot up after power-on time.sleep_ms(200) # Init communication with CO2 sensor try: _logger.debug("Init CO2 sensor...") co2 = hw.co2 co2.set_mode(explorir.MODE_POLLING) except Exception as e: _logger.error("Unexpected error initializing CO2 sensor. %s: %s", type(e).__name__, e) def try_read_co2_sensor(): try: co2_readings[co2_i] = co2.read_co2() # [] = will propagate co2_ms = chrono.read_ms() # = will NOT propagate _logger.info("CO2 reading #%d: %6d ppm at %4d ms", co2_i, co2_readings[co2_i], co2_ms) except Exception as e: _logger.error( "Unexpected error during CO2 sensor reading #%d. %s: %s", co2_i, type(e).__name__, e) finally: co2_i += 1 # += will propagate # Do throwaway reads of CO2 while waiting for temperature try_read_co2_sensor() time.sleep_ms(500) wdt.feed() try_read_co2_sensor() # Read temperature try: _logger.debug("Waiting for external temp read...") while not etemp_reading: etemp_reading = etemp.read_temp_async() etemp_ms = chrono.read_ms() _logger.info("etemp reading : %6.3f C at %4d ms", etemp_reading, etemp_ms) if not etemp_reading and etemp_ms > 1000: _logger.error( "Timeout reading external temp sensor after %d ms", etemp_ms) break time.sleep_ms(5) wdt.feed() except Exception as e: _logger.error("Unexpected error waiting for etemp reading. %s: %s", type(e).__name__, e) # Do more reads of CO2 sensor for _ in range(co2_i, len(co2_readings)): time.sleep_ms(500) wdt.feed() try_read_co2_sensor() # co2_ms did not propagate like the others, so get it again co2_ms = chrono.read_ms() co2_raws = {field: None for field in CO2_RAWS} try: co2.select_fields(CO2_RAWS) co2_raws = co2.read_fields() except: _logger.exception("Unexpected error reading co2 multi-fields") reading = { "rtime": rtime, "co2": co2_readings, "co2_ms": co2_ms, "etemp": etemp_reading, "etemp_ms": etemp_ms, "flash_count": flash_count, "co2_raws": co2_raws, } return reading
''' 实验名称:EEPROM(AT24C02) 版本:v1.0 日期:2020.12 作者:01Studio 说明:EEPROM的读写实验 ''' from at24c02 import AT24C02 import time EE = AT24C02(i2c_num=1) #哥伦布的B8,B9为I2C1 EE.write(1, 8) #往地址1写入数字8(用户可以更改自己写的数字) time.sleep_ms(5) #需要适当延时再读取 print(EE.read(1)) #读取地址1数据,等于前面写入的数字
def fast_vline(x, y, height, color): lcd.fill(x, y, 1, height, color) graphics = gfx.GFX(lcdWidth, lcdHeight, lcd.pixel, hline=fast_hline, vline=fast_vline) lcd.fill(0, 0, lcdWidth, lcdHeight, bgColor) graphics.rect(8, 8, lcdWidth - 16, lcdHeight - 16, textColor) lcd.text("Hello STEMBot 2!", 100, 100, textColor) time.sleep_ms(250) #intro screen delay tune = RTTTL('14:d=4,o=4,b=240:c,e,g,e,f,e,d,e,c') #buzzer.play(tune) pinUp = Pin('E5', Pin.IN, Pin.PULL_UP) pinDown = Pin('B6', Pin.IN, Pin.PULL_UP) pinSel = Pin('B2', Pin.IN, Pin.PULL_UP) #middle button below LCD l = os.listdir('apps') valid = [] for file in l: if (file.endswith('.py') and (file[0] != '.' and file != '_')): #Remove duplicates newfile = file.replace('_', ' ')
import pyb import time while True: pyb.LED(3).on() #LED3 = orange time.sleep(1) pyb.LED(3).off() time.sleep_ms(500)
def __init__(self, i2c): self.i2c = i2c self.soft_reset() # Should not take longer than 15ms, but we wait a little bit longer time.sleep_ms(50)
def func1(): while 1: print("hello 1...") time.sleep_ms(10)
def main(): clear_screen() #clear screen by filling black rectangle (slow) BLK.value(1) #turn backlight on display._set_mem_access_mode( 0, False, False, True ) #setting screen orientation (rotation (0-7), vertical mirror, horizonatal mirror, is bgr) while True: clear_screen() BLK.value(1) if not button1.value(): fill_hline() if not button2.value(): fill_vline() #display.fill(st7789.BLACK) #display.pixel(random.randint(0, 135), random.randint(0, 240) , st7789.color565(random.getrandbits(8),random.getrandbits(8),random.getrandbits(8))) x = random.randint(0, 135) y = random.randint(0, 240) w = random.randint(0, 135) h = random.randint(0, 240) display.circle(x, y, 30, random_color()) display.ellipse(x, y, 10, 20, random_color()) clear_screen() time.sleep(1) clear_screen() display.hline(10, 127, 63, random_color()) time.sleep(1) display.vline(10, 0, 127, random_color()) time.sleep(1) display.fill_hrect(23, 50, 30, 75, random_color()) time.sleep(1) display.hline(0, 0, 127, random_color()) time.sleep(1) display.line(127, 0, 64, 127, random_color()) time.sleep(2) clear_screen() coords = [[0, 63], [78, 80], [122, 92], [50, 50], [78, 15], [0, 63]] display.lines(coords, random_color()) time.sleep(1) clear_screen() display.fill_polygon(7, 63, 63, 50, random_color()) time.sleep(1) display.fill_rectangle(0, 0, 15, 127, random_color()) time.sleep(1) clear_screen() display.fill_rectangle(0, 0, 63, 63, random_color()) time.sleep(1) display.rectangle(0, 64, 63, 63, random_color()) time.sleep(1) display.fill_rectangle(64, 0, 63, 63, random_color()) time.sleep(1) display.polygon(3, 96, 96, 30, random_color(), rotate=15) time.sleep(3) clear_screen() display.fill_circle(32, 32, 30, random_color()) time.sleep(1) display.circle(32, 96, 30, random_color()) time.sleep(1) display.ellipse(96, 96, 16, 30, random_color()) display.fill_ellipse(96, 32, 30, 16, random_color()) time.sleep(1) display.fill(0) v = 30 display.text((0, v), "Hello World!", random_color(), sysfont, 1, nowrap=True) v += sysfont["Height"] display.text((0, v), "Hello World!", random_color(), sysfont, 2, nowrap=True) v += sysfont["Height"] * 2 display.text((0, v), "Hello World!", random_color(), sysfont, 3, nowrap=True) v += sysfont["Height"] * 3 display.text((0, v), str(1234.567), random_color(), sysfont, 4, nowrap=True) time.sleep_ms(1500) display.fill(0) v = 0 display.text((0, v), "Hello World!", random_color(), sysfont) v += sysfont["Height"] display.text((0, v), str(math.pi), random_color(), sysfont) v += sysfont["Height"] display.text((0, v), " Want pi?", random_color(), sysfont) v += sysfont["Height"] * 2 display.text((0, v), hex(8675309), random_color(), sysfont) v += sysfont["Height"] display.text((0, v), " Print HEX!", random_color(), sysfont) v += sysfont["Height"] * 2 display.text((0, v), "Sketch has been", random_color(), sysfont) v += sysfont["Height"] display.text((0, v), "running for: ", random_color(), sysfont) v += sysfont["Height"] display.text((0, v), str(time.ticks_ms() / 1000), random_color(), sysfont) display.text((0, v), " seconds.", random_color(), sysfont) time.sleep(10) BLK.value(0)
def draw(): hexes = board_setup(resources, numbers) for h in hexes: h.clear() time.sleep_ms(100) h.draw()
logger.debug("Time_current = {}".format(datetime_string(time_current))) logger.debug("Time_start = {}...".format(datetime_string(time_start))) logger.debug("Waiting for {} seconds ...".format(time_start - time_current)) while True: if time.time() >= time_start: break # MESURING logger.debug("Measuring ACC...") pycom.heartbeat(False) pycom.rgbled(0x000F00) X, Y, Z, Xrms, Yrms, Zrms = ACC.measure(Td=nsecOfMeasure) rmsACC = (Xrms**2 + Yrms**2 + Zrms**2)**0.5 logger.debug("Measuring ACC Done.") pycom.rgbled(0x000000) time.sleep_ms(100) pycom.heartbeat(True) # STORING FILE INTO SD CARD logger.debug("Storing data into SD...") filename = '/sd/gcam{}-acc{}-'.format(iCAM, iACC) + datetime_string(time_start) with open(filename, 'wb') as file: for i in range(len(X)): file.write(ustruct.pack('<ddd', X[i], Y[i], Z[i])) logger.debug("Storing data into SD Done.") # # REPORTING (state=3) # logger.debug("Reporting state=3 to CTLR ...") response = socket_client.request('set,state{},3;set,rms{},{}'.format( iACC, iACC, rmsACC))
def poweron(self): self.res(1) time.sleep_ms(1) self.res(0) time.sleep_ms(10) self.res(1)
def test_main(): time.sleep_ms(1000) testgrid() testblockColor() # def test_main_org(): print("Start main") tft.fill(TFT.BLACK) tftprinttest() time.sleep_ms(4000) print("test Y line") testlines(TFT.YELLOW) time.sleep_ms(500) print("fast line") testfastlines(TFT.RED, TFT.BLUE) time.sleep_ms(500) testdrawrects(TFT.GREEN) time.sleep_ms(500) testfillrects(TFT.YELLOW, TFT.PURPLE) time.sleep_ms(500) tft.fill(TFT.BLACK) testfillcircles(10, TFT.BLUE) testdrawcircles(10, TFT.WHITE) time.sleep_ms(500) testroundrects() time.sleep_ms(500) testtriangles() time.sleep_ms(500) testdrawarects(TFT.GREEN) time.sleep_ms(500) testgrid()
img=sensor.snapshot() lcd.display(img) ''' flash_ls = os.listdir() if (not "boot.py" in flash_ls) : f = open("boot.py", "wb") f.write(boot_py) f.close() banner = ''' __ __ _____ __ __ _____ __ __ | \/ | /\ |_ _| \ \ / / | __ \ \ \ / / | \ / | / \ | | \ V / | |__) | \ \_/ / | |\/| | / /\ \ | | > < | ___/ \ / | | | | / ____ \ _| |_ / . \ | | | | |_| |_| /_/ \_\ |_____| /_/ \_\ |_| |_| Official Site : https://www.sipeed.com Wiki : https://maixpy.sipeed.com ''' print(banner) import time time.sleep_ms(300) # wait for key interrupt to cancel boot.py run(for maixpy ide) # run boot.py import boot
def testblockColor(): vPos = 80 fSize = 2 aColor = TFT.RED tft.fill(TFT.BLACK) tft.text((8, vPos), "TFT.BLACK", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) aColor = TFT.BLACK tft.fill(TFT.RED) tft.text((8, vPos), "TFT.RED", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.MAROON) tft.text((8, vPos), "TFT.MAROON", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.GOLD) tft.text((8, vPos), "TFT.GOLD", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.GREEN) tft.text((8, vPos), "TFT.GREEN", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.FOREST) tft.text((8, vPos), "TFT.FOREST", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.BLUE) tft.text((8, vPos), "TFT.BLUE", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.NAVY) tft.text((8, vPos), "TFT.NAV", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.CYAN) tft.text((8, vPos), "TFT.CYAN", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.YELLOW) tft.text((8, vPos), "TFT.YELLOW", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.PURPLE) tft.text((8, vPos), "TFT.PURPLE", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.WHITE) tft.text((8, vPos), "TFT.WHITE", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.GRAY) tft.text((8, vPos), "TFT.GRAY", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000) tft.fill(TFT.ORANGE) tft.text((8, vPos), "TFT.ORANGE", aColor, sysfont, fSize, nowrap=True) time.sleep_ms(1000)
def delay_ms(ms): time.sleep_ms(ms)
# Complete project details at https://RandomNerdTutorials.com import machine, onewire, ds18x20, time ds_pin = machine.Pin(4) ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin)) roms = ds_sensor.scan() print('Found DS devices: ', roms) while True: ds_sensor.convert_temp() time.sleep_ms(750) for rom in roms: print(rom) print(ds_sensor.read_temp(rom)) time.sleep(5)
def main(GS): try: GS.ConfigFile = 'mycfng.json' GS.NotifyFile = 'NotifyStatus.json' GS.data = {} GS.data2 = {} LoadConfig(GS) SetNotify(GS) # PIR SETUP Connettore D5 button = Pin(14, Pin.IN, Pin.PULL_UP) # Station UP GS.station = network.WLAN(network.STA_IF) # Disabilito AP ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sleep_ms(LOOP_WAIT_MS) sleep_ms(LOOP_WAIT_MS) sleep_ms(LOOP_WAIT_MS) WifiConnect(GS) MqttSetUP(GS) internalLed.on() PrintCnt = 0 while True: if PrintCnt == LOOP_SKIPS: # Limit console noise log("INFO", "----- LOOOP MqttPIR -----") timer = Timer(0) timer.init(period=(TIMEOUT_MS * 30), mode=Timer.ONE_SHOT, callback=timeout_callback) try: log("DEBUG", "NewCheck") GS.c.check_msg() log("DEBUG", "NewCheck DONE") log("DEBUG", "Ping Start") GS.c.ping() log("DEBUG", "Ping DONE") internalLed.on() except Exception as e: log("ERROR", 'Error {}'.format(e)) internalLed.off() machine.reset() # GS.c.disconnect() # WifiConnect(GS) # MqttSetUP(GS) sleep_ms(LOOP_WAIT_MS) finally: timer.deinit() if not button.value(): if PrintCnt == LOOP_SKIPS: # Limit console noise GS.statusMsg["Circut"] = "closed" msg = "Circut closed" log("DEBUG", msg) PrintCnt = 0 else: PrintCnt += 1 else: msg = "Circut opened!" log("INFO", msg) GS.statusMsg["Circut"] = "opened" if int(GS.IS_TO_NOTIFY) == 1: try: log("DEBUG", "Pub on Trigger: [" + str(GS.OUT_TRG_NOTIFY) + "]") GS.c.publish(GS.OUT_TRG_NOTIFY, ujson.dumps(GS.OUT_TRG_MSG), qos=1) log("DEBUG", "Pub Status on: [" + str(GS.OUT_PIR_STATUS) + "]") GS.c.publish(GS.OUT_PIR_STATUS, msg=ujson.dumps(GS.statusMsg), retain=True, qos=1) msg = "Notifications DONE" log("DEBUG", msg) except Exception as e: log("ERROR", 'Error {}'.format(e)) internalLed.off() machine.reset() sleep_ms(LOOP_WAIT_MS) else: log("DEBUG", "IS TO NOTIFY: [" + str(GS.IS_TO_NOTIFY) + "]") msg = "Notification not sent. Notification disabled" log("DEBUG", msg) sleep_ms(LOOP_WAIT_MS) except Exception as e: log("ERROR", 'Error {}'.format(e)) internalLed.off() machine.reset() sleep_ms(LOOP_WAIT_MS) GS.c.disconnect()
import time, math, ujson, network
import time import display import board d = C import keyboard_AT42QT1110 as kb k = kb.Keyboard() minvals = [1000] * 8 while (1): time.sleep_ms(200) d.disp.fill(0) # d.disp.text(str(board.vbat()),0,8) #USB voltage for i, v in enumerate(board.keyboard_note_keys): #Level of each key v = k.uc1.read_analog(v) minvals[i] = min(minvals[i], v) d.disp.text(str(v) + " " + str(v - minvals[i]), 0, 8 * i) d.disp.show()
def poweron(self): self.res.high() time.sleep_ms(1) self.res.low() time.sleep_ms(10) self.res.high()
def init(self): for command, data in ( (_RDDSDR, b"\x03\x80\x02"), (_PWCRTLB, b"\x00\xc1\x30"), (_PWRONCTRL, b"\x64\x03\x12\x81"), (_DTCTRLA, b"\x85\x00\x78"), (_PWCTRLA, b"\x39\x2c\x00\x34\x02"), (_PRCTRL, b"\x20"), (_DTCTRLB, b"\x00\x00"), (_PWCTRL1, b"\x23"), (_PWCTRL2, b"\x10"), (_VMCTRL1, b"\x3e\x28"), (_VMCTRL2, b"\x86")): self._write(command, data) if self.rotation == 0: # 0 deg self._write(_MADCTL, b"\x48") self.width = self._init_height self.height = self._init_width elif self.rotation == 1: # 90 deg self._write(_MADCTL, b"\x28") self.width = self._init_width self.height = self._init_height elif self.rotation == 2: # 180 deg self._write(_MADCTL, b"\x88") self.width = self._init_height self.height = self._init_width elif self.rotation == 3: # 270 deg self._write(_MADCTL, b"\xE8") self.width = self._init_width self.height = self._init_height elif self.rotation == 4: # Mirrored + 0 deg self._write(_MADCTL, b"\xC8") self.width = self._init_height self.height = self._init_width elif self.rotation == 5: # Mirrored + 90 deg self._write(_MADCTL, b"\x68") self.width = self._init_width self.height = self._init_height elif self.rotation == 6: # Mirrored + 180 deg self._write(_MADCTL, b"\x08") self.width = self._init_height self.height = self._init_width elif self.rotation == 7: # Mirrored + 270 deg self._write(_MADCTL, b"\xA8") self.width = self._init_width self.height = self._init_height else: self._write(_MADCTL, b"\x08") for command, data in ( (_PIXSET, b"\x55"), (_FRMCTR1, b"\x00\x18"), (_DISCTRL, b"\x08\x82\x27"), (_ENA3G, b"\x00"), (_GAMSET, b"\x01"), (_PGAMCTRL, b"\x0f\x31\x2b\x0c\x0e\x08\x4e\xf1\x37\x07\x10\x03\x0e\x09\x00"), (_NGAMCTRL, b"\x00\x0e\x14\x03\x11\x07\x31\xc1\x48\x08\x0f\x0c\x31\x36\x0f")): self._write(command, data) self._write(_SLPOUT) time.sleep_ms(120) self._write(_DISPON)
def func2(): while 1: print("hello 2...") time.sleep_ms(10)
def restart(port=21, verbose=0, splash=True): stop() sleep_ms(200) start(port, verbose, splash)
from machine import SoftSPI, Pin import tinypico as TinyPICO from micropython_dotstar import DotStar import time, random # Configure SPI for controlling the DotStar # Internally we are using software SPI for this as the pins being used are not hardware SPI pins spi = SoftSPI(sck=Pin(TinyPICO.DOTSTAR_CLK), mosi=Pin(TinyPICO.DOTSTAR_DATA), miso=Pin(TinyPICO.SPI_MISO)) # Create a DotStar instance dotstar = DotStar(spi, 1, brightness=0.5) # Just one DotStar, half brightness # Turn on the power to the DotStar TinyPICO.set_dotstar_power(True) # On and Off times in ms wait_on = 500 wait_off = 500 # Flash the Dotstar a random colour every second while True: # Pick a random colour from the colour wheel r, g, b = TinyPICO.dotstar_color_wheel(int(random.random() * 255)) # Display the colour for wait_on time then clear for wait_off time dotstar[0] = (r, g, b, 1) time.sleep_ms(wait_on) dotstar[0] = (0, 0, 0, 1) time.sleep_ms(wait_off)
#Program 5 - potentiometer on channel 3 (D1 and D0 high, D2 low - push to D_in - made in line 13) import machine, neopixel, time, ubinascii spi = machine.SPI(1, baudrate=1000000, polarity=0, phase=0) #Set up chip select chip_select = machine.Pin(16, machine.Pin.OUT) #Get a list of 1 neopixel led = neopixel.NeoPixel(machine.Pin(15), 1) data_out = bytearray(3) data_in = bytearray(3) #Set up input data_in[0] = 0x01 data_in[1] = 0xb0 data_in[2] = 0x0 while True: chip_select.off() spi.write_readinto(data_in, data_out) #Choose third input chip_select.on() time.sleep_ms(200) #Wait so results don't come too quick data_out[1] = data_out[1] & 0x03 hex = ubinascii.hexlify(data_out) #Get a hexadecimal value from output integer = int(hex, 16) #Get a decimal value from output fraction = integer % 1024 #Get results from the first 10 bits (0-1023) and dismiss the rest print(fraction) #Print the result (for debug) led[0] = (int(255 * ((fraction) / 1023)), int(255 * ((fraction) / 1023)), int(255 * ((fraction) / 1023))) #Set up the light led.write() #Write to neopixel
def reset(self): self.rst(0) time.sleep_ms(50) self.rst(1) time.sleep_ms(50)
pattern = 0 crab_x = 0 crab_vx = 1 # Main loop while True: for fish_x in range(70, -21, -1): setbmpmn(5, 0, 7, 8, 6 + pattern) #display plants 1 setbmpmn(23, 0, 7, 8, 6 + (pattern + 1) % 3) #display plants 2 setbmpmn(42, 0, 7, 8, 6 + (pattern + 2) % 3) #display plants 3 setbmpmn(crab_x, 2, 10, 6, 9 + (crab_x & 1)) #display crab setbmpmn(fish_x, fish_y, 16, 8, pattern) #display golden fish if bubble_y >= 0: setp(bubble_x, bubble_y) #display bubble putled() #output VRAM data to MAX7219 LED display time.sleep_ms(70) clrbmpmn(fish_x, fish_y, 16, 8) #clear golden fish clrbmpmn(crab_x, 2, 10, 6) #clear crab if bubble_y >= 0: clrp(bubble_x, bubble_y) #clear bubble bubble_y = bubble_y - 1 #move bubble if fish_x & 1: pattern = (pattern + 1) % 3 #next bitmap pattern if (fish_x & 3) == 0: fish_y = fish_y + fish_vy #golden fish up/down if fish_y < -1: fish_vy = 1 elif fish_y > 1: fish_vy = -1 bubble_x = fish_x - 8 #bubble appear bubble_y = 7
def test_main(): while True: tft.fill(TFT.BLACK) tft.fillrect( 0, 0, ) while True: tft.fill(TFT.BLACK) tft.text(( 0, 0 ), "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", TFT.WHITE, sysfont, 1) time.sleep_ms(1000) tftprinttest() time.sleep_ms(2000) testlines(TFT.YELLOW) time.sleep_ms(500) testfastlines(TFT.RED, TFT.BLUE) time.sleep_ms(500) testdrawrects(TFT.GREEN) time.sleep_ms(500) testfillrects(TFT.YELLOW, TFT.PURPLE) time.sleep_ms(500) tft.fill(TFT.BLACK) testfillcircles(10, TFT.BLUE) testdrawcircles(10, TFT.WHITE) time.sleep_ms(500) testroundrects() time.sleep_ms(500) testtriangles() time.sleep_ms(500)