Exemplo n.º 1
0
    def _card_state_change(self, pin):
        """
        Need to debounce this
        :param pin:
        :return:
        """
        if self._debounce:
            return

        self._debounce = True
        self._debounce_timer = Timer(-1)
        self._debounce_timer.init(period=DEBOUNCE_TIME,
                                  mode=Timer.ONE_SHOT,
                                  callback=self._remove_debounce)

        irq_state = disable_irq()

        if pin.value():  # No card present
            if self._card:  # Card may not be present on boot
                enable_irq(irq_state)
                uos.umount(self._directory)
                irq_state = disable_irq()
                self._deinit_card()
        else:
            try:
                card = self._init_card()
                enable_irq(irq_state)
                uos.mount(card, self._directory)
                irq_state = disable_irq()
            except OSError:  # Mount issue, probably EPERM
                pass

        enable_irq(irq_state)
Exemplo n.º 2
0
 def distance_mm(self):
     pre = 0
     post = 0
     k = -1
     length = 500
     resp = bytearray(length)
     resp[0] = 0xFF
     machine.disable_irq()
     self.spi.send_recv(resp, resp)
     machine.enable_irq()
     # find first non zero value
     try:
         i, value = next((ind, v) for ind, v in enumerate(resp) if v)
     except StopIteration:
         i = -1
     if i > 0:
         pre = bin(value).count("1")
         # find first non full high value afterwards
         try:
             k, value = next((ind, v)
                             for ind, v in enumerate(resp[i:length - 2])
                             if resp[i + ind + 1] == 0)
             post = bin(value).count("1") if k else 0
             k = k + i
         except StopIteration:
             i = -1
     dist= -1 if i < 0 else\
           round(((pre + (k - i) * 8 + post) * 8 * 0.172) / 2)
     return dist
Exemplo n.º 3
0
 def _write_bit(self, value, pin_init, pin_value, Pin_OUT):
     """
     Write a single bit - requires cached methods/attributes be passed as arguments.
     See also write_bit()
     """
     d0, d1, d2, d3 = self.write_delays
     udelay = sleep_us
     if value:
         # write 1
         i = disable_irq()
         pin_init(Pin_OUT)
         pin_value(0)
         udelay(d0)
         pin_value(1)
         enable_irq(i)
         udelay(d1)
     else:
         # write 0
         i = disable_irq()
         pin_init(Pin_OUT)
         pin_value(0)
         udelay(d2)
         pin_value(1)
         enable_irq(i)
         udelay(d3)
Exemplo n.º 4
0
 def _send(self):
     """
     send the buffer over SPI.
     """
     disable_irq()
     self.spi.write(self.buf)
     enable_irq()
Exemplo n.º 5
0
	def send_buf(self):
		"""
		Send buffer over SPI.
		"""
		disable_irq()
		self.spi.write(self.buf)
		enable_irq()
Exemplo n.º 6
0
 def _send(self):
     """
     send the buffer over SPI.
     """
     disable_irq()
     self.spi.write(self.buf)
     enable_irq()
Exemplo n.º 7
0
 def send_buf(self):
     """
     Send buffer over SPI.
     """
     disable_irq()
     self.spi.write(self.buf)
     enable_irq()
     gc.collect()
Exemplo n.º 8
0
 def switch_cb(pin):
     global irq_counter
     if irq_counter < 1:
         irq_counter += 1
         red_led.off()
         green_led.off()
         machine.disable_irq()
         print('Rebooting to enter Calibration Mode...')
         utime.sleep_ms(3000)
         machine.reset()
Exemplo n.º 9
0
    def handle_reset(self, p):
        machine.disable_irq()

        import micropython
        import time

        if p.value() == 0:
            time.sleep_ms(500)
            if p.value() == 0:
                print("Resetting Device...")
                micropython.schedule(self.hard_reset_ref, 0)
Exemplo n.º 10
0
def main():
    global led_count

    machine.disable_irq()
    led_init()
    switch_push_init()
    led_count = 0
    machine.enable_irq()

    while True:
        pass
Exemplo n.º 11
0
def main():
    global led_count

    machine.disable_irq()
    led_init()
    switch_push_init()
    led_count = 0
    machine.enable_irq()

    while True:
        led_out_bdigit(led_count)
        machine.disable_irq()
        led_count += 1
        machine.enable_irq()
        busy_wait()
Exemplo n.º 12
0
 def write_bit(self, addr):  #发送位函数。
     #发送时关掉中断,防止中断影响时序
     state = machine.disable_irq()
     self.pin.value(1)  #开始拉高
     sleep_us(1000)
     #sleep_us( 1000 )
     self.pin.value(0)  #开始引导码
     # minimal 2ms
     sleep_us(4000)  #此处延时最少要大于2ms
     self.pin.value(1)
     #将数字(二进制)对应位数比较,若对应位都为1,则对应位为1,否则为0;
     #即将addr按位取出
     #addr & 0x01 表示最低位,即低位在前
     #addr & 0x01 means lower bit fist
     # 3:1 time occupation means "1"
     if (addr & 0x01):  #3:1表示数据位1,每个位用两个脉冲表示
         sleep_us(600)
         self.pin.value(0)
         sleep_us(200)
         # 1:3  time occupation means "0"
     else:  # 1:3表示数据位0 ,每个位用两个脉冲表示
         sleep_us(200)
         self.pin.value(0)
         sleep_us(600)
     self.pin.value(addr)
     self.pin.value(1)
     #恢复中断
     #resum interrupt
     machine.enable_irq(state)
Exemplo n.º 13
0
 def debounce(self, timer):
     state = machine.disable_irq()
     if (self.debouncing and self.debouncing.value() == 0):
         self.debounce_done = True
     else:
         self.debouncing = None
     machine.enable_irq(state)
Exemplo n.º 14
0
    def read(self):
        #First wait for data ready, DOUT will be low when ready
        while not self.is_ready():
            pass
        #disable interrupts to avoid problems during reading
        #If SCK goes high longer than 65µs the chip enter power down state.
        #So we must avoid interruots during reading
        interrupt_status = machine.disable_irq()

        dataBits = 0

        for i in range(0, 24):
            self.pSCK.value(True)
            dataBits <<= 1
            utime.sleep_us(1)            #Minimum waiting time
            self.pSCK.value(False)
            bitLu = self.pOUT()
            if bitLu: dataBits += 1
            utime.sleep_us(1)            #Minimum waiting time

        # set channel and gain factor for next reading
        for i in range(self.GAIN):
            self.pSCK.value(True)
            utime.sleep_us(1)            #Minimum waiting time
            self.pSCK.value(False)
            utime.sleep_us(1)            #Minimum waiting time

        #
        machine.enable_irq(interrupt_status)        #Re enable interrupts
        if dataBits >= 8388608:                 #negative value
            dataBits = dataBits - 16777216
        return dataBits
Exemplo n.º 15
0
 def _upper_half(pin):
     irq_state = machine.disable_irq()
     try:
         self.triggered = True
         self.handlers[(id(pin), trigger)].triggered = True
     finally:
         machine.enable_irq(irq_state)
    def read(self):
        """
        Acquire vbatt reading by sampling ADC.
        """

        # Power on ADC.
        self.adc.init()

        log.debug('Reading battery level on pin {} with voltage divider {}/{}'.
                  format(self.pin, self.resistor_r1, self.resistor_r2))

        # Sample ADC a few times.
        # Todo: Make attenuation factor configurable.
        adc_channel = self.adc.channel(attn=ADC.ATTN_6DB, pin=self.pin)
        adc_samples = [0.0] * self.adc_sample_count
        adc_mean = 0.0
        i = 0
        irq_state = disable_irq()
        while i < self.adc_sample_count:
            sample = adc_channel()
            adc_samples[i] = sample
            adc_mean += sample
            i += 1
        enable_irq(irq_state)

        adc_mean /= self.adc_sample_count
        adc_variance = 0.0
        for sample in adc_samples:
            adc_variance += (sample - adc_mean)**2
        adc_variance /= (self.adc_sample_count - 1)

        raw_voltage = adc_channel.value_to_voltage(4095)
        mean_voltage = adc_channel.value_to_voltage(int(adc_mean))
        mean_variance = (adc_variance * 10**6) // (adc_mean**2)

        # log.debug("ADC readings. count=%u:\n%s" %(self.adc_sample_count, str(adc_samples)))
        log.debug(
            "SystemBatteryLevel: Mean of ADC readings (0-4095) = %15.13f" %
            adc_mean)
        log.debug(
            "SystemBatteryLevel: Mean of ADC voltage readings (0-%dmV) = %15.13f"
            % (raw_voltage, mean_voltage))
        log.debug("SystemBatteryLevel: Variance of ADC readings = %15.13f" %
                  adc_variance)
        log.debug(
            "SystemBatteryLevel: 10**6*Variance/(Mean**2) of ADC readings = %15.13f"
            % mean_variance)

        resistor_sum = self.resistor_r1 + self.resistor_r2
        voltage_millivolt = (adc_channel.value_to_voltage(
            int(adc_mean))) * resistor_sum / self.resistor_r2
        voltage_volt = voltage_millivolt / 1000.0

        # Shut down ADC channel.
        adc_channel.deinit()

        log.debug('Battery level: {}'.format(voltage_volt))

        reading = {'system.voltage': voltage_volt}
        return reading
Exemplo n.º 17
0
    def _settle_checker(self, _):
        """Scheduled(!) each ms while we're debouncing something."""
        self._running_jobs = self.RUNNING_CHECKING
        # Most of the following code could possibly be moved into the
        # ``DebouncedTimer`` class for separation of concerns, but we should
        # probably do some benchmarking first.
        for pin_id, pin in self._pins.items():
            if pin._settle_wait is not None:  # pin is being debounced
                if pin._settle_wait <= 0:  # it has settled now
                    pin._settle_wait = None
                    if pin._value != pin._previous:
                        pin._previous = pin._value
                        pin._callback(pin_id, pin._value)
                else:
                    # Since no interrupt sets this to None, we can safely
                    # assume that it's an int.
                    pin._settle_wait -= 1
                    # There is at least one running job left.
                    self._running_jobs = self.RUNNING_SOME

        # If there are no debouncing jobs left, disable the timer.
        irq = disable_irq()
        try:
            if self._running_jobs == self.RUNNING_CHECKING:
                # Didn't see running jobs, and no new ones were inserted
                # meanwhile via an interrupt.
                self._running_jobs = self.RUNNING_NONE
                self._timer.deinit()
        finally:
            enable_irq(irq)
Exemplo n.º 18
0
def main():
    global relay_pin

    client = MQTTClient(CLIENT_ID, SERVER)
    client.set_callback(new_msg)

    try:
        client.connect()
    except OSError:
        print("MQTT Broker seems down")
        print("Resetting after 20 seconds")
        time.sleep(20)
        machine.reset()

    client.subscribe(COMMAND_TOPIC)

    # Publish as available once connected
    client.publish(AVAILABILITY_TOPIC, "online", retain=True)

    switch_pin = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
    reed_switch = Switch(switch_pin)

    # Initialize state of garage door after booting up
    if switch_pin.value():
        client.publish(STATE_TOPIC, "open", retain=True)
    else:
        client.publish(STATE_TOPIC, "closed", retain=True)

    relay_pin = machine.Pin(4, machine.Pin.OUT, 0)

    try:
        while True:

            reed_switch_new_value = False

            # Disable interrupts for a short time to read shared variable
            irq_state = machine.disable_irq()
            if reed_switch.new_value_available:
                reed_switch_value = reed_switch.value
                reed_switch_new_value = True
                reed_switch.new_value_available = False
            machine.enable_irq(irq_state)

            # If the reed switch had a new value, publish the new state
            if reed_switch_new_value:
                if reed_switch_value:
                    client.publish(STATE_TOPIC, "open")
                else:
                    client.publish(STATE_TOPIC, "closed")

            # Process any MQTT messages
            if client.check_msg():
                client.wait_msg()

            time.sleep_ms(500)

    finally:
        client.publish(AVAILABILITY_TOPIC, "offline", retain=False)
        client.disconnect()
        machine.reset()
Exemplo n.º 19
0
	def callback(self,pin):
		irqs = machine.disable_irq()
		hasdata = self.mr()
		machine.enable_irq(irqs)
		if hasdata and not self.rxtimer:
			self.rxtimer = machine.Timer(1)
			self.rxtimer.init(mode=machine.Timer.ONE_SHOT, period=1,callback=self.real_decoder)
Exemplo n.º 20
0
def start_killer():
    global dog_started, dog_start_time, killed
    state = machine.disable_irq()
    dog_started = True
    dog_start_time = ticks_ms()
    killed = False
    machine.enable_irq(state)
Exemplo n.º 21
0
    def read(self):
        # wait for the device being ready
        for _ in range(500):
            if self.pOUT() == 0:
                break
            time.sleep_ms(1)
        else:
            raise OSError("Sensor does not respond")

        # shift in data, and gain & channel info
        result = 0
        for j in range(24 + self.GAIN):
            state = disable_irq()
            self.pSCK(True)
            self.pSCK(False)
            enable_irq(state)
            result = (result << 1) | self.pOUT()

        # shift back the extra bits
        result >>= self.GAIN

        # check sign
        if result > 0x7fffff:
            result -= 0x1000000

        return result
Exemplo n.º 22
0
def my_callback(p):
    interrupt_state = machine.disable_irq()
    print('in interrupt')
    time.sleep_ms(800)
    print(11111)
    machine.enable_irq(interrupt_state)
    return
Exemplo n.º 23
0
def stop_killer():
    global dog_started, dog_start_time, killed
    state = machine.disable_irq()
    dog_started = False
    dog_start_time = None
    killed = False
    machine.enable_irq(state)
def encbutprss(a):
    global debouncetime, lastbouncetime, updatescreen, dispcursor, pnr, ticktock
    irq_state = machine.disable_irq()
    now = utime.ticks_ms()
    if now - lastbouncetime > debouncetime and pnr == 0:

        ticktock = utime.ticks_ms()
        #killme.init(period=15000, mode=Timer.ONE_SHOT, callback=shutdown)
        if Value0[dispcursor] == "off":
            Value0[dispcursor] = "on"
            if datatype[dispcursor] != 2:
                Value1[dispcursor] = "100"
        else:
            Value0[dispcursor] = "off"
            if datatype[dispcursor] != 2:
                Value1[dispcursor] = "0"
        updatemsg = {
            "id": dispcursor,
            "value0": Value0[dispcursor],
            "value1": Value1[dispcursor]
        }
        updatemsgjson = ujson.dumps(updatemsg)
        mqttobject.publish(secrets["topicpub"], updatemsgjson)
    pnr = 0
    lastbouncetime = now
    updatescreen = 1
    machine.enable_irq(irq_state)
Exemplo n.º 25
0
 def __collect_input(self):
     # collect the data while unchanged found
     unchanged_count = 0
     # this is used to determine where is the end of the data
     max_unchanged_count = 100
     last = -1
     data = []
     m = bytearray(800)  # needs long sample size to grab all the bits from the DHT # noqa
     irqf = disable_irq()
     self.__pin(1)
     for i in range(len(m)):
         m[i] = self.__pin()  # sample input and store value
     enable_irq(irqf)
     for i in range(len(m)):
         current = m[i]
         data.append(current)
         if last != current:
             unchanged_count = 0
             last = current
         else:
             unchanged_count += 1
             if unchanged_count > max_unchanged_count:
                 break
     # print(data)
     return data
Exemplo n.º 26
0
 def btn_isr(self, pin):
     state = machine.disable_irq()
     self.debouncing = pin
     self.debounce_timer.init(period=80,
                              mode=machine.Timer.ONE_SHOT,
                              callback=self.debounce)
     machine.enable_irq(state)
Exemplo n.º 27
0
def update_timer_counter():
  global timer_counter
  if event_list.head:
    timer_counter_new = event_list.head.time_next - ticks_ms()
    irq_state = machine.disable_irq()
    timer_counter = timer_counter_new
    machine.enable_irq(irq_state)
Exemplo n.º 28
0
def main():
	global sw_pressed
	sw_pressed = None

	SW_PRESS_INTERVAL = 250 * 1000	#250ms
	SW_IRQ_TRIGGER    = Pin.IRQ_FALLING

	#SW1
	sw1 = Pin(20, Pin.IN, Pin.PULL_UP)
	#割り込みの設定
	sw1.irq(trigger=SW_IRQ_TRIGGER, handler=callback)

	ref_time = utime.ticks_us()
	while True:
		if sw_pressed:
			# disable IRQ until get values
			sw_state   = machine.disable_irq()
			sw_trigger = sw_pressed.irq().flags()
			time_diff  = utime.ticks_diff(utime.ticks_us(), ref_time)
			# enable IRQ
			machine.enable_irq(sw_state)

			if( time_diff > SW_PRESS_INTERVAL ):
				if sw_trigger == SW_IRQ_TRIGGER:
					if sw_pressed == sw1:
						print("sw1")
				else:
					pass
			else:
				pass			# avoid chattering

			sw_pressed = None
			ref_time = utime.ticks_us()
Exemplo n.º 29
0
def button_hdlr(_pin):
    global last_press
    state = machine.disable_irq()
    if utime.time() - last_press > 1:
        last_press = utime.time()
        micropython.schedule(debounce_press, 0)
    machine.enable_irq(state)
Exemplo n.º 30
0
def main():
    '''Main Event Loop'''
    global interruptCounter, totalInterrupts, CUR_FORMULA, READY, GPIO_ODR, COL_INDEX, COL_TIME

    # PINS REGISTERS
    GPIO_REG = const(0x3ff44000)
    GPIO_EN = const(0x8)
    GPIO_CLR = const(0xC)
    BIT21 = const(1 << 21)  # 2097152
    BIT14 = const(1 << 14)  # 16384
    BIT26 = const(1 << 26)  # 67108864
    BIT15 = const(1 << 15)  # 32768
    BIT25 = const(1 << 25)  # 33554432
    BIT27 = const(1 << 27)  # 134217728
    BIT12 = const(1 << 12)  # 4096
    BIT13 = const(1 << 13)  # 8192
    LEDS = [BIT21, BIT14, BIT26, BIT15, BIT25, BIT27, BIT12, BIT13]
    _LED_PINS = [21, 14, 26, 15, 25, 27, 12, 13]
    LED_PINS = [Pin(i, Pin.OUT, value=0) for i in _LED_PINS]
    ALL_LEDS = const(237039616)
    LED_COUNT = const(8)
    GPIO_ODR = {
        "REG": GPIO_REG,
        "EN": GPIO_EN,
        "CLR": GPIO_CLR,
        "ALL_LEDS": ALL_LEDS,
        "LED_COUNT": LED_COUNT
    }

    # Last Revolution Time
    LAST_REV = 0

    print("POVPi Ready")
    display_status(9)
    # Run Blynk in Thread
    thread.stack_size(5 * 1024)
    thread.start_new_thread(run_blynk, ())
    # Startup Shadow
    startup_shadow = {"display": "_LINE_", "enabled": True}
    update_shadow(new_state=startup_shadow)
    gc.collect()
    while 1:
        # Handle Interrupts
        if interruptCounter > 0:
            state = machine.disable_irq()
            interruptCounter -= 1
            machine.enable_irq(state)
            time_delta = time.ticks_diff(time.ticks_cpu(), LAST_REV)
            COL_TIME = int(time_delta / 360)
            COL_INDEX = 0
            LAST_REV = time.ticks_cpu()
            totalInterrupts += 1
        if READY and CUR_FORMULA:
            if LAST_REV == 0:
                LAST_REV = time.ticks_cpu()
            if COL_INDEX < 90:
                byte = CUR_FORMULA[COL_INDEX]
            COL_INDEX = display(byte, COL_TIME, COL_INDEX, GPIO_REG, GPIO_EN,
                                GPIO_CLR, ALL_LEDS)
Exemplo n.º 31
0
    def check_queued_tasks(self, was_idle):
        if self.queued & CONSTANTS.QUEUED_TASKS.STRIKE:
            was_idle = False
            self.strike()
            state = disable_irq()
            self.queued &= ~CONSTANTS.QUEUED_TASKS.STRIKE
            enable_irq(state)

        if self.queued & CONSTANTS.QUEUED_TASKS.DISARMED:
            was_idle = False
            self.disarmed()
            state = disable_irq()
            self.queued &= ~CONSTANTS.QUEUED_TASKS.DISARMED
            enable_irq(state)

        if was_idle:
            self.idle()
Exemplo n.º 32
0
 def timeouta(self, t):
     #print(t)
     state = machine.disable_irq()
     self.client.check_msg()
     machine.enable_irq(state)
     self.tim.init(period=self.timeout,
                   mode=Timer.ONE_SHOT,
                   callback=self.timeouta)
Exemplo n.º 33
0
def getval(pin):
    """readout a dht11/22 sensor"""
    ms = [1] * 300
    pin(0)
    time.sleep_us(20000)
    pin(1)
    irqf = disable_irq()
    for i in range(len(ms)):
        ms[i] = pin()  # sample input and store value
    enable_irq(irqf)
    return ms
Exemplo n.º 34
0
Arquivo: o.py Projeto: psy0rz/stuff
    def write_bit(self, value):
        sleep_us = time.sleep_us
        pin = self.pin

        i = machine.disable_irq()
        pin(0)
        sleep_us(1)
        pin(value)
        sleep_us(60)
        pin(1)
        sleep_us(1)
        machine.enable_irq(i)
Exemplo n.º 35
0
Arquivo: o.py Projeto: psy0rz/stuff
    def read_bit(self):
        sleep_us = time.sleep_us
        enable_irq = machine.enable_irq
        pin = self.pin

        pin(1) # half of the devices don't match CRC without this line
        i = machine.disable_irq()
        pin(0)
        sleep_us(1)
        pin(1)
        sleep_us(1)
        value = pin()
        enable_irq(i)
        sleep_us(40)
        return value
Exemplo n.º 36
0
def update_mboot(filename):
    print('Loading file', filename)

    mboot_fw = dfu_read(filename)
    if mboot_fw is None:
        return
    if len(mboot_fw) != 1:
        assert 0
    mboot_addr, mboot_fw = mboot_fw[0]
    if mboot_addr != 0x08000000:
        assert 0

    # TODO: Validate firmware in a simple way

    print('Found Mboot data with size %u.' % len(mboot_fw))

    chk = check_mem_contains(mboot_addr, mboot_fw)
    if chk:
        print('Supplied version of Mboot is already on device.')
        return

    print('Programming Mboot, do not turn off!')
    time.sleep_ms(50)

    irq = machine.disable_irq()
    flash_unlock()
    flash_erase_sector(0)
    if len(mboot_fw) > 16 * 1024 and not check_mem_erased(mboot_addr + 16 * 1024, 16 * 1024):
        flash_erase_sector(1)
    flash_write(mboot_addr, mboot_fw)
    flash_lock()
    machine.enable_irq(irq)

    print('New Mboot programmed.')

    if check_mem_contains(mboot_addr, mboot_fw):
        print('Verification of new Mboot succeeded.')
    else:
        print('Verification of new Mboot FAILED!  Try rerunning.')

    print('Programming finished, can now reset or turn off.')
Exemplo n.º 37
0
    def read(self):
        # wait for the device being ready
        while self.pOUT() == 1:
            idle()

        # shift in data, and gain & channel info
        result = 0
        for j in range(24 + self.GAIN):
            state = disable_irq()
            self.pSCK(True)
            self.pSCK(False)
            enable_irq(state)
            result = (result << 1) | self.pOUT()

        # shift back the extra bits
        result >>= self.GAIN

        # check sign
        if result > 0x7fffff:
            result -= 0x1000000

        return result
Exemplo n.º 38
0
# Little hack because the WDT's .feed doesn't really work on ESP8266 yet
# This is required because sometimes, importing the 'moisture' module
# fails with a MemoryError
import machine
irq = machine.disable_irq()

from moisture import MoistureMonitor
import network
import time
import ntptime

import config

machine.enable_irq(irq)

sta = network.WLAN(network.STA_IF)
sta.active(True)

for ap in sta.scan():
    if ap[0] not in config.aps:
        continue

    print("Found AP {}".format(ap))

    ap = ap[0]

    sta.connect(ap, config.aps[ap])

    while sta.status() != network.STAT_GOT_IP:
        print("Waiting for connection to come up")
        time.sleep(1)
Exemplo n.º 39
0
 def disableIRQ(self):
     self.irqState = machine.disable_irq() # Start of critical section