Exemple #1
0
 def _write_bit(self, value, pin_init, pin_value, Pin_OUT_PP):
     """
     Write a single bit - requires cached methods/attributes be passed as arguments.
     See also write_bit()
     """
     d0, d1, d2, d3 = self.write_delays
     udelay = pyb.udelay
     if value:
         # write 1
         i = disable_irq()
         pin_value(0)
         pin_init(Pin_OUT_PP)
         udelay(d0)
         pin_value(1)
         enable_irq(i)
         udelay(d1)
     else:
         # write 0
         i = disable_irq()
         pin_value(0)
         pin_init(Pin_OUT_PP)
         udelay(d2)
         pin_value(1)
         enable_irq(i)
         udelay(d3)
    def main(self):
        """
        Main function where interrupt handler is initialized and a callback
        function passed
        
        :param: None
        :return: None
        """
        # Allocate exception buffer since heap cannot be allocated within an ISR context
        micropython.alloc_emergency_exception_buf(100)
        # Set up interrupt handler
        ext_int = pyb.ExtInt(self.pin, pyb.ExtInt.IRQ_FALLING,
                             pyb.Pin.PULL_NONE, self.measure)

        while self.num_seconds < (self.max_duration // self.sample_period):
            # Sleep for specified interval to count number of interrupts received
            time.sleep(self.sample_period)
            # Disable IRQs and process result
            pyb.disable_irq()
            rpm = self.irq_count * 60 / (2 * self.blades)
            output_str = str(self.num_seconds) + "," + "{0:.2f}".format(rpm)
            # Print the result to serial console
            print(output_str)
            # Reset IRQ counter for the next interval
            self.irq_count = 0
            self.num_seconds += self.sample_period
            # Enable IRQs
            pyb.enable_irq()
Exemple #3
0
 def send_msg(self, msg):
     """Send a message (bytes or str) to host"""
     if isinstance(msg, str): msg = msg.encode()
     uart = self.uart
     disable_irq()
     uart.writechar(CMD_MSG)
     uart.write(pack('H', len(msg)))
     uart.write(msg)
     enable_irq()
Exemple #4
0
 def y11(self,unused):
     if self.y2.value():
         irq_state = disable_irq()
         self.toneEnQueueable.push(self.targCoilID,-1)
         enable_irq(irq_state)
     else:
         irq_state = disable_irq()
         self.toneEnQueueable.push(self.targCoilID,1)
         enable_irq(irq_state)
Exemple #5
0
def pulse():
  global number_of_pulse_pairs
  global adc_vals
  global adc
  pyb.disable_irq()
  # TODO: check these two have any effect, I thought they might prevent a pending GPIO toggle
  # stm.mem32[stm.TIM5 + stm.TIM_EGR] &= 0xff<<8 #|= 1
  # stm.mem32[stm.TIM2 + stm.TIM_EGR] &= 0xff<<8 #|= 1
  force_inactive_tim1()
  force_inactive_tim2()
  force_inactive_tim5()
  rep_counter_overflow_detector.set_longer_counter(number_of_pulse_pairs)
  stm.mem32[stm.TIM5 + stm.TIM_EGR] |= 1 # UG: Update generation is set updates registers, inits counter.
  stm.mem32[stm.TIM3 + stm.TIM_EGR] |= 1
  stm.mem32[stm.TIM2 + stm.TIM_EGR] |= 1
  stm.mem32[stm.TIM4 + stm.TIM_EGR] |= 1
  stm.mem32[stm.TIM1 + stm.TIM_EGR] |= 1  # gotta do this, or the num-pulses won't register (if it was just changed)

  # reset the counters to their default values (mostly 0, but some offset)
  stm.mem16[stm.TIM1 + stm.TIM_CNT] = 0
  #stm.mem16[stm.TIM1 + stm.TIM_CNT] = (stm.mem32[stm.TIM1 + stm.TIM_ARR] // 2) + (2* get_tim5_width1())+2
  stm.mem16[stm.TIM1 + stm.TIM_CNT] = stm.mem32[stm.TIM1 + stm.TIM_ARR] # it seems TIM1 is running at double the freq TIM2/5
  stm.mem32[stm.TIM2 + stm.TIM_CNT] = 0#stm.mem32[stm.TIM2 + stm.TIM_ARR] //2
  stm.mem32[stm.TIM3 + stm.TIM_CNT] = 0
  stm.mem32[stm.TIM4 + stm.TIM_CNT] = stm.mem32[stm.TIM5 + stm.TIM_ARR] //2
  # offset TIM5 phase by 180 degrees relative to TIM2
  stm.mem32[stm.TIM5 + stm.TIM_CNT] = stm.mem32[stm.TIM5 + stm.TIM_ARR] //2   # offset TIM5 counter by half-the pulse-width

  tim2_3_set_pwm2()
  tim5_set_pwm2()
  tim1_1_set_pwm2()
  
  # enable OPM
  stm.mem16[tim_kickoff + stm.TIM_CR1] |= 1<<TIM_CR1_OPM
  # disable OPM
  stm.mem16[stm.TIM2 + stm.TIM_CR1] &= (~(1<<TIM_CR1_OPM))&two_byte_mask
  # disable OPM
  stm.mem16[stm.TIM5 + stm.TIM_CR1] &= (~(1<<TIM_CR1_OPM))&two_byte_mask
  stm.mem16[stm.TIM4 + stm.TIM_CR1] &= (~(1<<TIM_CR1_OPM))&two_byte_mask
  
  rep_counter_overflow_detector.longer_counter = rep_counter_overflow_detector._longer_counter
  print('trace')
  stm.mem16[stm.TIM1 + stm.TIM_SR] = (stm.mem16[stm.TIM1 + stm.TIM_SR] & 0b111<<13) # clear all flags
  pyb.enable_irq()
  print('pulsing')
  # enable OPM
  #reset_vals()
  adc.read_timed(adc_vals)
  #stm.mem16[stm.TIM4 + stm.TIM_CR1] |= 1 # CEN -- start ADC callback
  if rep_counter_overflow_detector.longer_counter==1:
    stm.mem16[tim_kickoff + stm.TIM_CR1] |= 1
    stm.mem16[stm.TIM1 + stm.TIM_RCR] = rep_counter_overflow_detector.or_in_end
  else:
    stm.mem16[tim_kickoff + stm.TIM_CR1] |= 1
  adc.read_timed_stop()
  print('done')
Exemple #6
0
 def dump(self):
     ts = [0] * Tachometer.NUM_SAMPLES
     pyb.disable_irq()
     for i in range(Tachometer.NUM_SAMPLES):
         ts[i] = self.timestamp[i]
     last_pulse = self.pulse_timestamp
     delta_time = self.delta_time
     num_samples = self.num_samples
     pyb.enable_irq()
     print("last_pulse =", last_pulse)
     print("delta_time =", delta_time)
     print("num_samples =", num_samples)
     for i in range(Tachometer.NUM_SAMPLES):
         print("ts[%d] = %d" % (i, ts[i]))
Exemple #7
0
 def dump(self):
     ts = [0] * Tachometer.NUM_SAMPLES
     pyb.disable_irq()
     for i in range(Tachometer.NUM_SAMPLES):
         ts[i] = self.timestamp[i]
     last_pulse = self.pulse_timestamp
     delta_time = self.delta_time
     num_samples = self.num_samples
     pyb.enable_irq()
     print("last_pulse =", last_pulse)
     print("delta_time =", delta_time)
     print("num_samples =", num_samples)
     for i in range(Tachometer.NUM_SAMPLES):
         print("ts[%d] = %d" % (i, ts[i]))
Exemple #8
0
 def callback(self,unusedLine):
     #if self.locked:
     #    return
     #self.locked = True
     irq_state = disable_irq()
     self.push(self.id)
     enable_irq(irq_state)
def listen_for_signals(can, leds):
    global SIGNALS
    SIGNALS[0] &= 0b0
    state = None

    with open('/sd/can.log', 'a') as f:
        try:
            while True:
                if SIGNALS[0] & 0b1:
                    state = disable_irq()
                    SIGNALS[0] &= 0b0
                    enable_irq(state)

                    while can.any(0):
                        _id, rtr, fmi, data = can.recv(0, timeout=10000)
                        print(str(_id),
                              '1' if rtr else '0',
                              str(fmi),
                              str(data),
                              sep=',',
                              file=f)
                        #f.flush()
                        data = int.from_bytes(data, 'little')

                        if _id == 11:
                            if data & 0b100:
                                leds[data & 0b11].on()
                            else:
                                leds[data & 0b11].off()
        except Exception as e:
            print('Exception: {}'.format(e))
        except KeyboardInterrupt as e:
            print(e)

    os.sync()
Exemple #10
0
    def get(self, in_ISR=False):
        """ Read an item from the queue. If there isn't anything in there,
        wait (blocking the calling process) until something becomes
        available. If non-blocking reads are needed, one should call @c any()
        to check for items before attempting to read any items.
        @param in_ISR Set this to @c True if calling from within an ISR """

        # Wait until there's something in the queue to be returned
        while self.empty():
            pass

        # Prevent data corruption by blocking interrupts during data transfer
        if self._thread_protect and not in_ISR:
            irq_state = pyb.disable_irq()

        # Get the item to be returned from the queue
        to_return = self._buffer[self._rd_idx]

        # Move the read pointer and adjust the number of items in the queue
        self._rd_idx += 1
        if self._rd_idx >= self._size:
            self._rd_idx = 0
        self._num_items -= 1
        if self._num_items < 0:
            self._num_items = 0

        # Re-enable interrupts
        if self._thread_protect and not in_ISR:
            pyb.enable_irq(irq_state)

        return (to_return)
Exemple #11
0
 def reset_count(self):
     '''Resets the counts and protects the processs form being
     interrupted.
     '''
     irq_state = pyb.disable_irq()
     self._count = 0
     pyb.enable_irq(irq_state)
Exemple #12
0
 def ioctl(self, req, arg):
     if req == MP_STREAM_POLL and (arg & MP_STREAM_POLL_RD):
         state = pyb.disable_irq()
         r = self.ready
         self.ready = False
         pyb.enable_irq(state)
         return r
     return 0
Exemple #13
0
 def loop(self):
     self.geigerPower.low()
     self.wix.high()
     geiger.start()
     rtc = pyb.RTC()
     ap1m = tapunte.tapunte()
     t15 = 0 #contador de 15 minutos
     #esperamos segs = 0
     datetime = rtc.datetime()
     while datetime[6] != 0:
         datetime = rtc.datetime()
     lm = datetime[5]
     pyb.disable_irq()
     geiger.count1m = 0
     geiger.count15m = 0
     pyb.enable_irq()
     while True:
         datetime = rtc.datetime()
         if datetime[5] == lm:
             pyb.delay(50)
         else:
             lm = datetime[5]
             t15 = t15 + 1
             is15 = t15 == 15
             pyb.disable_irq()
             count1m_copy = geiger.count1m
             count15m_copy = geiger.count15m
             geiger.count1m = 0
             if is15:
                 geiger.count15m = 0
             pyb.enable_irq()
             cpm = count1m_copy
             if cpm > ap1m.maxcpm:
                 ap1m.maxcpm = cpm
             if cpm < ap1m.mincpm:
                 ap1m.mincpm = cpm
             if is15:
                 ap1m.cpm = count15m_copy//15
                 ap1m.d = int('0x%02d%02d%02d%02d'%(datetime[0]%100, datetime[1], datetime[2], datetime[3]),16)
                 ap1m.t = int('0x%02d%02d%02d%02d'%(datetime[4], datetime[5], datetime[6], 0), 16)
                 ap1m.am2302 = self.am2302.getTempHum()
                 self.fram.framWrite(self.frt.indApunte * tapunte.TAPUNTE_SIZE, ap1m.buff)
                 self.frt.incrIndApunte()
                 t15 = 0
                 ap1m.maxcpm = 0
                 ap1m.mincpm = 65535
Exemple #14
0
 def doTrem(self):
     if not self.aVec[0]:
         return
     #State.printT('Tremolo Level:\t',self.tremoloLevel)
     #print('Push: M Vol %s'%self.vVec[self.tremoloLevel])
     irq_state = disable_irq()
     self.volEnQueueable.push(self.targCoilID,self.vVec[self.tremoloLevel])
     enable_irq(irq_state)
     self.tremoloLevel ^= 1
Exemple #15
0
 def speed(self):  #meters/second
     irq_state = disable_irq()
     periods = [ticks_diff(self._sample_times[i], self._sample_times[i+1]) \
                for i in range(self.BUFFER_SIZE-1)]
     enable_irq(irq_state)
     period = sum([x * y for x, y in zip(self.WEIGHTS, periods)]) * pow(
         10, -3)  #seconds
     speed = self.STEP / period if period > 0 else 0  # meters/second
     return speed * 3.6  # m/s -> km/h
Exemple #16
0
 def doVib(self):
     if not self.aVec[1]:
         return
     #State.printT('Vibrato Level:\t',self.vibratoLevel)
     #print('Push: M Tone %s'%self.tVec[self.vibratoLevel])
     irq_state = disable_irq()
     self.toneEnQueueable.push(self.targCoilID,self.tVec[self.vibratoLevel])
     enable_irq(irq_state)
     self.vibratoLevel ^= 1
Exemple #17
0
def test_irq():
    # test basic disable/enable
    i1 = pyb.disable_irq()
    print(i1)
    pyb.enable_irq() # by default should enable IRQ

    # check that interrupts are enabled by waiting for ticks
    pyb.delay(10)

    # check nested disable/enable
    i1 = pyb.disable_irq()
    i2 = pyb.disable_irq()
    print(i1, i2)
    pyb.enable_irq(i2)
    pyb.enable_irq(i1)

    # check that interrupts are enabled by waiting for ticks
    pyb.delay(10)
Exemple #18
0
 def value(self):
     '''Returns the final value of this input.  Interrupts are disabled so that
     the value isn't altered during retrieval.  The conversion function, if supplied,
     in the constructor is applied before returning.
     '''
     irq_state = pyb.disable_irq()
     val = self._compute_value()
     pyb.enable_irq(irq_state)
     return self.convert_func(val) if self.convert_func else val
Exemple #19
0
def test_irq():
    # test basic disable/enable
    i1 = pyb.disable_irq()
    print(i1)
    pyb.enable_irq()  # by default should enable IRQ

    # check that interrupts are enabled by waiting for ticks
    pyb.delay(10)

    # check nested disable/enable
    i1 = pyb.disable_irq()
    i2 = pyb.disable_irq()
    print(i1, i2)
    pyb.enable_irq(i2)
    pyb.enable_irq(i1)

    # check that interrupts are enabled by waiting for ticks
    pyb.delay(10)
Exemple #20
0
 def poll(self):
     #if not self.bounceMgr.ready():
      #   return
     res = self.update()
     if res:
         #self.bounceMgr.trigger()
         irq_state = disable_irq()
         self.enQV[res[0]].push(self.id,res[1])
         enable_irq(irq_state)
Exemple #21
0
    def _send_receive(self, buff):
#         print(buff)
        irq = pyb.disable_irq()
        self.CSn.low()
        self.bus.send_recv(buff, buff)
        self.CSn.high()
        pyb.enable_irq(irq)
        self._parse_status(buff[:2])
#         print(buff)
        return buff
Exemple #22
0
 def _send_receive(self, buff):
     #         print(buff)
     irq = pyb.disable_irq()
     self.CSn.low()
     self.bus.send_recv(buff, buff)
     self.CSn.high()
     pyb.enable_irq(irq)
     self._parse_status(buff[:2])
     #         print(buff)
     return buff
Exemple #23
0
 def rpm(self):
     if not self.pulse_detected:
         return 0
     timer_count = self.timer.counter() & 0x1fffffff
     last_pulse = self.pulse_timestamp
     if timer_count < last_pulse:
         last_pulse -= 0x20000000
     if (timer_count - last_pulse) > 1000000:
         # No pulses in the past second.
         self.pulse_detected = False
         #print("timer_count =",  timer_count, "last_pusle =",  last_pulse)
         #self.dump()
         return 0
     pyb.disable_irq()
     delta_time = self.delta_time
     num_samples = self.num_samples
     pyb.enable_irq()
     if delta_time == 0 or self.pulses_per_rev == 0:
         return 0
     return num_samples * 1000000 * 60 / (delta_time * self.pulses_per_rev)
Exemple #24
0
    def dispatch(self):
        irq_state = pyb.disable_irq()
        flags = self.flags
        self.flags = 0
        pyb.enable_irq(irq_state)

        for i in range(32):
            if (flags & (1 << i)) != 0:
                handler = self.handlers.get(i)
                if handler != None:
                    handler()
Exemple #25
0
 def rpm(self):
     if not self.pulse_detected:
         return 0
     timer_count = self.timer.counter() & 0x1fffffff
     last_pulse = self.pulse_timestamp
     if timer_count < last_pulse:
         last_pulse -= 0x20000000
     if (timer_count - last_pulse) > 1000000:
         # No pulses in the past second.
         self.pulse_detected = False
         #print("timer_count =",  timer_count, "last_pusle =",  last_pulse)
         #self.dump()
         return 0
     pyb.disable_irq()
     delta_time = self.delta_time
     num_samples = self.num_samples
     pyb.enable_irq()
     if delta_time == 0 or self.pulses_per_rev == 0:
         return 0
     return num_samples * 1000000 * 60 / (delta_time * self.pulses_per_rev)
Exemple #26
0
 def release(self):
     if not self.__val:
         raise RuntimeError('mutex didnt aquired yet')
     thread_id = _thread.get_ident()
     if self.__restrict_owner and self.__owner != thread_id:
         raise RuntimeError('mutex been released by other thread')
     irq_state = None
     if self.__using_critical_section:
         irq_state = pyb.disable_irq()
     self.__owner = -1
     self.__val = False
     if self.__using_critical_section:
         pyb.enable_irq(irq_state)
Exemple #27
0
 def _write(self, data, memaddr, devaddr):
     '''
     Perform a memory write. Caller should trap OSError.
     '''
     irq_state = True
     if self.disable_interrupts:
         irq_state = pyb.disable_irq()
     result = self._mpu_i2c.mem_write(data,
                                      devaddr,
                                      memaddr,
                                      timeout=self._timeout)
     pyb.enable_irq(irq_state)
     return result
def listen_for_benchmark(can):
    global SIGNALS
    SIGNALS[0] &= 0
    state = None

    while True:
        if SIGNALS[0] & 1:
            state = disable_irq()
            SIGNALS[0] &= 0
            enable_irq(state)

            while can.any(0):
                can.recv(0, timeout=10000)
Exemple #29
0
 def _read(self, count, memaddr, devaddr):
     '''
     Perform a memory read. Caller should trap OSError. Possible values of
     error args[0]: errorno.ETIMEDOUT errno.EBUSY or errno.EIO
     '''
     irq_state = True
     if self.disable_interrupts:
         irq_state = pyb.disable_irq()
     result = self._mpu_i2c.mem_read(count,
                                     devaddr,
                                     memaddr,
                                     timeout=self._timeout)
     pyb.enable_irq(irq_state)
     return result
Exemple #30
0
 def acquire(self, dummy=False):
     if dummy:
         self.__val = True
     else:
         thread_id = _thread.get_ident()
         if self.__val:
             if self.__owner == thread_id:
                 raise RuntimeError('dead lock')
             while self.__val:
                 pass
         irq_state = None
         if self.__using_critical_section:
             irq_state = pyb.disable_irq()
         self.__val = True
         self.__owner = thread_id
         if self.__using_critical_section:
             pyb.enable_irq(irq_state)
Exemple #31
0
    def get(self, in_ISR=False):
        """ Read an item of data from the share. Interrupts are disabled as
        the data is read so as to prevent data corruption by changes in
        the data as it is being read. 
        @param in_ISR Set this to True if calling from within an ISR """

        # Disable interrupts before reading the data
        if self._thread_protect and not in_ISR:
            irq_state = pyb.disable_irq()

        to_return = self._buffer[0]

        # Re-enable interrupts
        if self._thread_protect and not in_ISR:
            pyb.enable_irq(irq_state)

        return (to_return)
Exemple #32
0
    def put(self, data, in_ISR=False):
        """ Write an item of data into the share. Any old data is overwritten.
        This code disables interrupts during the writing so as to prevent
        data corrupting by an interrupt service routine which might access
        the same data.
        @param data The data to be put into this share
        @param in_ISR Set this to True if calling from within an ISR """

        # Disable interrupts before writing the data
        if self._thread_protect and not in_ISR:
            irq_state = pyb.disable_irq()

        self._buffer[0] = data

        # Re-enable interrupts
        if self._thread_protect and not in_ISR:
            pyb.enable_irq(irq_state)
Exemple #33
0
    def write_bit(self, value):
        """
        Write a single bit.
        """

        # Optimisation of stabilisation of time intervals
        pin, udelay, pinInit, pinValue, pinOUT, pinIN = self.links

        i = disable_irq()
        pinValue(0)
        pinInit(pinOUT)
        udelay(1)
        if value:
            pinValue(1)
        udelay(60)
        pinValue(1)
        udelay(1)
        enable_irq(i)
Exemple #34
0
    def reset(self):
        """
        Perform the onewire reset function.
        """

        # Optimisation of stabilisation of time intervals
        pin, udelay, pinInit, pinValue, pinOUT, pinIN = self.links

        pinValue(0)
        pinInit(pinOUT)
        udelay(480)
        i = disable_irq()
        pinInit(pinIN, pin.PULL_UP)
        udelay(60)
        status = not pinValue()
        enable_irq(i)
        udelay(420)
        return status
Exemple #35
0
    def reset(self):
        """
        Perform the onewire reset function.
        """
        
        # Optimisation of stabilisation of time intervals
        pin, udelay, pinInit, pinValue, pinOUT, pinIN = self.links

        pinValue(0)
        pinInit(pinOUT)
        udelay(480)
        i = disable_irq()
        pinInit(pinIN, pin.PULL_UP)
        udelay(60)
        status = not pinValue()
        enable_irq(i)
        udelay(420)
        return status
Exemple #36
0
    def write_bit(self, value):
        """
        Write a single bit.
        """
        
        # Optimisation of stabilisation of time intervals
        pin, udelay, pinInit, pinValue, pinOUT, pinIN = self.links

        i = disable_irq()
        pinValue(0)
        pinInit(pinOUT)
        udelay(1)
        if value:
            pinValue(1)
        udelay(60)
        pinValue(1)
        udelay(1)
        enable_irq(i)
Exemple #37
0
 def _read_bit(self, pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP):
     """
     Read a single bit - requires cached methods/attributes be passed as arguments.
     See also read_bit()
     """
     d0, d1, d2 = self.read_delays
     udelay = pyb.udelay
     pin_init(Pin_IN, Pin_PULL_UP) # TODO why do we need this?
     i = disable_irq()
     pin_value(0)
     pin_init(Pin_OUT_PP)
     udelay(d0)
     pin_init(Pin_IN, Pin_PULL_UP)
     udelay(d1)
     value = pin_value()
     enable_irq(i)
     udelay(d2)
     return value
Exemple #38
0
	def get(self, arr):
		""" Get new data from buffer and decrease nr_bytes.

		If no data available, return -1 (MaxInt when Uint)
		"""
		if arr[3]:  # nr_data available
			p = arr[2]  # OK, Fetch get_ptr
			data = arr[p]
			p += 1
			if p >= arr[4]:
				p = 5                   # Make circular
			arr[2] = p  # Update get_ptr -> next position to get data from
			''' Protect the critical section: update nr_data '''
			int_stat = disable_irq()    # We don't want an interrupt just now
			arr[3] -= 1  # Publish new data
			enable_irq(int_stat)        # Restore previus mask
		else:
			data = -1                   # Oops: no data available !
		return data
Exemple #39
0
    def read_bit(self):
        """
        Read a single bit
        """

        # Optimisation of stabilisation of time intervals
        pin, udelay, pinInit, pinValue, pinOUT, pinIN = self.links

        pinInit(pinIN, pin.PULL_UP) # Half of the packages are not matching by CRC whitout this line
        i = disable_irq()
        pinValue(0)
        pinInit(pinOUT)
        udelay(1)
        pinInit(pinIN, pin.PULL_UP)
        udelay(1)
        value = pinValue()
        enable_irq(i)
        udelay(40)
        return value
def write(data):
    # Prepare the data to transmit first so we can do it quickly.
    out_data = []
    for i in range(0, len(data), 2):
        out_data.append(data[i:i+2])
    # Disable interrupts so we can send all packets without gaps.
    state = pyb.disable_irq()
    for i in range(len(out_data)):
        max_exceptions = 10
        loop = True
        while(loop):
            try:
                bus.send(out_data[i], timeout = 1)
                loop = False
            except OSError as error:
                if(max_exceptions <= 0):
                    pyb.enable_irq(state)
                    return
                max_exceptions -= 1
    pyb.enable_irq(state)
Exemple #41
0
	def put(self, arr, data):  # Todo: What if data is a tuple or list? Add method put_all ?
		""" Put new data into buffer and increase nr_bytes.

		Skips new data if buffer already full, but "peek" is always updated
		"""
		arr[0] = data  # Always update peek = last input data
		s = arr[3]  # nr_data = already in arr
		if s < arr[4] - 5:  # Check if room for more
			p = arr[1]  # Yes, so Fetch put_ptr
			arr[p] = data
			p += 1
			if p >= arr[4]:
				p = 5                   # Make circular (skipping pointers in beginning)
			arr[1] = p  # Update put_ptr -> next position to put data
			''' Protect the critical section: update nr_data (do not use 's' since it could be old)'''
			int_stat = disable_irq()    # We don't want an interrupt just now
			arr[3] += 1  # Publish new data
			enable_irq(int_stat)        # Restore previous mask
		else:
			pass                        # We are full, do nothing
Exemple #42
0
def write(data):
    # Prepare the data to transmit first so we can do it quickly.
    out_data = []
    for i in range(0, len(data), 2):
        out_data.append(data[i:i + 2])
    # Disable interrupts so we can send all packets without gaps.
    state = pyb.disable_irq()
    for i in range(len(out_data)):
        max_exceptions = 10
        loop = True
        while (loop):
            try:
                bus.send(out_data[i], timeout=1)
                loop = False
            except OSError as error:
                if (max_exceptions <= 0):
                    pyb.enable_irq(state)
                    return
                max_exceptions -= 1
    pyb.enable_irq(state)
Exemple #43
0
    def read_bit(self):
        """
        Read a single bit
        """

        # Optimisation of stabilisation of time intervals
        pin, udelay, pinInit, pinValue, pinOUT, pinIN = self.links

        pinInit(
            pinIN, pin.PULL_UP
        )  # Half of the packages are not matching by CRC whitout this line
        i = disable_irq()
        pinValue(0)
        pinInit(pinOUT)
        udelay(1)
        pinInit(pinIN, pin.PULL_UP)
        udelay(1)
        value = pinValue()
        enable_irq(i)
        udelay(40)
        return value
Exemple #44
0
def display_pusteblume(hum, average_hum_diff, tmp, last_image):
    # turn off all interrupts. Switch interrupt (line 10) erases the display and crashes
    # if sth. writes to it at the same time.
    irq_state = pyb.disable_irq()
    try:
        with open('/sd/pusteblume/s_p_{}.jpg'.format(last_image), 'rb') as f:
            f.readinto(image_buf)
            lcd.set_pos(0, 0)
            lcd.jpeg(image_buf)
            lcd.set_pos(5, 110)
            lcd.set_font(1, scale=1)
            lcd.set_text_color(lcd.rgb(188, 234, 231), lcd.rgb(64, 64, 128))
            lcd.write('H ' + str(round(hum)) + ' ')
            lcd.set_pos(40, 130)
            lcd.write(str(round(average_hum_diff, 2)))

            lcd.set_pos(80, 110)
            lcd.set_font(1, scale=1)
            lcd.set_text_color(lcd.rgb(188, 234, 231), lcd.rgb(64, 64, 128))
            lcd.write('T ' + str(round(tmp)))
    finally:
        pyb.enable_irq(irq_state)
Exemple #45
0
    def put(self, item, in_ISR=False):
        """ Put an item into the queue. If there isn't room for the item, wait 
        (blocking the calling process) until room becomes available,
        unless the @c overwrite constructor parameter was set to @c True to 
        allow old data to be clobbered. If non-blocking behavior without
        overwriting is needed, one should call @c full() to ensure that the 
        queue is not full before putting data into it.
        @param item The item to be placed into the queue
        @param in_ISR Set this to @c True if calling from within an ISR """

        # If we're in an ISR and the queue is full and we're not allowed to
        # overwrite data, we have to give up and exit
        if self.full():
            if in_ISR:
                return

            # Wait (if needed) until there's room in the buffer for the data
            if not self._overwrite:
                while self.full():
                    pass

        # Prevent data corruption by blocking interrupts during data transfer
        if self._thread_protect and not in_ISR:
            irq_state = pyb.disable_irq()

        # Write the data and advance the counts and pointers
        self._buffer[self._wr_idx] = item
        self._wr_idx += 1
        if self._wr_idx >= self._size:
            self._wr_idx = 0
        self._num_items += 1
        if self._num_items >= self._size:
            self._num_items = self._size

        # Re-enable interrupts
        if self._thread_protect and not in_ISR:
            pyb.enable_irq(irq_state)
Exemple #46
0
    def reset(self):
        """
        Perform the onewire reset function.
        Returns 1 if a device asserted a presence pulse, 0 otherwise.

        If you receive 0, then check your wiring and make sure you are providing
        power and ground to your devices.
        """
        retries = 25
        self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP)

        # We will wait up to 250uS for
        # the bus to come high, if it doesn't then it is broken or shorted
        # and we return a 0;

        # wait until the wire is high... just in case
        while True:
            if self.data_pin.value():
                break
            retries -= 1
            if retries == 0:
                raise OSError("OneWire pin didn't go high")
            pyb.udelay(10)

        #  pull the bus low for at least 480us
        self.data_pin.low()
        self.data_pin.init(self.data_pin.OUT_PP)
        pyb.udelay(480)

        # If there is a slave present, it should pull the bus low within 60us
        i = pyb.disable_irq()
        self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP)
        pyb.udelay(70)
        presence = not self.data_pin.value()
        pyb.enable_irq(i)
        pyb.udelay(410)
        return presence
Exemple #47
0
	ptr += 1				# increment buffer pointer (index)

	if (ptr == N):			# wraparound ptr - goes 0 to N-1

		ptr = 0

		buffer_full = True	# set the flag (semaphore) for buffer full





# Create timer interrupt - one every 1/8000 sec or 125 usec

pyb.disable_irq()			# disable interrupt while configuring timer

sample_timer = pyb.Timer(7, freq=8000)	# set timer 7 for 8kHz

sample_timer.callback(isr_sampling)		# specify interrupt service routine

pyb.enable_irq()			# enable interrupt again


# -------- End of interrupt section ----------------




# Define constants for main program loop - shown in UPPERCASE
        self.main_count = 0
        self.done = False
        tim = pyb.Timer(4)
        tim.init(freq=1000)
        tim.callback(self.callback)

    def report(self):
        print("main_count = %d irq_count = %d counter = %d sum = %d" % (self.main_count, self.irq_count, self.counter, self.main_count + self.irq_count))

    def callback(self, tim):
        self.counter += 1
        self.irq_count += 1
        if self.irq_count >= 10000:
            tim.callback(None)
            self.done = True

t = AtomicTest()

t.start()
while not t.done:
    t.main_count += 1
    t.counter += 1
t.report()

t.start()
while not t.done:
    t.main_count += 1
    pyb.disable_irq()
    t.counter += 1
    pyb.enable_irq()
t.report()
Exemple #49
0
 def callback(self,unusedLine):
     irq_state = disable_irq()
     self.push(self.id)
     enable_irq(irq_state)
Exemple #50
0
import pyb

start = pyb.millis()
count = 0
while True:
    pyb.disable_irq()
    m = pyb.millis()
    u = pyb.micros() & 0x7fffffff
    pyb.enable_irq()
    m2 = u // 1000
    if m2 != m:
        if m2 != (m + 1) or (u % 1000) > 100:
            print("msec %d usec %d" % (m, u))
            count += 1
    if (m - start) >= 10000:
        print('%4d err = %d' % (m // 1000, count))
        start = m
        if count > 0:
            break

Exemple #51
0
 def show(self):
     buf = self.buf
     pyb.freq(168000000)
     pyb.disable_irq()
     bb = _bitbang(_buf_addr(self.buf), self.length * 3 * 8)
     pyb.enable_irq()