def _oil_sensor_callback(self, gpio, level, tick): if level == 1: if self._high_tick is not None: t = pigpio.tickDiff(self._high_tick, tick) if self._period is not None: self._period = (self._old * self._period) + (self._new * t) else: self._period = t self._high_tick = tick elif level == 0: if self._high_tick is not None: t = pigpio.tickDiff(self._high_tick, tick) if self._high is not None: self._high = (self._old * self._high) + (self._new * t) else: self._high = t elif level == 2: #watchdog time out self._high = pi.read(gpio) self._period = 1
def _cbf(self, gpio, level, tick): if level == 1: if self._high_tick is not None: self._p = pigpio.tickDiff(self._high_tick, tick) self._high_tick = tick elif level == 0: if self._high_tick is not None: self._hp = pigpio.tickDiff(self._high_tick, tick) if (self._p is not None) and (self._hp is not None): print("g={} f={:.1f} dc={:.1f}". format(gpio, 1000000.0/self._p, 100.0 * self._hp/self._p))
def count_rain_ticks(gpio, level, tick): '''Count the ticks from a reed switch''' global precip_tick_count global last_rising_edge logger = logging.getLogger('root') pulse = False if last_rising_edge is not None: #check tick in microseconds if pigpio.tickDiff(last_rising_edge, tick) > s.DEBOUNCE_MICROS * 1000000: pulse = True else: pulse = True if pulse: last_rising_edge = tick precip_tick_count += 1 logger.debug('Precip tick count : {tick}'.format(tick= precip_tick_count)) with open('{fd1}/data/tick_count'.format(fd1= s.SYS_FOLDER), 'w') as f: f.write('{tick_time}:{tick_count}'.format( tick_time=int(datetime.datetime.now().strftime("%s")), tick_count=int(precip_tick_count)))
def _cbf(self, gpio, level, tick): if level == 1: # Rising edge. if self._high_tick is not None and tick > self._high_tick: t = pigpio.tickDiff(self._high_tick, tick) #microseconds #print('duration = ' + str(t)) #print('min period = ' + str(self._min_period)) if(t >= self._min_period): if self._period is not None: self._period = (self._old * self._period) + (self._new * t) else: self._period = t self._high_tick = tick elif level == 2: # Watchdog timeout. if self._period is not None: if self._period < 2000000000: self._period += (self._watchdog * 1000)
def _edge_cb(self, pin, edge, tick): self._gpio.set_watchdog(self._echo_pin, 0) if edge == pigpio.TIMEOUT : _log.debug("echo timeout exceded") self._elapsed = pigpio.tickDiff(self._t0, tick) self._detection.cancel() async.call_from_thread(self.scheduler_wakeup)
def t6cbf(gpio, level, tick): global t6_count, t6_on, t6_on_tick if level == 1: t6_on_tick = tick t6_count += 1 else: if t6_on_tick is not None: t6_on += pigpio.tickDiff(t6_on_tick, tick)
def _cb(self, gpio, level, tick): if level != pigpio.TIMEOUT: if self.in_code == False: self.in_code = True self.pi.set_watchdog(self.gpio, self.code_timeout) self.hash_val = 2166136261 # FNV_BASIS_32 self.edges = 1 self.t1 = None self.t2 = None self.t3 = None self.t4 = tick else: self.edges += 1 self.t1 = self.t2 self.t2 = self.t3 self.t3 = self.t4 self.t4 = tick if self.t1 is not None: d1 = pigpio.tickDiff(self.t1,self.t2) d2 = pigpio.tickDiff(self.t3,self.t4) self._hash(d1, d2) else: if self.in_code: self.in_code = False self.pi.set_watchdog(self.gpio, 0) if self.edges > 12: self.callback(self.hash_val)
def ticks2unixUTC(tick): global RTCsecond,RTCtick,ppm tickOffset=pigpio.tickDiff(RTCtick, tick) print RTCsecond,RTCtick,tick,tickOffset bias=ppm*(tickOffset/1000000.) UTC=float(RTCsecond)+(tickOffset+bias)/1000000. #print (RTCsecond,ppm,tick,tickOffset,pllOffset,bias,UTC) return UTC
def on_echo(self, _, level, tick): if level == 2: pigpio.gpio_trigger(self.GPIO_TRIGGER) if level == 1: self.tick_up = tick elif level == 0: delta = pigpio.tickDiff(self.tick_up, tick) self.update_distance(delta * 0.017)
def either_edge_callback(self, gpio, level, tick): level_handlers = { pigpio.FALLING_EDGE: self._edge_FALL, pigpio.RISING_EDGE: self._edge_RISE, pigpio.EITHER_EDGE: self._edge_EITHER } handler = level_handlers[level] diff = pigpio.tickDiff(self.high_tick, tick) handler(tick, diff)
def _cb(self, gpio, level, tick): """ Accumulate the 40 data bits. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. """ diff = pigpio.tickDiff(self.high_tick, tick) if level == 0: # Edge length determines if bit is 1 or 0. if diff >= 50: val = 1 if diff >= 200: # Bad bit? self.CS = 256 # Force bad checksum. else: val = 0 if self.bit >= 40: # Message complete. self.bit = 40 elif self.bit >= 32: # In checksum byte. self.CS = (self.CS<<1) + val if self.bit == 39: # 40th bit received. self.pi.set_watchdog(self.gpio, 0) self.no_response = 0 total = self.hH + self.hL + self.tH + self.tL if (total & 255) == self.CS: # Is checksum ok? self.rhum = ((self.hH<<8) + self.hL) * 0.1 if self.tH & 128: # Negative temperature. mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH<<8) + self.tL) * mult self.tov = time.time() elif self.bit >=24: # in temp low byte self.tL = (self.tL<<1) + val elif self.bit >=16: # in temp high byte self.tH = (self.tH<<1) + val elif self.bit >= 8: # in humidity low byte self.hL = (self.hL<<1) + val elif self.bit >= 0: # in humidity high byte self.hH = (self.hH<<1) + val else: # header bits pass
def cbf(gpio, level, tick): global start_tick, last_tick, low_ticks, high_ticks, run if start_tick is not None: ticks = pigpio.tickDiff(last_tick, tick) last_tick = tick if level == 0: # Falling edge. high_ticks = high_ticks + ticks else: # Rising edge. low_ticks = low_ticks + ticks interval = pigpio.tickDiff(start_tick, tick) if interval >= INTERVAL: results(interval) start_tick = tick last_tick = tick low_ticks = 0 high_ticks = 0 else: start_tick = tick last_tick = tick
def _cb(self, gpio, level, tick): if self.last_tick is not None: if level == pigpio.TIMEOUT: #print "wtf why TIMEOUT?" self.pi.set_watchdog(self.rxgpio, 0) # Switch watchdog off. if self.in_message: self._insert(4, not self.last_level) self.good = 0 self.in_message = False else: edge = pigpio.tickDiff(self.last_tick, tick) if edge < self.min_mics: #print "edge too small", edge self.good = 0 self.in_message = False elif edge > self.max_mics: #print "edge too big", edge if self.in_message: self._insert(4, level) self.good = 0 self.in_message = False else: self.good += 1 if self.good > 8: bitlen = (100 * edge) / self.mics if bitlen < 140: bits = 1 elif bitlen < 240: bits = 2 elif bitlen < 340: bits = 3 else: bits = 4 self._insert(bits, level) self.last_tick = tick self.last_level = level
def discipline(gpio, level, tick): global RTCsecond,RTCtick,ppm diff=pigpio.tickDiff(RTCtick,tick) now=time.time() getPPM() #trying to avoid spurius signals #not update if there is less than 0.9999 seconds if diff <999900: print "Spuck!",diff return RTCsecond=int(round(now)) print (now,RTCsecond,RTCtick,tick,diff) RTCtick=tick
def either_edge_callback(self, gpio, level, tick): """ Either Edge callbacks, called each time the gpio edge changes. Accumulate the 40 data bits from the dht11 sensor. """ level_handlers = { pigpio.FALLING_EDGE: self._edge_FALL, pigpio.RISING_EDGE: self._edge_RISE, pigpio.EITHER_EDGE: self._edge_EITHER, } handler = level_handlers[level] diff = pigpio.tickDiff(self.high_tick, tick) handler(tick, diff)
def _cbf(self, g, l, t): """ Accumulates the code from pairs of short/long pulses. The code end is assumed when an edge greater than 5 ms is detected. """ edge_len = pigpio.tickDiff(self._last_edge_tick, t) self._last_edge_tick = t if edge_len > 5000: # 5000 us, 5 ms. if self._in_code: if self.min_bits <= self._bits <= self.max_bits: self._lbits = self._bits self._lcode = self._code self._lgap = self._gap self._lt0 = int(self._t0/self._bits) self._lt1 = int(self._t1/self._bits) self._ready = True if self.cb is not None: self.cb(self._lcode, self._lbits, self._lgap, self._lt0, self._lt1) self._in_code = True self._gap = edge_len self._edge = 0 self._bits = 0 self._code = 0 elif self._in_code: if self._edge == 0: self._e0 = edge_len elif self._edge == 1: self._calibrate(self._e0, edge_len) if self._edge % 2: # Odd edge. bit = self._test_bit(self._even_edge_len, edge_len) self._code = self._code << 1 if bit == 1: self._code += 1 elif bit != 0: self._in_code = False else: # Even edge. self._even_edge_len = edge_len self._edge += 1
def _pulse(self, gpio, level, tick): """ ISR -- sort of """ diff = pigpio.tickDiff ( self.lastTicks, tick ) self.lastTicks = tick t = ( tick, gpio, diff, self.state ) self.q.put ( t, False ) if self.state == 0 : self.state = 1 else : self.state = 0 self.pi.write ( self.ledPin, self.state )
def count(self, tick): if self.state == 0: self.startTick = tick self.lastTick = tick self.state = 1 self.nClicks = self.nClicks + 1 diff = pigpio.tickDiff ( self.lastTick, tick ) self.lastTick = tick if diff > self.quietInterval: return True else: self.duration = self.duration + diff return False
def either_edge_callback(self, gpio, level, tick): """ Either Edge callbacks, called each time the gpio edge changes. Accumulate the 40 data bits from the dht22 sensor. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. """ level_handlers = { pigpio.FALLING_EDGE: self._edge_FALL, pigpio.RISING_EDGE: self._edge_RISE, pigpio.EITHER_EDGE: self._edge_EITHER } handler = level_handlers[level] diff = pigpio.tickDiff(self.high_tick, tick) handler(tick, diff)
def t3cbf(gpio, level, tick): global t3_reset, t3_count, t3_tick, t3_on, t3_off if t3_reset: t3_count = 0 t3_on = 0.0 t3_off = 0.0 t3_reset = False else: td = pigpio.tickDiff(t3_tick, tick) if level == 0: t3_on += td else: t3_off += td t3_count += 1 t3_tick = tick
def _cbf(self, gpio, level, tick): if self._start_tick is not None: ticks = pigpio.tickDiff(self._last_tick, tick) self._last_tick = tick if level == 0: # falling edge self._high_ticks = self._high_ticks + ticks elif level == 1: # Rising edge self._low_ticks = self._low_ticks + ticks else: # timeout level, not used pass else: self._start_tick = tick self._last_tick = tick
def cbf(pin, level, tick): global start_tick global state global bits global tolerance global histogram # End of Gap if level == 1: start_tick = tick # End of Pulse elif level == 0: delta = gpio.tickDiff(start_tick, tick) # start_tick = tick # long pulse if delta in range(820 - 2 * tolerance, 820 + 2 * tolerance): bits = np.append(bits, [1]) state = 1 # short pulse elif delta in range(300 - tolerance, 300 + tolerance): bits = np.append(bits, [0]) else: pass # Watchdog timeout elif (level == 2) and (state > 0): if bits.size == 34: histogram[1] = histogram[1] + bits histogram[0] += 1 frame = np.packbits(bits) print "Frame: " + ''.join('0x{:02X} '.format(x) for x in frame) #print "Command: 0b{:08b}".format(((frame[2]&0x0f) << 4) + (frame[3]&0x0f)) else: pass bits = np.empty(0, dtype=np.uint8) state = 0 else: pass
def _rising_edge(self, gpio, level, tick): edge_len = pigpio.tickDiff(self._last_edge_tick, tick) self._last_edge_tick = tick if edge_len > 10000: self._in_code = True self._bits = -2 self._code = 0 elif self._in_code: self._bits += 1 if self._bits >= 1: self._code <<= 1 if (edge_len >= 60) and (edge_len <= 150): if edge_len > 100: # 1 bit self._code += 1 else: # invalid bit self._in_code = False if self._in_code: if self._bits == 40: self._decode_dhtxx() self._in_code = False
def _cbf(self, g, l, t): if g == self._OUT: # Frequency counter. if self._cycle == 0: self._start_tick = t else: self._last_tick = t self._cycle += 1 else: # Must be transition between colour samples. if g == self._S2: if l == 0: # Clear -> Red. self._cycle = 0 return else: # Blue -> Green. colour = 2 else: if l == 0: # Green -> Clear. colour = 1 else: # Red -> Blue. colour = 0 if self._cycle > 1: self._cycle -= 1 td = pigpio.tickDiff(self._start_tick, self._last_tick) self._hertz[colour] = (1000000 * self._cycle) / td self._tally[colour] = self._cycle else: self._hertz[colour] = 0 self._tally[colour] = 0 self._cycle = 0 # Have we a new set of RGB? if colour == 1: for i in range(3): self.hertz[i] = self._hertz[i] self.tally[i] = self._tally[i]
def cbf(self, pin, level, tick): # End of Pulse if level == 0: pass # End of Gap if level == 1: delta = gpio.tickDiff(self.start_tick, tick) self.start_tick = tick # use frame-gap after 1st frame as trigger to scan the next frames; pulse + very long gap if self.state == 0 and delta in range(self.pulse_verylong_gap_µs - self.symbol_tolerance_µs, self.pulse_verylong_gap_µs + self.symbol_tolerance_µs): self.debug("Start of frame detected", TRACE) self.state = 1 # pulse + long gap => 1 elif (self.state == 1) and delta in range(self.pulse_long_gap_µs - self.symbol_tolerance_µs, self.pulse_long_gap_µs + self.symbol_tolerance_µs): self.symbols = np.append(self.symbols, [1]) # pulse + medium gap => 0 elif (self.state == 1) and delta in range(self.pulse_medium_gap_µs - self.symbol_tolerance_µs, self.pulse_medium_gap_µs + self.symbol_tolerance_µs): self.symbols = np.append(self.symbols, [0]) elif (self.state == 1) and delta in range(self.pulse_verylong_gap_µs - self.symbol_tolerance_µs, self.pulse_verylong_gap_µs + self.symbol_tolerance_µs): self.debug("End of Frame : " + str(self.symbols.size)+ " Bits received", TRACE) if self.symbols.size == 37: self.state = 2 # all good else: self.symbols = np.empty(0, dtype=np.uint8) self.state = 0 else: pass # Watchdog timeout elif (level == 2) and (self.state > 0): self.debug("End of Transmission: " + str(self.symbols.size) + " Bits received", TRACE) if self.symbols.size == 37: self.decode() else: pass self.symbols = np.empty(0, dtype=np.uint8) self.state = 0 else: pass
def get_distance_cms(): # (7) """ Get distance in centimeters """ trigger() timeout = time() + TIMEOUT_SECS # (8) while not reading_success: if time() > timeout: return SENSOR_TIMEOUT sleep(0.01) # Elapsed time in microseconds. Divide by 2 to get time from sensor to object. elapsed_microseconds = pigpio.tickDiff(tick_start, tick_end) / 2 # (9) # Convert to seconds elapsed_seconds = elapsed_microseconds / 1000000 # Calculate distance in meters (d = v * t) distance_in_meters = elapsed_seconds * VELOCITY # (10) # Convert to centimeters distance_in_centimeters = distance_in_meters * 100 return distance_in_centimeters
def cbf(self, gpio, level, tick): #change to low (a falling edge) if level == 0: #if first edge is a falling one the following code will fail #a try first time is faster than an if-statement every time try: #http://abyz.me.uk/rpi/pigpio/python.html#callback # tick 32 bit The number of microseconds since boot # WARNING: this wraps around from # 4294967295 to 0 roughly every 72 minutes #Tested: This is handled by the tickDiff function internally, if t1 (earlier tick) #is smaller than t2 (later tick), which could happen every 72 min. The result will #not be a negative value, the real difference will be properly calculated. self.duty_cycle = self.duty_scale*pigpio.tickDiff(t1=self.tick_high, t2=tick)/self.period except Exception: pass #change to high (a rising edge) elif level == 1: self.tick_high = tick
def Throttle(gpio, level, tick): global last_tick_T, diff_T, diffT, diffS, diffA if last_tick_T is not None: diff_T = pigpio.tickDiff(last_tick_T, tick) if diff_T < 3000 and diff_S < 3000 and diff_A < 3000: diffT = diff_T diffS = diff_S diffA = diff_A if 1900 < diffA < 2100: cv.stop(diffA) if 1400 < diffA < 1600: cv.Throttle(diffT, diffS, diffA) if 900 < diffA < 1000: cv.automatico(diffA) #if 900 < diffA < 1000: # cv.AX1(diffA) # update the tick last_tick_T = tick
def cbf(gpio, level, tick): global last_tick, in_code, code, fetching_code, pi if level == pigpio.TIMEOUT: pi.set_watchdog(GPIO, 0) # Cancel watchdog. if in_code: in_code = False IR.end_of_code() return edge = pigpio.tickDiff(last_tick, tick) last_tick = tick if fetching_code: if (edge > PRE_US) and (not in_code): # Start of a code. in_code = True pi.set_watchdog(GPIO, POST_MS) # Start watchdog. elif (edge > POST_US) and in_code: # End of a code. in_code = False pi.set_watchdog(GPIO, 0) # Cancel watchdog. IR.end_of_code() elif in_code: code.append(edge)
def count_rain_ticks(gpio, level, tick): '''Count the ticks from a reed switch''' global precip_tick_count global last_rising_edge logger = logging.getLogger('root') pulse = False if last_rising_edge is not None: #check tick in microseconds if pigpio.tickDiff(last_rising_edge, tick) > s.DEBOUNCE_MICROS * 1000000: pulse = True else: pulse = True if pulse: last_rising_edge = tick precip_tick_count += 1 logger.debug('Precip tick count : {tick}'.format(tick= precip_tick_count))
def _cbf(self, gpio, level, tick): if level == 1: if debug: self._log("callback level 1 {t:d} {s:d} cnt {c:d}".format( t=tick, s=self.state, c=self.cnt)) self.state = 1 self._high_tick = tick elif level == 0: if debug: self._log("callback level 0 {t:d} {s:d} cnt {c:d}".format( t=tick, s=self.state, c=self.cnt)) if self._high_tick is not None: t = pigpio.tickDiff(self._high_tick, tick) if debug: self._log( "callback calc time = {t:d} {s:d} cnt {c:d}".format( t=t, s=self.state, c=self.cnt)) self.t = t self._log("set state to 2 cnt {c:d}".format(c=self.cnt)) self.state = 2
def _cbf(self, gpio, level, tick): if level == 1: # Rising edge. if self._high_tick is not None and tick > self._high_tick: t = pigpio.tickDiff(self._high_tick, tick) #microseconds #print('duration = ' + str(t)) #print('min period = ' + str(self._min_period)) if (t >= self._min_period): if self._period is not None: self._period = (self._old * self._period) + (self._new * t) else: self._period = t self._high_tick = tick elif level == 2: # Watchdog timeout. if self._period is not None: if self._period < 2000000000: self._period += (self._watchdog * 1000)
def cbf(self, gpio, level, tick): #change to low (falling edge) if level == 0: self.tick_low = tick #try is needed because one of t1 or t2 might be None and then tickDiff fails try: #http://abyz.me.uk/rpi/pigpio/python.html#callback # tick 32 bit The number of microseconds since boot # WARNING: this wraps around from # 4294967295 to 0 roughly every 72 minutes #Tested: This is handled by the tickDiff function internally, if t1 (earlier tick) #is smaller than t2 (later tick), which could happen every 72 min. The result will #not be a negative value, the real difference will be properly calculated. self.pulse_width = pigpio.tickDiff(t1=self.tick_high, t2=self.tick_low) except Exception: pass #change to high (rising edge) elif level == 1: self.tick_high = tick
def cbf(self, pin, level, tick): # End of Pulse if level == 0: pass # End of Gap if level == 1: delta = gpio.tickDiff(self.start_tick, tick) self.start_tick = tick # use frame-gap after 1st frame as trigger to scan the next frames; pulse + very long gap if self.state == 0 and delta in range( 4500 - 4 * self.symbol_tolerance_µs, 4500 + 4 * self.symbol_tolerance_µs): self.state = 1 # pulse + long gap elif (self.state == 1) and delta in range( 2500 - 2 * self.symbol_tolerance_µs, 2500 + 2 * self.symbol_tolerance_µs): self.symbols = np.append(self.symbols, [1]) # pulse + short gap elif (self.state == 1) and delta in range( 1500 - 2 * self.symbol_tolerance_µs, 1500 + 2 * self.symbol_tolerance_µs): self.symbols = np.append(self.symbols, [0]) else: pass # Watchdog timeout elif (level == 2) and (self.state > 0): if self.symbols.size == 36: self.decode() else: pass self.symbols = np.empty(0, dtype=np.uint8) self.state = 0 else: pass
def callback(gpio, level, tick): nonlocal fetching_code, ir_signal_list, in_code, last_tick if level != pigpio.TIMEOUT: edge = pigpio.tickDiff(last_tick, tick) last_tick = tick if fetching_code == True: if (edge > pre_duration) and ( not in_code): # Start of a code. in_code = True pi.set_watchdog(gpio, post_duration) # Start watchdog. elif (edge > post_duration) and in_code: # End of a code. in_code = False pi.set_watchdog(gpio, 0) # Cancel watchdog. # Finish if len(ir_signal_list) > length_threshold: fetching_code = False else: ir_signal_list = [] print( "Received IR command is too short, please try again" ) elif in_code: ir_signal_list.append(edge) else: pi.set_watchdog(gpio, 0) # Cancel watchdog. if in_code: in_code = False # Finish if len(ir_signal_list) > length_threshold: fetching_code = False else: ir_signal_list = [] print( "Received IR command is too short, please try again" )
def _cbf(self, g, l, t): edge_len = pigpio.tickDiff(self._last_edge_tick, t) self._last_edge_tick = t if edge_len > 5000: if self._in_code: if self.min_bits <= self._bits <= self.max_bits: self._lbits = self._bits self._lcode = self._code self._lgap = self._gap self._lt_0 = int(self._t_0 / self._bits) self._lt_1 = int(self._t_1 / self._bits) self._ready = True if self.cb is not None: self.cb(int(bin(self._lcode)[2::2], 2), int(self._lbits / 2), self._lgap, self._lt_0, self._lt_1) self._in_code = True self._gap = edge_len self._edge = 0 self._bits = 0 self._code = 0 elif self._in_code: if self._edge == 0: self._e0 = edge_len elif self._edge == 1: self._calibrate(self._e0, edge_len) if self._edge % 2: bit = self._test_bit(self._even_edge_len, edge_len) self._code = self._code << 1 if bit == 1: self._code += 1 elif bit != 0: self._in_code = False else: self._even_edge_len = edge_len self._edge += 1
def cbf(pin, level, tick): global start_tick global state global bits if level == 1: start_tick = tick elif level == 0: delta = gpio.tickDiff(start_tick, tick) if (state == 0) and (delta > 5300) and (delta < 5700): bits = np.empty(0, dtype=np.uint8) state = 1 elif (state == 1) and (delta < 500): bits = np.append(bits, [0]) elif (state == 1) and (delta > 500) and (delta < 1000): bits = np.append(bits, [1]) elif state == 1: # print if bits.size >= 32: print "Rx: "+''.join('0x{:02X} '.format(x) for x in np.packbits(bits)[:4]) state = 0 else: pass else: pass
def terminate(self): self._cb.cancel() self._duration = pigpio.tickDiff(self._startTick, self._endTick)
def cbf(pin, level, tick): global start_tick global state global bits global hw_sync global clock global histogram # End of Gap if level == 1: delta = gpio.tickDiff(start_tick, tick) start_tick = tick # HW-Sync if (0 <= state <= 2) and (delta in range(2500 - 2 * tolerance, 2500 + 2 * tolerance)): if state < 2: hw_sync = np.empty(0) hw_sync = np.append(hw_sync, [delta]) state = 2 # long gap elif (state == 3) and (delta in range(2 * clock - tolerance, 2 * clock + tolerance)): bits = np.append(bits, [0, 0]) # short gap elif (state == 3) and (delta in range(clock - tolerance, clock + tolerance)): bits = np.append(bits, [0]) else: pass # End of Pulse elif level == 0: delta = gpio.tickDiff(start_tick, tick) start_tick = tick # wake-up pulse if (state == 0) and (delta in range(10050 - tolerance, 10050 + tolerance)): state = 1 # HW-Sync elif (0 <= state <= 2) and (delta in range(2500 - 2 * tolerance, 2500 + 2 * tolerance)): if state < 2: hw_sync = np.empty(0) hw_sync = np.append(hw_sync, [delta]) state = 2 # start of frame mark elif (state == 2) and (delta in range(4850 - 2 * tolerance, 4850 + 2 * tolerance)): clock = int(np.average(hw_sync) / 4) print "Clock Sync:", hw_sync, clock bits = np.empty(0, dtype=np.uint8) state = 3 # long pulse elif (state == 3) and (delta in range(2 * clock - tolerance, 2 * clock + tolerance)): bits = np.append(bits, [1, 1]) # short pulse elif (state == 3) and (delta in range(clock - tolerance, clock + tolerance)): bits = np.append(bits, [1]) else: pass # Watchdog timeout elif (level == 2) and (state > 0): # skip first bit, because it is part of the start of frame mark bits = bits[1::] # append one zero-bit, in case the last bit was a one and the last zero-bit can't be detected, because the frame is over if bits.size < 112: bits = np.append(bits, [0]) if bits.size == 112: # decode manchester (rising edge = 1, falling edge = 0) decoded = np.ravel( np.where(np.reshape(bits, (-1, 2)) == [0, 1], 1, 0))[::2] histogram[1] = histogram[1] + decoded histogram[0] += 1 frame = np.packbits(decoded) print "Raw: " + ''.join('0x{:02X} '.format(x) for x in frame) for i in range(frame.size - 1, 0, -1): frame[i] = frame[i] ^ frame[i - 1] cksum = frame[0] ^ (frame[0] >> 4) for i in range(1, 7): cksum = cksum ^ frame[i] ^ (frame[i] >> 4) cksum = cksum & 0x0f print "Frame: " + ''.join('0x{:02X} '.format(x) for x in frame) print " Control: 0x{:02X}".format((frame[1] >> 4) & 0x0f) print " Checksum: {}".format("ok" if cksum == 0 else "error") print " Address: " + ''.join('{:02X} '.format(x) for x in frame[4:7]) print " Rolling Code: " + ''.join('{:02X} '.format(x) for x in frame[2:4]) else: pass bits = np.empty(0, dtype=np.uint8) state = 0 else: pass
def _callback(self, gpio, level, tick): # Calculate tick difference diff = pigpio.tickDiff(self.high_tick, tick) # Determine if bit 1 or 0 if level == 0: if diff >= 50: val = 1 if diff >= 200: # Something is wrong self.checksum = 256 else: val = 0 if self.bit >= 40: # Data accept finished self.bit = 40 elif self.bit >= 32: # Save checksum byte self.checksum = (self.checksum << 1) + val if self.bit == 39: # 40th bit received. self.pi.set_watchdog(self.gpio, 0) bitsum = self.hIntegral + self.hDecimal + self.tIntegral + self.tDecimal if (bitsum & 255) == self.checksum: # Correct checksum self.humidity = (self.hIntegral) self.temperature = (self.tIntegral) elif self.bit >= 24: # Save temperature decimal data self.tDecimal = (self.tDecimal << 1) + val elif self.bit >= 16: # Save temperature integral data self.tIntegral = (self.tIntegral << 1) + val elif self.bit >= 8: # Save humidity decimal data self.hDecimal = (self.hDecimal << 1) + val elif self.bit >= 0: # Save humidity integral data self.hIntegral = (self.hIntegral << 1) + val self.bit += 1 elif level == 1: self.high_tick = tick # Reset if diff > 250000: self.bit = -2 self.hIntegral = 0 self.hDecimal = 0 self.tIntegral = 0 self.tDecimal = 0 self.checksum = 0 else: # Fatal self.pi.set_watchdog(self.gpio, 0)
def _cb(self, gpio, level, tick): if level != pigpio.TIMEOUT: # Get microseconds since last change pulse = tick - self.lastTick self.lastTick = tick if pulse < 150: #very short pulse so ignore it return elif self.state == RX_STATE_IDLE and pulse <= 5000: #quick check to see worth proceeding return elif pulse < 500: #normal short pulse trans = level + 2 elif pulse < 2000: #normal long pulse trans = level + 4 elif pulse > 5000: # gap between messages trans = level + 6 else: trans = 8 #State machine using nested ifs if self.state == RX_STATE_IDLE: if trans == 7: # 1 after a message gap self.state = RX_STATE_MSGSTARTFOUND self.duplicate = True elif self.state == RX_STATE_MSGSTARTFOUND: if trans == 2: # nothing to do wait for next 1 trans = trans elif trans == 3: # start of a byte detected self.byte = 0 self.state = RX_STATE_BYTESTARTFOUND else: self.state = RX_STATE_IDLE elif self.state == RX_STATE_BYTESTARTFOUND: if trans == 2: # nothing to do wait for next 1 trans = trans elif trans == 3: # 1 160->500 self.data = 0 self.bit = 0 self.state = RX_STATE_GETBYTE elif trans == 5: # 0 500->1500 starts with a 0 so enter it self.data = 0 self.bit = 1 self.state = RX_STATE_GETBYTE else: self.state = RX_STATE_IDLE elif self.state == RX_STATE_GETBYTE: if trans == 2: # nothing to do wait for next 1 trans = trans elif trans == 3: # 1 160->500 self.data = self.data << 1 | 1 self.bit +=1 elif trans == 5: # 500 - 1500 a 1 followed by a 0 self.data = self.data << 2 | 2 self.bit +=2 else: self.state = RX_STATE_IDLE # Check if byte complete if self.bit >= 8: # Translate symbols to nibbles and enter message self.data = _sym2nibble(self.data) if self.data != self.message[self.byte]: # Is it same as last packet self.duplicate = False self.repeatCount = 0 self.message[self.byte] = self.data self.byte +=1 self.bit = 0 if self.byte >= MESSAGE_BYTES: # Is packet complete if pigpio.tickDiff(self.messageTick, self.lastTick) > RX_MSG_TIMEOUT or self.messageTick == 0: # Long time since last message so reset the counter self.repeatCount = 0 elif self.duplicate: self.repeatCount +=1 if self.repeat == 0 or self.repeatCount == self.repeat: self.messages.append(self.message[0:MESSAGE_BYTES]) self.state = RX_STATE_IDLE self.messageTick = self.messageTick else: self.state = RX_STATE_BYTESTARTFOUND else: self.pi.set_watchdog(self.rxgpio, 0) # Switch watchdog off.
def __cb(self, pin, level, tick): """ Accumulate the 40 data bits. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. @param pin: the pin used to read data @type pin: int8 @param level: the level @type level: int8 @param tick: Tick used to diff @type tick: int8 """ diff = pigpio.tickDiff(self.high_tick, tick) if level == 0: # Edge length determines if bit is 1 or 0. if (diff >= 50): val = 1 if (diff >= 200): # Bad bit? self.CS = 256 # Force bad checksum. else: val = 0 if (self.bit >= 40): # Message complete. self.bit = 40 elif (self.bit >= 32): # In checksum byte. self.CS = (self.CS << 1) + val if (self.bit == 39): # 40th bit received. self.pi.set_watchdog(self.__pin, 0) self.no_response = 0 total = self.hH + self.hL + self.tH + self.tL if ((total & 255) == self.CS): # Is checksum ok? self.rhum = ((self.hH << 8) + self.hL) * 0.1 if (self.tH & 128): # Negative temperature. mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH << 8) + self.tL) * mult self.tov = time.time() else: self.bad_CS += 1 elif (self.bit >= 24): # in temp low byte self.tL = (self.tL << 1) + val elif (self.bit >= 16): # in temp high byte self.tH = (self.tH << 1) + val elif (self.bit >= 8): # in humidity low byte self.hL = (self.hL << 1) + val elif (self.bit >= 0): # in humidity high byte self.hH = (self.hH << 1) + val else: # header bits pass self.bit += 1 elif (level == 1): self.high_tick = tick if (diff > 250000): self.bit = -2 self.hH = 0 self.hL = 0 self.tH = 0 self.tL = 0 self.CS = 0 else: # level == pigpio.TIMEOUT: self.pi.set_watchdog(self.__pin, 0) if (self.bit < 8): # Too few data bits received. self.bad_MM += 1 # Bump missing message count. self.no_response += 1 if (self.no_response > self.MAX_NO_RESPONSE): self.no_response = 0 self.bad_SR += 1 # Bump sensor reset count. elif (self.bit < 39): # Short message receieved. self.bad_SM += 1 # Bump short message count. self.no_response = 0 else: # Full message received. self.no_response = 0
def _cb(self, gpio, level, tick): if level <> pigpio.TIMEOUT: # Get microseconds since last change pulse = tick - self.lastTick self.lastTick = tick if pulse < 150: #very short pulse so ignore it return elif self.state == RX_STATE_IDLE and pulse <= 5000: #quick check to see worth proceeding return elif pulse < 500: #normal short pulse trans = level + 2 elif pulse < 2000: #normal long pulse trans = level + 4 elif pulse > 5000: # gap between messages trans = level + 6 else: trans = 8 #State machine using nested ifs if self.state == RX_STATE_IDLE: if trans == 7: # 1 after a message gap self.state = RX_STATE_MSGSTARTFOUND self.duplicate = True elif self.state == RX_STATE_MSGSTARTFOUND: if trans == 2: # nothing to do wait for next 1 trans = trans elif trans == 3: # start of a byte detected self.byte = 0 self.state = RX_STATE_BYTESTARTFOUND else: self.state = RX_STATE_IDLE elif self.state == RX_STATE_BYTESTARTFOUND: if trans == 2: # nothing to do wait for next 1 trans = trans elif trans == 3: # 1 160->500 self.data = 0 self.bit = 0 self.state = RX_STATE_GETBYTE elif trans == 5: # 0 500->1500 starts with a 0 so enter it self.data = 0 self.bit = 1 self.state = RX_STATE_GETBYTE else: self.state = RX_STATE_IDLE elif self.state == RX_STATE_GETBYTE: if trans == 2: # nothing to do wait for next 1 trans = trans elif trans == 3: # 1 160->500 self.data = self.data << 1 | 1 self.bit +=1 elif trans == 5: # 500 - 1500 a 1 followed by a 0 self.data = self.data << 2 | 2 self.bit +=2 else: self.state = RX_STATE_IDLE # Check if byte complete if self.bit >= 8: # Translate symbols to nibbles and enter message self.data = _sym2nibble(self.data) if self.data <> self.message[self.byte]: # Is it same as last packet self.duplicate = False self.repeatCount = 0 self.message[self.byte] = self.data self.byte +=1 self.bit = 0 if self.byte >= MESSAGE_BYTES: # Is packet complete if pigpio.tickDiff(self.messageTick, self.lastTick) > RX_MSG_TIMEOUT or self.messageTick == 0: # Long time since last message so reset the counter self.repeatCount = 0 elif self.duplicate: self.repeatCount +=1 if self.repeat == 0 or self.repeatCount == self.repeat: self.messages.append(self.message[0:MESSAGE_BYTES]) self.state = RX_STATE_IDLE self.messageTick = self.messageTick else: self.state = RX_STATE_BYTESTARTFOUND else: self.pi.set_watchdog(self.rxgpio, 0) # Switch watchdog off.
def _cb(self, gpio, level, tick): """ Accumulate the 40 data bits. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. """ diff = pigpio.tickDiff(self.high_tick, tick) if level == 0: # Edge length determines if bit is 1 or 0. if diff >= 50: val = 1 if diff >= 200: # Bad bit? self.CS = 256 # Force bad checksum. else: val = 0 if self.bit >= 40: # Message complete. self.bit = 40 elif self.bit >= 32: # In checksum byte. self.CS = (self.CS<<1) + val if self.bit == 39: # 40th bit received. self.pi.set_watchdog(self.gpio, 0) self.no_response = 0 total = self.hH + self.hL + self.tH + self.tL if (total & 255) == self.CS: # Is checksum ok? self.rhum = ((self.hH<<8) + self.hL) * 0.1 if self.tH & 128: # Negative temperature. mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH<<8) + self.tL) * mult self.tov = time.time() if self.LED is not None: self.pi.write(self.LED, 0) else: self.bad_CS += 1 elif self.bit >=24: # in temp low byte self.tL = (self.tL<<1) + val elif self.bit >=16: # in temp high byte self.tH = (self.tH<<1) + val elif self.bit >= 8: # in humidity low byte self.hL = (self.hL<<1) + val elif self.bit >= 0: # in humidity high byte self.hH = (self.hH<<1) + val else: # header bits pass self.bit += 1 elif level == 1: self.high_tick = tick if diff > 250000: self.bit = -2 self.hH = 0 self.hL = 0 self.tH = 0 self.tL = 0 self.CS = 0 else: # level == pigpio.TIMEOUT: self.pi.set_watchdog(self.gpio, 0) if self.bit < 8: # Too few data bits received. self.bad_MM += 1 # Bump missing message count. self.no_response += 1 if self.no_response > self.MAX_NO_RESPONSE: self.no_response = 0 self.bad_SR += 1 # Bump sensor reset count. if self.power is not None: self.powered = False self.pi.write(self.power, 0) time.sleep(2) self.pi.write(self.power, 1) time.sleep(2) self.powered = True elif self.bit < 39: # Short message receieved. self.bad_SM += 1 # Bump short message count. self.no_response = 0 else: # Full message received. self.no_response = 0
#!/usr/bin/python import pigpio import time if __name__ == '__main__': pi=pigpio.pi("cronostamper") pi.set_mode(12, pigpio.OUTPUT) pi.hardware_PWM(12,1,500000) for i in range(1,2000): t1 = pi.get_current_tick() pi.hardware_PWM(12,i*1,500000) pi.get_PWM_dutycycle(12) t2 = pi.get_current_tick() print i,pigpio.tickDiff(t1,t2) time.sleep(0.00050) print pi.get_hardware_revision()
def _cb(self, gpio, level, tick): diff = pigpio.tickDiff(self.high_tick, tick) if level == 0: if diff >= 50: val = 1 if diff >= 200: self.CS = 256 else: val = 0 if self.bit >= 40: self.bit = 40 elif self.bit >= 32: self.CS = (self.CS<<1) + val if self.bit == 39: self.pi.set_watchdog(self.gpio, 0) self.no_response = 0 total = self.hH + self.hL + self.tH + self.tL if (total & 255) == self.CS: self.rhum = ((self.hH<<8) + self.hL) * 0.1 if self.tH & 128: mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH<<8) + self.tL) * mult self.tov = time.time() if self.LED is not None: self.pi.write(self.LED, 0) else: self.bad_CS += 1 elif self.bit >=24: self.tL = (self.tL<<1) + val elif self.bit >=16: self.tH = (self.tH<<1) + val elif self.bit >= 8: self.hL = (self.hL<<1) + val elif self.bit >= 0: self.hH = (self.hH<<1) + val else: pass self.bit += 1 elif level == 1: self.high_tick = tick if diff > 250000: self.bit = -2 self.hH = 0 self.hL = 0 self.tH = 0 self.tL = 0 self.CS = 0 else: self.pi.set_watchdog(self.gpio, 0) if self.bit < 8: self.bad_MM += 1 self.no_response += 1 if self.no_response > self.MAX_NO_RESPONSE: self.no_response = 0 self.bad_SR += 1 if self.power is not None: self.powered = False self.pi.write(self.power, 0) time.sleep(2) self.pi.write(self.power, 1) time.sleep(2) self.powered = True elif self.bit < 39: self.bad_SM += 1 self.no_response = 0 else: self.no_response = 0
def Steering(gpio, level, tick): global last_tick_S, diff_S if last_tick_S is not None: diff_S = pigpio.tickDiff(last_tick_S, tick) last_tick_S = tick
def imu_fth_isr(gpio, level, tick): """Interrupt service routine for FIFO threshold interrupt Args: gpio: The GPIO that changed state level: State that the GPIO changed to. Low: 0, high: 1, no change: 2. tick: Number of microseconds since boot (max 2^32 - 1, then wraps back to 0) """ isr_time = time.time() # Sometimes INT1 can trigger again as the FIFO is being read and filled # back up at the same time. If the time since the last tick is less than # 0.1s then exit the ISR. global last_tick MIN_TICK_DIFF_US = 10**5 tick_diff = pigpio.tickDiff(last_tick, tick) print(f"Time since last tick {tick_diff / 10**6} seconds") if tick_diff < MIN_TICK_DIFF_US: return global fifo_start print(f"Interrupt at {isr_time}") print(f"FIFO fill time: {isr_time - fifo_start:4.03f} seconds") fifo_start = isr_time # Read FIFO status status1 = imu._fifo_status1 status2 = imu._fifo_status2 status3 = imu._fifo_status3 status4 = imu._fifo_status4 # Number of unread words (16 bits) unread_words = ((status2 & 0x0F) << 8) + status1 print(f"Words in FIFO: {unread_words}") # Pattern index # In our case, the accelerometer and gyroscope data rates are equal, so the # pattern is in [0:5] where # 0 -> Gx # 1 -> Gy # 2 -> Gz # 3 -> Ax # 4 -> Ay # 5 -> Az pattern_index = (status4 << 8) + status3 print(f"Index of next reading: {pattern_index}") # Read in multiples of 6, the number of readings from Gx to Az BYTES_PER_WORD = 2 WORDS_PER_PATTERN = 6 words_to_read = unread_words // WORDS_PER_PATTERN * WORDS_PER_PATTERN buffer_size = words_to_read * BYTES_PER_WORD buffer = bytearray(buffer_size) FIFO_DATA_OUT_L = bytearray(b'\x3E') # Read FIFO data into buffer start_time = time.time() imu.i2c_device.write_then_readinto(FIFO_DATA_OUT_L, buffer) end_time = time.time() total_read_time = end_time - start_time print( f"{buffer_size} bytes read in {total_read_time:.6f} seconds. {buffer_size/total_read_time:.0f} bytes/s" ) # Read FIFO status status1 = imu._fifo_status1 status2 = imu._fifo_status2 status3 = imu._fifo_status3 status4 = imu._fifo_status4 unread_words = ((status2 & 0x0F) << 8) + status1 print(f"Words in FIFO: {unread_words}") pattern_index = (status4 << 8) + status3 print(f"Index of next reading: {pattern_index}") last_tick = tick # Print data PREVIEW_BYTES = 12 print( f"buffer = {buffer[:PREVIEW_BYTES].hex()} ... {buffer[-PREVIEW_BYTES:].hex()} | Len: {len(buffer)}" ) data = [parse_fifo_data(buffer[i:i + 2]) for i in range(0, len(buffer), 2)] print( f"data = [{', '.join(map(str, data[:PREVIEW_BYTES]))}, ..., {', '.join(map(str, data[-PREVIEW_BYTES:]))}] | Len: {len(data)}" ) print()
def cbf(GPIO, level, tick): if last[GPIO] is not None: diff = pigpio.tickDiff(last[GPIO], tick) print("G={} l={} d={}".format(GPIO, level, diff)) last[GPIO] = tick
def __gpio_callback(self, gpio, level, tick): if level == pigpio.LOW: if self.__last_high_tick is not None: high_ticks = pigpio.tickDiff(self.__last_high_tick, tick) if high_ticks > 1000: # packet start # print('====> PACKET START') self.__pass_any_packet_to_callback(self.STATUS_OK) self.__received_bytes = [0] self.__parity = 0 self.__bit_count = 0 self.__bit_ticks = None elif self.__received_bytes is not None and high_ticks > 150: # next byte in packet # print('====> NEXT BYTE START') if self.__bit_count == 9: self.__received_bytes.append(0) self.__bit_ticks = None self.__bit_count = 0 self.__parity = 0 else: self.__pass_any_packet_to_callback(self.STATUS_BIT_COUNT_ERROR) self.__reset_packet() self.__last_low_tick = tick elif level == pigpio.HIGH: if self.__last_low_tick is not None: low_ticks = pigpio.tickDiff(self.__last_low_tick, tick) # print('{0} @ {1} -> {2}: {3}'.format(gpio, tick, level, low_ticks)) if self.__received_bytes is not None: if self.__bit_ticks is None: # calibration T-strobe at begin of byte self.__bit_ticks = low_ticks else: # a 0-bit has a short high interval, 1-bit a long high interval bit = 0 if low_ticks > self.__bit_ticks else 1 if self.__bit_count < 8: # data bit received self.__received_bytes[-1] = self.__received_bytes[-1] * 2 + bit self.__bit_count += 1 self.__parity += bit if self.__bit_count == 9: self.__check_parity() self.pi.set_watchdog(self.gpio, 1) # 1 ms elif self.__bit_count > 9: # more bits than expected (8 bits + 1 __parity) self.__pass_any_packet_to_callback(self.STATUS_BIT_COUNT_ERROR) self.__reset_packet() self.__last_high_tick = tick elif level == pigpio.TIMEOUT: self.__pass_any_packet_to_callback(self.STATUS_OK) self.__reset_packet()
def _cb(self, gpio, level, tick): """ Accumulate the 40 data bits. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. """ if self.accumulating: if level == 0: diff = pigpio.tickDiff(self.tick, tick) # edge length determines if bit is 1 or 0 if diff >= 50: val = 1 else: val = 0 if self.bit >= 32: # in checksum byte self.CS = (self.CS<<1) + val if self.bit >= 39: # 40 bits received self.accumulating = False pigpio.set_watchdog(self.gpio, 0) total = self.hH + self.hL + self.tH + self.tL if (total & 255) == self.CS: # is checksum ok self.rhum = ((self.hH<<8) + self.hL) * 0.1 if self.tH & 128: # negative temperature mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH<<8) + self.tL) * mult self.tov = time.time() else: self.bad_CS += 1 elif self.bit >=24: # in temp low byte self.tL = (self.tL<<1) + val elif self.bit >=16: # in temp high byte self.tH = (self.tH<<1) + val elif self.bit >= 8: # in humidity low byte self.hL = (self.hL<<1) + val elif self.bit >= 0: # in humidity high byte self.hH = (self.hH<<1) + val else: # header bits pass self.bit += 1 elif level == 1: self.tick = tick if self.bit == -3: # correct for first reading self.bit = -2 else: # level == pigpio.TIMEOUT: # time out if less than 40 bits received self.accumulating = False pigpio.set_watchdog(self.gpio, 0) self.bad_TO += 1 else: # perhaps a repeated watchdog if level == pigpio.TIMEOUT: pigpio.set_watchdog(self.gpio, 0)
def _cb(self, gpio, level, tick): """ Accumulate the 40 data bits. Format into 5 bytes, humidity high, humidity low, temperature high, temperature low, checksum. """ diff = pigpio.tickDiff(self.high_tick, tick) if level == 0: # Edge length determines if bit is 1 or 0. if diff >= 50: val = 1 if diff >= 200: # Bad bit? self.CS = 256 # Force bad checksum. else: val = 0 if self.bit >= 40: # Message complete. self.bit = 40 elif self.bit >= 32: # In checksum byte. self.CS = (self.CS << 1) + val if self.bit == 39: # 40th bit received. self.pi.set_watchdog(self.gpio, 0) self.no_response = 0 total = self.hH + self.hL + self.tH + self.tL if (total & 255) == self.CS: # Is checksum ok? self.rhum = ((self.hH << 8) + self.hL) * 0.1 if self.tH & 128: # Negative temperature. mult = -0.1 self.tH = self.tH & 127 else: mult = 0.1 self.temp = ((self.tH << 8) + self.tL) * mult self.tov = time.time() if self.LED is not None: self.pi.write(self.LED, 0) else: self.bad_CS += 1 elif self.bit >= 24: # in temp low byte self.tL = (self.tL << 1) + val elif self.bit >= 16: # in temp high byte self.tH = (self.tH << 1) + val elif self.bit >= 8: # in humidity low byte self.hL = (self.hL << 1) + val elif self.bit >= 0: # in humidity high byte self.hH = (self.hH << 1) + val else: # header bits pass self.bit += 1 elif level == 1: self.high_tick = tick if diff > 250000: self.bit = -2 self.hH = 0 self.hL = 0 self.tH = 0 self.tL = 0 self.CS = 0 else: # level == pigpio.TIMEOUT: self.pi.set_watchdog(self.gpio, 0) if self.bit < 8: # Too few data bits received. self.bad_MM += 1 # Bump missing message count. self.no_response += 1 if self.no_response > self.MAX_NO_RESPONSE: self.no_response = 0 self.bad_SR += 1 # Bump sensor reset count. if self.power is not None: self.powered = False self.pi.write(self.power, 0) time.sleep(2) self.pi.write(self.power, 1) time.sleep(2) self.powered = True elif self.bit < 39: # Short message receieved. self.bad_SM += 1 # Bump short message count. self.no_response = 0 else: # Full message received. self.no_response = 0
def _cbf(self, gpio, level, tick): if level == 1: # Rising edge. if self.tick_t0 is not None: t = pigpio.tickDiff(self.tick_t0, tick) self.addPeriod(t) self.tick_t0 = tick
def AX1(gpio, level, tick): global last_tick_A, diff_A, diffA if last_tick_A is not None: diff_A = pigpio.tickDiff(last_tick_A, tick) last_tick_A = tick
import pigpio import time import numpy as np import sys # define output pin pi = pigpio.pi() pin_out = 13 pi.set_mode(pin_out, pigpio.OUTPUT) # get initial time # time_i = time.perf_counter() tick_i = pi.get_current_tick() # set target pulsewidth target_pw = int(sys.argv[1]) # this_pw = pi.get_servo_pulsewidth(pin_out) # print("Current pulsewidth: ",this_pw) pi.set_servo_pulsewidth(pin_out, target_pw) print("Target pulsewidth: ", target_pw) # get final time # time_f = time.perf_counter() tick_f = pi.get_current_tick() # print("\nTime elapsed: ",time_f-time_i," s") print("\nTime elapsed: ", pigpio.tickDiff(tick_i, tick_f), " ms") # 1-second delay time.sleep(1)