コード例 #1
0
 def awaitReset(self):
     try:
         try:
             machine.time_pulse_us(self.pin, 1)
         except:
             self.err = 'Not Connected'
             return False
         t = machine.time_pulse_us(self.pin, 0)
         if t < 480:
             self.err = 'Very short reset ' + str(t) + 'us'
             return False
     except:
         self.err = 'Very long reset'
         return False
     self.pin.init(self.pin.OUT_OD)
     self.pin.low()
     time.sleep_us(60)
     # let it float
     self.pin.init(self.pin.IN, self.pin.PULL_NONE)
     time.sleep_us(5)
     if self.pin.value() == 0:
             self.err = 'No presence response from door'
             return False
     else:
             return True
コード例 #2
0
def median_of_n(p, n, timeout, verbose=False):
    # Return the median of n frequency measurements
    # on pin p, using time_pulse_us with timeout
    set = []
    for i in range(n):
        try:
            v0 = time_pulse_us(p, 1, timeout)
            if v0 < 0:
                return timeout, False
            v1 = time_pulse_us(p, 1, timeout)
            if v1 < 0:
                return timeout, False
            v2 = time_pulse_us(p, 0, timeout)
            if v2 < 0:
                return timeout, False
            v3 = time_pulse_us(p, 0, timeout)
            if v3 < 0:
                return timeout, False
            set.append(v1 + v3)
        except Exception as ex:
            print('exception =', ex, ' on sample ', i)
    set.sort()
    if verbose:
        print(set[n // 2], set)
    return set[n // 2], True
コード例 #3
0
 def awaitReset(self):
     try:
         try:
             machine.time_pulse_us(self.pin, 1)
         except:
             self.err = 'Not Connected'
             return False
         t = machine.time_pulse_us(self.pin, 0)
         if t < 480:
             self.err = 'Very short reset ' + str(t) + 'us'
             return False
     except:
         self.err = 'Very long reset'
         return False
     self.pin.init(self.pin.OUT_OD)
     self.pin.low()
     time.sleep_us(60)
     # let it float
     self.pin.init(self.pin.IN, self.pin.PULL_NONE)
     time.sleep_us(5)
     if self.pin.value() == 0:
         self.err = 'No presence response from door'
         return False
     else:
         return True
コード例 #4
0
def sensor_values():
	trigger.value(0)
	time.sleep_us(2)
	# inicia el pulso de 10us
	trigger.value(1)
	time.sleep_us(10)
	trigger.value(0)
	# activar echo
	pulso = machine.time_pulse_us(echo, 1, 30000)
	dist = round(pulso * 0.01716, 2)
	a=0
	
	while dist<2 or dist>400:
			trigger.value(1)
			time.sleep_us(10)
			trigger.value(0)
			pulso = machine.time_pulse_us(echo, 1, 30000)
			dist = round(pulso * 0.01716, 2)
			a+=1
			if a==2:
				sys.stdout.write('--> midiendo..')
			elif a>2:
				sys.stdout.write('.')

	if a!=0:
		print("")

	print("Distancia: ", dist,"cm")
コード例 #5
0
ファイル: pwm_read.py プロジェクト: tarzain/muni_clock
    def get_angle(self):
        self.t_highs = []
        self.t_lows = []

        self.t_highs.append(machine.time_pulse_us(self.pin, 1, 1100))
        self.t_highs.append(machine.time_pulse_us(self.pin, 1, 1100))

        self.t_lows.append(machine.time_pulse_us(self.pin, 0, 1100))
        self.t_lows.append(machine.time_pulse_us(self.pin, 0, 1100))

        self.t_high = max(self.t_highs)
        self.t_low = max(self.t_lows)

        tCycle = self.t_high + self.t_low
        theta = 0
        dc = 0
        unitsFC = 360
        dcMin = 0.029
        dcMax = 0.971
        dutyScale = 1
        if(tCycle == 0):
            return 0
        dc = (dutyScale * self.t_high) / tCycle
        theta = ((dc - dcMin) * unitsFC) / (dcMax - dcMin)
        return theta
コード例 #6
0
def irBin(rx):
    puls = 0
    data_raw = []
    print("Receive......")
    while puls < 4400 or puls > 4600:
        puls = time_pulse_us(rx, 1)
    while puls < 30000:
        puls = time_pulse_us(rx, 1)
        data_raw.append(puls)
    return data_raw
コード例 #7
0
 def decode_ir(self):
     # COPPIE DI VALORI TEMPORALI
     # VALORE SPERIMENTALE
     nletture = 38
     lettura_tot = []
     ingresso = Pin("X5" , Pin.IN, Pin.PULL_UP)
     # SALVO LA SEQUENZA INVIATA DAL TELECOMANDO IN UNA LISTA
     for i in range(nletture):
         lettura_tot.append(machine.time_pulse_us(ingresso,0))
         lettura_tot.append(machine.time_pulse_us(ingresso,1))
     return lettura_tot
コード例 #8
0
    def sendBit(self, bit):
        try:
            machine.time_pulse_us(self.pin, 0, timeout_us=60)
        except:
            self.err = 'Write timeslot timeout'
            return

        if bit & 1:
            return
        else:
            self.pin.low()
            self.pin.init(self.pin.OUT_OD)
            time.sleep_us(60)
            self.pin.init(self.pin.IN, self.pin.PULL_NONE)
        return
コード例 #9
0
    def sendBit(self, bit):
        try:
            machine.time_pulse_us(self.pin, 0, timeout_us=60)
        except:
            self.err = 'Write timeslot timeout'
            return

        if bit & 1:
            return
        else:
            self.pin.low()
            self.pin.init(self.pin.OUT_OD)
            time.sleep_us(60)
            self.pin.init(self.pin.IN, self.pin.PULL_NONE)
        return
コード例 #10
0
 def _send_pulse_and_wait(self):
     """
     Send the pulse to trigger and listen on echo pin.
     We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
     """
     self.trigger.value(0)  # Stabilize the sensor
     sleep_us(5)
     self.trigger.value(1)
     # Send a 10us pulse.
     sleep_us(10)
     self.trigger.value(0)
     try:
         pulse_time = time_pulse_us(self.echo, 1, self.echo_timeout_us)
         # time_pulse_us returns -2 if there was timeout waiting for condition; and -1 if there was timeout during the main measurement. It DOES NOT raise an exception
         # ...as of MicroPython 1.17: http://docs.micropython.org/en/v1.17/library/machine.html#machine.time_pulse_us
         if pulse_time < 0:
             MAX_RANGE_IN_CM = const(
                 500
             )  # it's really ~400 but I've read people say they see it working up to ~460
             pulse_time = int(MAX_RANGE_IN_CM * 29.1)  # 1cm each 29.1us
         return pulse_time
     except OSError as ex:
         if ex.args[0] == 110:  # 110 = ETIMEDOUT
             raise OSError('Out of range')
         raise ex
コード例 #11
0
    def _send_pulse_and_wait(self):
        """
        Send the pulse to trigger and listen on echo pin.
        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
        """
        self.trigger.value(0)  # Stabilize the sensor
        time.sleep_us(5)
        self.trigger.value(1)
        # Send a 10us pulse.
        time.sleep_us(10)
        self.trigger.value(0)
        try:
            if (uname().sysname == 'WiPy'):
                pulse_list = pulses_get(self.echo, self.echo_timeout_us)
                if (len(pulse_list) == 0):
                    pulse_time = -1
                else:
                    pulse_time = pulse_list[0][1]
            else:
                pulse_time = time_pulse_us(self.echo, 1, self.echo_timeout_us)

            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110:  # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex
コード例 #12
0
def ReadFLOW(trig, echo):

    timeout_us = 25000  # no need to wait more then sensor's range limit (4,00 m)

    sensor_hight = 1, 50

    trig.value(1)
    sleep_us(10)
    trig.value(0)

    duration = time_pulse_us(echo, 1, timeout_us)

    if duration < 0:
        print("Out of range")
    else:
        # To calculate the distance we get the pulse_time and divide it by 2
        # (the pulse walk the distance twice)
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.034320 cm/us that is 1cm each 29.1us

        # Calculate the Speed of Sound in M/S
        sound_comp = 331.4 + (0.606 * temp_dht22) + (0.0124 * hum_dht22)

        distance = (duration / 2) * 0.000343

        water_hight = sensor_hight - distance

        discharge = (0.209763317*(water_hight**(5/3))) / \
            ((water_hight + 0.918486862)**(2/3))
        print(discharge, " m3/s")

    pass
コード例 #13
0
    def get_distance(self):
        # Delay measurement if measure frequency is too high in order to avoid overlapping echos.
        time_to_next_measurement = 3 * Ultrasonic._MAX_ULTRASONIC_TRAVEL_TIME - \
            (ticks_us() - Ultrasonic._last_trigger_us)
        if time_to_next_measurement > 0:
            sleep_us(time_to_next_measurement)

        # Reset pins
        self.echo_pin.read_digital()
        self.trig_pin.write_digital(0)
        sleep_us(2)

        # Trigger sound
        Ultrasonic._last_trigger_us = ticks_us()
        self.trig_pin.write_digital(1)
        sleep_us(10)
        self.trig_pin.write_digital(0)

        # Read echo travel time
        travel_time = time_pulse_us(self.echo_pin, 1,
                                    Ultrasonic._MAX_ULTRASONIC_TRAVEL_TIME)
        if travel_time <= 0:
            travel_time = Ultrasonic._MAX_ULTRASONIC_TRAVEL_TIME

        # Return distance
        return travel_time // self.distance_unit
コード例 #14
0
ファイル: HCSR04.py プロジェクト: hoosierEE/crimsonbot
    def get_distance_cm(self, measurement = "CM", log=True):
        '''
            Calculates a single sensor ping value.

        param:measurement: Defaults to Centimeter conversion. Takes string of either
        "CM" or "IN".
        param:log: Logging defaults to print the distance, set to False to skip.
        '''
        trigPin = self.trigPin
        echoPin = self.echoPin

        # Clears the trigPin
        trigPin(HIGH);
        trigPin(LOW);
        sleep_us(2)

        # Sets the trigPin on HIGH state for 10 micro seconds
        trigPin(HIGH);
        sleep_us(10);
        trigPin(LOW);

        # Reads the echoPin, `time` gets set to the sound wave
        # travel time in microseconds.
        try:
            time = time_pulse_us(echoPin, HIGH, 29000)
        except Exception:
            run = False

        # Calculating the distance in Centimeters
        dist_in_cm = (time / 2.0) / 29
        #Prints the distance on the Serial Monitor
        if log == True:
            print("Distance: ", dist_in_cm, "cm");

        return dist_in_cm
コード例 #15
0
def get_distance():
    trig.write_digital(1)
    trig.read_digital(0)
    micros = time_pulse_us(echo, 1)
    t_echo = micros/1000000
    dist_cm = (t_echo / 2) *34300
    sleep(100)
コード例 #16
0
 def measure_distance(self):
     self.trigger.high()
     utime.sleep_us(10)
     self.trigger.low()
     pulse_time = machine.time_pulse_us(self.echo, 1, 50000)
     print(pulse_time)
     return pulse_time
コード例 #17
0
 def distance_sensor(trigger_pin, echo_pin, echo_timeout_us=50000):
     '''https://sho0.neocities.org/downloads/8c65ac1b85b79ef3fed8c9a9fa699147.pdf'''
     # Инициируем работу вывода trigger (out)
     trigger = machine.Pin(trigger_pin, mode=machine.Pin.OUT, pull=None)
     # Инициируем работу вывода echo (in)
     echo = machine.Pin(echo_pin, mode=machine.Pin.IN, pull=None)
     # Стабилизируем значения датчика
     trigger.value(0)
     utime.sleep_us(5)
     # Посылаем импульс длительностью 10мкрс
     trigger.value(1)
     utime.sleep_us(10)
     trigger.value(0)
     # Функция `machine.time_pulse_us()` нужна, чтобы вычислить время с момента отправки
     # до момента получения сигнала на выводе echo
     try:
         pulse_time = machine.time_pulse_us(echo, machine.Pin.IN, echo_timeout_us)
     except OSError as ex:
         if ex.args[0] == 110: # 110 = ETIMEDOUT
             raise OSError('Out of range')
         raise ex
     # Для рассчёта расстояния берём значение <pulse_time> в микросекундах и делим его на 2,
     # (так как сигнал прошёл расстояние до препятствия, отразился и вернулся,
     # то есть прошёл расстояние дважды) и делим ещё раз на 29.1, так как скорость
     # звука в воздухе при температуре 20 градусов Цельсия равна 343 м/с, что при
     # пересчёте даёт значение 0.0343 см/мкрс или 1 см за 29.1 микросекунды и
     # в результате получим число сантиметров от сенсора до препятствия.
     # При работе в других температурных условиях см. таблицу скоростей звука!
     cms = (pulse_time/2) / 29.1
     # Если надо ограничить количество знаков после запятой, раскомментируйте следующую строку:
     #return float('{:.Nf}'.format(cms)) # where N - number of decimal points
     # и закомментируйте строку ниже
     return cms
コード例 #18
0
ファイル: fender.py プロジェクト: georgetzianabos/fender
    def read_distance(self):

        self.motor_stop(LEFT_MOTOR)
        self.motor_stop(RIGHT_MOTOR)

        divider = 42
        maxtime = 250 * divider

        pin2.read_digital()
        pin1.write_digital(0)
        utime.sleep_us(2)
        pin1.write_digital(1)
        utime.sleep_us(10)
        pin1.write_digital(0)

        duration = machine.time_pulse_us(pin2, 1, maxtime)
        distance = duration / divider

        color = (0, 255, 0)

        if distance <= 35:
            color = (255, 0, 0)
        elif distance > 35 and distance < 50:
            color = (255, 128, 0)

        for led in range(4):
            self.np[led] = color

        self.np.show()

        return distance
コード例 #19
0
 def distance(self):
     """Measure pulse length and return calculated distance [m]."""
     self._pulse()
     #PePo: pulse_width_s = time_pulse_us(self._echo, Pin.high) / 1000000
     pulse_width_s = time_pulse_us(self._echo, 1) / 1000000
     dist_m = (pulse_width_s / 2) * self._sound_speed
     return dist_m
コード例 #20
0
def	csbcx():				#超声波测距
	Trig.value(0)
	pyb.udelay(5)
	Trig.value(1)
	pyb.udelay(10)
	Trig.value(0)
	s=machine.time_pulse_us(Echo, 1, 30000)
	return (s*100//582)*2
コード例 #21
0
def distance(tp, ep):
    ep.read_digital()
    tp.write_digital(1)
    sleep_us(10)
    tp.write_digital(0)
    ts = time_pulse_us(ep, 1, 5000)
    if ts > 0: return ts * 17 // 100
    return ts
コード例 #22
0
ファイル: sensor.py プロジェクト: ccldaout/esp32
 def sense(self):
     for pin, dur_us, tmo_us, _ in self._pins:
         pin.init(machine.Pin.OUT, value=1)
         time.sleep_us(dur_us)
         pin.init(machine.Pin.IN)
         us = machine.time_pulse_us(pin, 1, tmo_us)
         pin.init(machine.Pin.OUT, value=0)
         yield us
コード例 #23
0
ファイル: main.py プロジェクト: limehouselabs/doorbell
def on_press(pin):
    if pin.value() == EXPECTED_STATE:
        pulse_len = machine.time_pulse_us(pin, EXPECTED_STATE,
                                          DOORBELL_TIMEOUT)
        if pulse_len > DOORBELL_TIME:
            if in_startup:
                bing_bong(STARTUP_MESSAGE)
            else:
                bing_bong(DOORBELL_MESSAGE)
コード例 #24
0
 def sample(self):
     self.stabilizeSensor()
     self.sendTriggerSignal()
     try:
         return machine.time_pulse_us(self.echo, 1, 30000)
     except OSError as ex:
         if ex.args[0] == 110:
             raise OSError("out of range")
         raise ex
コード例 #25
0
ファイル: micro_grove.py プロジェクト: qkzk/data_colab
def mesure_temps_A_R(broche = pin1):
    broche.write_digital(0)
    sleep_ms(2)
    broche.write_digital(1)
    sleep_ms(10)
    broche.write_digital(0)
    broche.read_digital()
    dt = time_pulse_us(broche, 1)
    return dt
コード例 #26
0
ファイル: hal.py プロジェクト: robokoding/sumorobot-firmware
 def get_sonar_value(self):
     # Send a pulse
     self.trigger.value(0)
     sleep_us(5)
     self.trigger.value(1)
     sleep_us(10)
     self.trigger.value(0)
     # Wait for the pulse and calculate the distance
     return round((time_pulse_us(self.echo, 1, 30000) / 2) / 29.1)
コード例 #27
0
ファイル: Tach.py プロジェクト: coylen/upyTach
 def update(self):
     try:
         while self.tach_pin.value() == 1:
             pass
         self.pulse_us = time_pulse_us(self.tach_pin, 1, 100000)
         self.RPM = 5000000 / self.pulse_us
         self.engine_on = True
     except:
         self.engine_on = False
         self.RPM = 0
コード例 #28
0
ファイル: sensor.py プロジェクト: ccldaout/esp32
    def measure(self):
        self._trig.value(1)
        time.sleep(0.00001)  # 10us
        self._trig.value(0)

        us = machine.time_pulse_us(self._echo, 1, self.tmo_us)
        if us > 0:
            dist = float(self.coef_cm * us)
            return min(max(2.0, dist), 400.0)
        return None
コード例 #29
0
def sonic(in1, in2):
    in1.write_digital(0)
    in2.read_digital()
    while True:
        in1.write_digital(1)
        in1.write_digital(0)
        time = time_pulse_us(in2, 1) / 10**6
        dist = int(time / 2 * 34300)
        display.show(dist)
        sleep(100)
コード例 #30
0
ファイル: diy13_1.py プロジェクト: reyna168/micropython_class
def distance():
    trigPin.value(1)
    time.sleep_us(10)
    trigPin.value(0)

    pulseTime = machine.time_pulse_us(echoPin, 1, echoTimeout)
    if pulseTime > 0:
        return pulseTime / 58
    else:
        return pulseTime
コード例 #31
0
ファイル: esp_8266Full.py プロジェクト: wwj718/python_banyan
 def distance_in_cm(self):
     self.trigger.value(1)
     sleep_us(10)
     self.trigger.value(0)
     try:
         time = time_pulse_us(self.echo, 1, 29000)
     except OSError:
         return None
     dist_in_cm = (time / 2.0) / 29
     return dist_in_cm
コード例 #32
0
ファイル: DistanceSensor.py プロジェクト: borigas/GarageMqtt
 def Measure(self):
     self.triggerPin.value(1)
     #time.sleep(0.001)
     self.triggerPin.value(0)
     
     time = machine.time_pulse_us(self.echoPin, 1, 100000)
     dist = 165.7 * time * 3.28084 / 1000000
     #print("Dist: ", dist, " ft. Temp Timer: ", time)
     
     return dist
コード例 #33
0
def distance():
    trigPin.value(1)  # 送出 10 us 的觸發訊號
    time.sleep_us(10)
    trigPin.value(0)
    # 計算高電位脈衝的時間
    pulseTime = machine.time_pulse_us(echoPin, 1, echoTimeout)
    if pulseTime > 0:
        return pulseTime / 58  # 公分換算
    else:
        return pulseTime  # 傳回 -1或-2
コード例 #34
0
    def distance_in_cm(self):
        # Send a 10us pulse
        self.trigger.on()
        sleep_us(10)
        self.trigger.off()

        # Wait for the pulse and calc its duration
        time_pulse = time_pulse_us(self.echo, 1, self.timeout)

        if time_pulse < 0:
            raise MeasurementTimeout(self.timeout)

        # Divide the duration of the pulse by 2 (round-trip) and then divide it
        # by 29 us/cm (speed of sound = ~340 m/s)
        return (time_pulse / 2) / 29
コード例 #35
0
    def recvBit(self):
        """Receive one bit

        High means 1 and low means 0. There will always be a short high pulse at the start of a time
        window, and then either it will fall (0) or not (1).
        """
        try:
            t = machine.time_pulse_us(self.pin, 0, timeout_us=100)
            if t > 30:
                return 0
            else:
                return 1
        except OSError:
            # We hit one of the two timeouts, which means it didn't go high,
            # which means a zero.
            return 0
コード例 #36
0
 def _send_pulse_and_wait(self):
     """
     Send the pulse to trigger and listen on echo pin.
     We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
     """
     self.trigger.value(0) # Stabilize the sensor
     time.sleep_us(5)
     self.trigger.value(1)
     # Send a 10us pulse.
     time.sleep_us(10)
     self.trigger.value(0)
     try:
         pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
         return pulse_time
     except OSError as ex:
         if ex.args[0] == 110: # 110 = ETIMEDOUT
             raise OSError('Out of range')
         raise ex
コード例 #37
0
import utime
import machine
from hwconfig import LED, BUTTON

# machine.time_pulse_us() function demo

print("""\
Let's play an interesting game:
You click button as fast as you can, and I tell you how slow you are.
Ready? Cliiiiick!
""")

while 1:
    delay = machine.time_pulse_us(BUTTON, 1, 10*1000*1000)
    if delay < 0:
        print("Well, you're *really* slow")
    else:
        print("You are as slow as %d microseconds!" % delay)
    utime.sleep_ms(10)