Exemple #1
0
class DHTBase:
    """ base support for DHT11 and DHT22 devices
    """

    __hiLevel = 51

    def __init__(self, dht11, pin, trig_wait, use_pulseio):
        """
        :param boolean dht11: True if device is DHT11, otherwise DHT22.
        :param ~board.Pin pin: digital pin used for communication
        :param int trig_wait: length of time to hold trigger in LOW state (microseconds)
        :param boolean use_pulseio: False to force bitbang when pulseio available (only with Blinka)
        """
        self._dht11 = dht11
        self._pin = pin
        self._trig_wait = trig_wait
        self._last_called = 0
        self._humidity = None
        self._temperature = None
        self._use_pulseio = use_pulseio
        if "Linux" not in uname() and not self._use_pulseio:
            raise Exception("Bitbanging is not supported when using CircuitPython.")
        # We don't use a context because linux-based systems are sluggish
        # and we're better off having a running process
        if self._use_pulseio:
            self.pulse_in = PulseIn(self._pin, 81, True)
            self.pulse_in.pause()

    def exit(self):
        """ Cleans up the PulseIn process. Must be called explicitly """
        if self._use_pulseio:
            self.pulse_in.deinit()

    def _pulses_to_binary(self, pulses, start, stop):
        """Takes pulses, a list of transition times, and converts
        them to a 1's or 0's.  The pulses array contains the transition times.
        pulses starts with a low transition time followed by a high transistion time.
        then a low followed by a high and so on.  The low transition times are
        ignored.  Only the high transition times are used.  If the high
        transition time is greater than __hiLevel, that counts as a bit=1, if the
        high transition time is less that __hiLevel, that counts as a bit=0.

        start is the starting index in pulses to start converting

        stop is the index to convert upto but not including

        Returns an integer containing the converted 1 and 0 bits
        """

        binary = 0
        hi_sig = False
        for bit_inx in range(start, stop):
            if hi_sig:
                bit = 0
                if pulses[bit_inx] > self.__hiLevel:
                    bit = 1
                binary = binary << 1 | bit

            hi_sig = not hi_sig

        return binary

    def _get_pulses_pulseio(self):
        """ _get_pulses implements the communication protcol for
        DHT11 and DHT22 type devices.  It sends a start signal
        of a specific length and listens and measures the
        return signal lengths.

        return pulses (array.array uint16) contains alternating high and low
        transition times starting with a low transition time.  Normally
        pulses will have 81 elements for the DHT11/22 type devices.
        """
        pulses = array.array("H")
        if self._use_pulseio:
            # The DHT type device use a specialize 1-wire protocol
            # The microprocessor first sends a LOW signal for a
            # specific length of time.  Then the device sends back a
            # series HIGH and LOW signals.  The length the HIGH signals
            # represents the device values.
            self.pulse_in.clear()
            self.pulse_in.resume(self._trig_wait)

            # loop until we get the return pulse we need or
            # time out after 1/4 second
            time.sleep(0.25)
            self.pulse_in.pause()
            while self.pulse_in:
                pulses.append(self.pulse_in.popleft())
        return pulses

    def _get_pulses_bitbang(self):
        """ _get_pulses implements the communication protcol for
        DHT11 and DHT22 type devices.  It sends a start signal
        of a specific length and listens and measures the
        return signal lengths.

        return pulses (array.array uint16) contains alternating high and low
        transition times starting with a low transition time.  Normally
        pulses will have 81 elements for the DHT11/22 type devices.
        """
        pulses = array.array("H")
        with DigitalInOut(self._pin) as dhtpin:
            # we will bitbang if no pulsein capability
            transitions = []
            # Signal by setting pin high, then low, and releasing
            dhtpin.direction = Direction.OUTPUT
            dhtpin.value = True
            time.sleep(0.1)
            dhtpin.value = False
            time.sleep(0.001)
            timestamp = time.monotonic()  # take timestamp
            dhtval = True  # start with dht pin true because its pulled up
            dhtpin.direction = Direction.INPUT
            dhtpin.pull = Pull.UP
            while time.monotonic() - timestamp < 0.25:
                if dhtval != dhtpin.value:
                    dhtval = not dhtval  # we toggled
                    transitions.append(time.monotonic())  # save the timestamp
            # convert transtions to microsecond delta pulses:
            # use last 81 pulses
            transition_start = max(1, len(transitions) - 81)
            for i in range(transition_start, len(transitions)):
                pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i - 1]))
                pulses.append(min(pulses_micro_sec, 65535))
        return pulses

    def measure(self):
        """ measure runs the communications to the DHT11/22 type device.
            if successful, the class properties temperature and humidity will
            return the reading returned from the device.

            Raises RuntimeError exception for checksum failure and for insuffcient
            data returned from the device (try again)
        """
        delay_between_readings = 2  # 2 seconds per read according to datasheet
        # Initiate new reading if this is the first call or if sufficient delay
        # If delay not sufficient - return previous reading.
        # This allows back to back access for temperature and humidity for same reading
        if (
            self._last_called == 0
            or (time.monotonic() - self._last_called) > delay_between_readings
        ):
            self._last_called = time.monotonic()

            new_temperature = 0
            new_humidity = 0

            if self._use_pulseio:
                pulses = self._get_pulses_pulseio()
            else:
                pulses = self._get_pulses_bitbang()
            # print(len(pulses), "pulses:", [x for x in pulses])

            if len(pulses) < 10:
                # Probably a connection issue!
                raise RuntimeError("DHT sensor not found, check wiring")

            if len(pulses) < 80:
                # We got *some* data just not 81 bits
                raise RuntimeError("A full buffer was not returned. Try again.")

            buf = array.array("B")
            for byte_start in range(0, 80, 16):
                buf.append(self._pulses_to_binary(pulses, byte_start, byte_start + 16))

            if self._dht11:
                # humidity is 1 byte
                new_humidity = buf[0]
                # temperature is 1 byte
                new_temperature = buf[2]
            else:
                # humidity is 2 bytes
                new_humidity = ((buf[0] << 8) | buf[1]) / 10
                # temperature is 2 bytes
                # MSB is sign, bits 0-14 are magnitude)
                new_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10
                # set sign
                if buf[2] & 0x80:
                    new_temperature = -new_temperature
            # calc checksum
            chk_sum = 0
            for b in buf[0:4]:
                chk_sum += b

            # checksum is the last byte
            if chk_sum & 0xFF != buf[4]:
                # check sum failed to validate
                raise RuntimeError("Checksum did not validate. Try again.")

            if new_humidity < 0 or new_humidity > 100:
                # We received unplausible data
                raise RuntimeError("Received unplausible data. Try again.")

            self._temperature = new_temperature
            self._humidity = new_humidity

    @property
    def temperature(self):
        """ temperature current reading.  It makes sure a reading is available

            Raises RuntimeError exception for checksum failure and for insuffcient
            data returned from the device (try again)
        """
        self.measure()
        return self._temperature

    @property
    def humidity(self):
        """ humidity current reading. It makes sure a reading is available

            Raises RuntimeError exception for checksum failure and for insuffcient
            data returned from the device (try again)
        """
        self.measure()
        return self._humidity
Exemple #2
0
class Scale:
    """Interface to a DYMO postal scale.
    """
    def __init__(self, pin, timeout=1.0):
        """Sets up a DYMO postal scale.
        :param ~pulseio.PulseIn pin: The digital pin the scale is connected to.
        :param double timeout: The timeout, in seconds.
        """
        self.timeout = timeout
        self.dymo = PulseIn(pin, maxlen=96, idle_state=True)
        try:
            self.check_scale()
        except RuntimeError:
            raise RuntimeError(
                "Failed to inititalize the scale, is the scale on?")
        # units we're measuring
        self.units = None
        # is the measurement stable?
        self.stable = None
        # the weight of what we're measuring
        self.weight = None

    def check_scale(self):
        """Checks for data from the scale.
        """
        timestamp = time.monotonic()
        self.dymo.pause()
        self.dymo.clear()
        self.dymo.resume()
        while len(self.dymo) < 35:
            if (time.monotonic() - timestamp) > self.timeout:
                raise RuntimeError("Timed out waiting for data")
        self.dymo.pause()

    def get_scale_data(self):
        """Read a pulse of SPI data on a pin that corresponds to DYMO scale
        output protocol (12 bytes of data at about 14KHz), timeout is in seconds
        """
        # check the scale's state
        self.check_scale()
        bits = [0] * 96  # there are 12 bytes = 96 bits of data
        bit_idx = 0  # we will count a bit at a time
        bit_val = False  # first pulses will be LOW
        for i in range(len(self.dymo)):
            if self.dymo[i] == 65535:  # check for the pulse between transmits
                break
            num_bits = int(self.dymo[i] / PULSE_WIDTH +
                           0.5)  # ~14KHz == ~7.5us per clock
            for bit in range(num_bits):
                bits[bit_idx] = bit_val
                bit_idx += 1
                if bit_idx == 96:  # we have read all the data we wanted
                    break
            bit_val = not bit_val
        data_bytes = [0] * 12  # alllocate data array
        for byte_n in range(12):
            the_byte = 0
            for bit_n in range(8):
                the_byte <<= 1
                the_byte |= bits[byte_n * 8 + bit_n]
            data_bytes[byte_n] = the_byte
        # do some very basic data checking
        if data_bytes[0] != 3 or data_bytes[1] != 3 or data_bytes[7] != 4:
            raise RuntimeError("Bad data capture")
        if data_bytes[8] != 0x1C or data_bytes[9] != 0 or data_bytes[10] \
        or data_bytes[11] != 0:
            raise RuntimeError("Bad data capture")

        self.stable = data_bytes[2] & 0x4
        self.units = data_bytes[3]
        self.weight = data_bytes[5] + (data_bytes[6] << 8)
        if data_bytes[2] & 0x1:
            self.weight *= -1
        if self.units == OUNCES:
            # oi no easy way to cast to int8_t
            if data_bytes[4] & 0x80:
                data_bytes[4] -= 0x100
            self.weight *= 10**data_bytes[4]
            self.units = "oz"
        if self.units == GRAMS:
            self.units = "g"
Exemple #3
0
class DYMOScale:
    """Interface to a DYMO postal scale.
    """
    def __init__(self, data_pin, units_pin, timeout=1.0):
        """Sets up a DYMO postal scale.
        :param ~pulseio.PulseIn data_pin: The data pin from the Dymo scale.
        :param ~digitalio.DigitalInOut units_pin: The grams/oz button from the Dymo scale.
        :param double timeout: The timeout, in seconds.
        """
        self.timeout = timeout
        # set up the toggle pin
        self.units_pin = units_pin
        # set up the dymo data pin
        self.dymo = PulseIn(data_pin, maxlen=96, idle_state=True)

    @property
    def weight(self):
        """Weight in grams"""
        reading = self.get_scale_data()
        if reading.units == OUNCES:
            reading.weight *= 28.35
        reading.units = GRAMS
        return reading

    def toggle_unit_button(self, switch_units=False):
        """Toggles the unit button on the dymo.
        :param bool switch_units: Simulates pressing the units button.
        """
        toggle_times = 0
        if switch_units:  # press the button once
            toggle_amt = 2
        else:  # toggle and preserve current unit state
            toggle_amt = 4
        while toggle_times < toggle_amt:
            self.units_pin.value ^= 1
            time.sleep(2)
            toggle_times += 1

    def _read_pulse(self):
        """Reads a pulse of SPI data on a pin that corresponds to DYMO scale
        output protocol (12 bytes of data at about 14KHz).
        """
        timestamp = time.monotonic()
        self.dymo.pause()
        self.dymo.clear()
        self.dymo.resume()
        while len(self.dymo) < 35:
            if (time.monotonic() - timestamp) > self.timeout:
                raise RuntimeError(
                    "Timed out waiting for data - is the scale turned on?")
        self.dymo.pause()

    def get_scale_data(self):
        """Reads a pulse of SPI data and analyzes the resulting data.
        """
        self._read_pulse()
        bits = [0] * 96  # there are 12 bytes = 96 bits of data
        bit_idx = 0  # we will count a bit at a time
        bit_val = False  # first pulses will be LOW
        for i in range(len(self.dymo)):
            if self.dymo[i] == 65535:  # check for the pulse between transmits
                break
            num_bits = int(self.dymo[i] / PULSE_WIDTH +
                           0.5)  # ~14KHz == ~7.5us per clock
            bit = 0
            while bit < num_bits:
                bits[bit_idx] = bit_val
                bit_idx += 1
                if bit_idx == 96:  # we have read all the data we wanted
                    break
                bit += 1
            bit_val = not bit_val
        data_bytes = [0] * 12  # alllocate data array
        for byte_n in range(12):
            the_byte = 0
            for bit_n in range(8):
                the_byte <<= 1
                the_byte |= bits[byte_n * 8 + bit_n]
            data_bytes[byte_n] = the_byte
        # do some very basic data checking
        if data_bytes[0] != 3 and data_bytes[0] != 2:
            raise RuntimeError("Bad data capture")
        if data_bytes[1] != 3 or data_bytes[7] != 4 or data_bytes[8] != 0x1C:
            raise RuntimeError("Bad data capture")
        if data_bytes[9] != 0 or data_bytes[10] or data_bytes[11] != 0:
            raise RuntimeError("Bad data capture")
        reading = ScaleReading()
        # parse out the data_bytes
        reading.stable = data_bytes[2] & 0x4
        reading.units = data_bytes[3]
        reading.weight = data_bytes[5] + (data_bytes[6] << 8)
        if data_bytes[2] & 0x1:
            reading.weight *= -1
        if reading.units == OUNCES:
            if data_bytes[4] & 0x80:
                data_bytes[4] -= 0x100
            reading.weight *= 10**data_bytes[4]
        return reading
Exemple #4
0
    ss.pin_mode(pir, ss.OUTPUT)
    ss.pin_mode(pir, ss.INPUT_PULLUP)

pir_read = [False, False, False, False]
pir_readpre = [False, False, False, False]
pir_change = [False, False, False, False]
change_index = []
last_change = 0
max_change = 4

direction = 0
servo_speed = 0

while True:
    # read the pulseIn object for the servo_fb
    servo_fb.pause()
    print(servo_fb)
    servo_fb.clear()
    pulses.resume()
    """
    # read each sensor in order and look for a change from low to high
    for index, pir in enumerate(PIR):
        pir_read[index] = ss.digital_read(pir)
        if pir_read[index] != pir_readpre[index]:
            pir_readpre[index] = pir_read[index]
            if pir_read[index] == True:
                pir_change[index] = True
                change_index.append(index + 1)
        else:
            pir_change[index] = False
    else:
class HCSR04:
    """Control a HC-SR04 ultrasonic range sensor.

    Example use:

    ::

        with HCSR04(trig, echo) as sonar:
            try:
                while True:
                    print(sonar.dist_cm())
                    sleep(2)
            except KeyboardInterrupt:
                pass
    """
    def __init__(self, trig_pin, echo_pin, timeout_sec=.1):
        """
        :param trig_pin: The pin on the microcontroller that's connected to the
            ``Trig`` pin on the HC-SR04.
        :type trig_pin: str or microcontroller.Pin
        :param echo_pin: The pin on the microcontroller that's connected to the
            ``Echo`` pin on the HC-SR04.
        :type echo_pin: str or microcontroller.Pin
        :param float timeout_sec: Max seconds to wait for a response from the
            sensor before assuming it isn't going to answer. Should *not* be
            set to less than 0.05 seconds!
        """
        if isinstance(trig_pin, str):
            trig_pin = getattr(board, trig_pin)
        if isinstance(echo_pin, str):
            echo_pin = getattr(board, echo_pin)
        self.dist_cm = self._dist_two_wire
        self.timeout_sec = timeout_sec

        self.trig = DigitalInOut(trig_pin)
        self.trig.switch_to_output(value=False, drive_mode=DriveMode.PUSH_PULL)

        self.echo = PulseIn(echo_pin)
        self.echo.pause()
        self.echo.clear()

    def __enter__(self):
        """Allows for use in context managers."""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """Automatically de-initialize after a context manager."""
        self.deinit()

    def deinit(self):
        """De-initialize the trigger and echo pins."""
        self.trig.deinit()
        self.echo.deinit()

    def dist_cm(self):
        """Return the distance measured by the sensor in cm.

        This is the function that will be called most often in user code. The
        distance is calculated by timing a pulse from the sensor, indicating
        how long between when the sensor sent out an ultrasonic signal and when
        it bounced back and was received again.

        If no signal is received, the return value will be ``-1``. This means
        either the sensor was moving too fast to be pointing in the right
        direction to pick up the ultrasonic signal when it bounced back (less
        likely), or the object off of which the signal bounced is too far away
        for the sensor to handle. In my experience, the sensor can detect
        objects over 460 cm away.

        :return: Distance in centimeters.
        :rtype: float
        """
        # This method only exists to make it easier to document. See either
        # _dist_one_wire or _dist_two_wire for the actual implementation. One
        # of those two methods will be assigned to be used in place of this
        # method on instantiation.
        pass

    def _dist_two_wire(self):
        self.echo.clear()  # Discard any previous pulse values
        self.trig.value = 1  # Set trig high
        time.sleep(0.00001)  # 10 micro seconds 10/1000/1000
        self.trig.value = 0  # Set trig low
        timeout = time.monotonic()
        self.echo.resume()
        while len(self.echo) == 0:
            # Wait for a pulse
            if (time.monotonic() - timeout) > self.timeout_sec:
                self.echo.pause()
                return -1
        self.echo.pause()
        if self.echo[0] == 65535:
            return -1

        return (self.echo[0] / 2) / (291 / 10)
Exemple #6
0
## go-loop

#ch1 = array('H', [1500])
ch2 = array('H', [1500])

while True:
    # get radio channel values
    #steering_servo.angle = get_angle(steering_channel)
    #throttle_servo.angle = get_angle(throttle_channel)

    ### working between here and next comment
    while len(throttle_channel) == 0:
        pass

    throttle_channel.pause()

    print(throttle_channel[0])

    ch2[0] = throttle_channel[0]
    throttle_servo.send(ch2)
    #throttle_servo.angle = get_angle(steering_channel[0])

    throttle_channel.clear()

    throttle_channel.resume(20000)

    #time.sleep(0.01)
    ### working between here and last comment

    # while len(steering_channel) == 0 or len(throttle_channel) == 0: