class EncoderCounter(object):
    ticks_to_mm_const = None # you must set this up before using distance methods
    def __init__(self, pin_number):
        self.device = DigitalInputDevice(pin=pin_number)
        self.device.pin.when_changed = self.when_changed
        self.pulse_count = 0
        self.direction = 1

    def when_changed(self):
        self.pulse_count += self.direction

    def set_direction(self, direction):
        """ This should be -1 or 1. """
        assert abs(direction)==1, "Direction %s should be 1 or -1" % direction
        self.direction = direction

    def reset(self):
        self.pulse_count = 0

    def stop(self):
        self.device.close()

    def distance_in_mm(self):
        return int(self.pulse_count * EncoderCounter.ticks_to_mm_const)

    @staticmethod
    def mm_to_ticks(mm):
        return mm / EncoderCounter.ticks_to_mm_const

    @classmethod
    def set_constants(cls, wheel_diameter_mm, ticks_per_revolution):
        cls.ticks_to_mm_const = (math.pi / ticks_per_revolution) * wheel_diameter_mm
Example #2
0
    def _read_debug_byte(self) -> int:
        """
        Reads a byte from the debug interface. Requires DD to be
        input when function is called.
        
        Return
            Returns the byte read.
        """
        data = 0

        dev_dd = DigitalInputDevice(pin=self.pin_dd)

        for _ in range(8):
            self.dev_dc.on()

            data = data << 1
            if dev_dd.value == 1:
                data |= 0x01

            self.dev_dc.off()
            self._wait()
        
        dev_dd.close()

        return data
Example #3
0
def collector(sample_length=45,
              dout=LOAD_CELL_DOUT,
              sck=LOAD_CELL_SCK,
              gain=LOAD_CELL_GAIN,
              loadcell_threshold=-200000,
              fsr_threshold=0.5):
    start_time = time()

    d_out = DigitalInputDevice(pin=dout, pull_up=True)
    sck = DigitalOutputDevice(pin=sck)
    adc = MCP3008(channel=0)

    load_cell_results = []
    fsr_results = []
    sck.off()

    timeout = 2
    while time() - start_time < sample_length:
        # Retrieve data from MCP3008
        fsr_results.append(adc.value)

        # Retrieve data from HX711
        loop_start_time = time()
        while not d_out.is_active:
            if time() - loop_start_time > timeout:
                break

        data = 0
        for j in range(24):
            data = data << 1
            sck.on()
            sck.off()
            if d_out.value == 0:
                data = data + 1
        #print("data", data, hex(data), convert_twos_complement(data))
        # load_cell_results.append(data)
        load_cell_results.append((hex(data), convert_twos_complement(data)))

        # 25th pulse
        sck.on()
        sck.off()

        # 128 pulses
        for i in range(gain):
            sck.on()
            sck.off()

    # Process data
    loadcell_data = ','.join(str(e) for e in load_cell_results)
    fsr_data = ','.join(str(e) for e in fsr_results)

    loadcell_results = [e[1] for e in load_cell_results if e[0] != '0xffffff']
    loadcell_result = 1 if data_processor(loadcell_results,
                                          loadcell_threshold) else 0
    fsr_result = 1 if data_processor(fsr_results, fsr_threshold) else 0

    final_result = 1 if fsr_result == 1 or loadcell_result == 1 else 0

    # Send data to remote server
    # firebase_values = {
    #         'isSitting': final_result,
    #         'datetime': datetime.fromtimestamp(start_time, get_localzone()),
    #         'timestamp': int(start_time)
    # }
    # sender.sendToFirebase(firebase_values=firebase_values)
    resp = send(final_result,
                datetime.fromtimestamp(start_time, get_localzone()))
    print(resp)

    # Save data into local database
    db.insert((int(start_time), fsr_data, fsr_result, loadcell_data,
               loadcell_result, final_result))

    adc.close()
    d_out.close()
    sck.close()

    return (load_cell_results, fsr_results)
class RotaryEncoder(Device):
    """
    Decode mechanical rotary encoder pulses.
    Connect the extrems pins of the rotary encoder (left and right pins) to any GPIO
    and the middle pin to a ground pin. Alternatively, connect the middle pin to the
    3V3 pin, then set *pull_up* to ``False`` in the :class:`RotaryEncoder` constructor.
    The following example will print a Rotary Encoder change direction::
        from gpiozero import RotaryEncoder
        def change(value):
            if value > 0:
                print("clockwise")
            else:
                print("counterclockwise")
        rotary = RotaryEncoder(13, 19)
        rotary.when_rotated = change
    Based in Pigpio implementation `Pigpio implementation <http://abyz.co.uk/rpi/pigpio/examples.html#Python_rotary_encoder_py>`_
    and `Paul Stoffregen implementation <https://github.com/PaulStoffregen/Encoder>`_
    :param int pin_a:
        An extreme GPIO pin which the RotaryEncoder is attached to. See :ref:`pin_numbering`
        for valid pin numbers.
    :param int pin_b:
        The another extreme GPIO pin which the RotaryEncoder is attached to. See :ref:`pin_numbering`
        for valid pin numbers.
    :param bool pull_up:
        If ``True`` (the default), the GPIO pins will be pulled high by default.
        In this case, connect the middle GPIO pin to ground. If ``False``,
        the GPIO pins will be pulled low by default. In this case,
        connect the middle pin of the RotaryEncoder to 3V3.
    """

    def __init__(self, pin_a, pin_b, pull_up=True):
        super(RotaryEncoder, self).__init__()
        self.when_rotated = lambda *args: None

        self.pin_a = DigitalInputDevice(pin=pin_a, pull_up=pull_up)
        self.pin_b = DigitalInputDevice(pin=pin_b, pull_up=pull_up)

        self.pin_a.when_activated = self._pulse
        self.pin_a.when_deactivated = self._pulse

        self.pin_b.when_activated = self._pulse
        self.pin_b.when_deactivated = self._pulse

        self._old_a_value = self.pin_a.is_active
        self._old_b_value = self.pin_b.is_active

    def _pulse(self):
        """
        Calls when_rotated callback if detected changes
        """
        new_b_value = self.pin_b.is_active
        new_a_value = self.pin_a.is_active

        value = TableValues.value(new_b_value, new_a_value, self._old_b_value, self._old_a_value)

        self._old_b_value = new_b_value
        self._old_a_value = new_a_value

        if value != 0:
            self.when_rotated(value)

    def close(self):
        self.pin_a.close()
        self.pin_b.close()

    @property
    def closed(self):
        return self.pin_a.closed and self.pin_b.closed

    @property
    def is_active(self):
        return not self.closed

    @property
    def value(self):
        return None

    def __repr__(self):
        return "<gpiozero.%s object on pin_a %r, pin_b %r, pull_up=%s, is_active=%s>" % (
                self.__class__.__name__, self.pin_a.pin, self.pin_b.pin, self.pin_a.pull_up, self.is_active)
Example #5
0
        if value == '0':
            gpio_out.off()
        else:
            gpio_out.on()
        time.sleep(cycle_time)

    # Interpret all the 0s and 1s we've collected
    binary_incoming = []
    current_edge = edges[0]
    current_time = edges[0][0] + dt.timedelta(seconds=(cycle_time / 2))

    while edges:
        if edges[0][0] < current_time:
            current_edge = edges.pop(0)
            # This is far from a realtime system, we'll just correct any
            # timing drift sync every time we see an edge.
            current_time = current_edge[0] + dt.timedelta(seconds=(cycle_time /
                                                                   2))
        binary_incoming.append(current_edge[1])
        current_time += dt.timedelta(seconds=cycle_time)

    binary_received = ''.join(binary_incoming[:-len(end_of_file)])
    print("Received binary: " + binary_received)

    message_received = Morse.from_binary(binary_received)
    print("Received message: " + message_received.plain_text)

finally:
    gpio_in.close()
    gpio_out.close()
Example #6
0
class Fan(object):
    """Fan"""

    def __init__(self, name, power_pin, tach_pin, initial_power_state=False):
        """

        Set initial values and initialize pin
        Example: fan_object = fan.Fan(name='fan1', power_pin=17, initial_power_state=0, tach_pin=27)

        Arguments:
            name {string} -- Logical name of this instance
            power_pin {int} -- BCM pin connected to the fan transistor
            tach_pin {int} -- BCM pin connected to the fan sense line
            initial_power_state {Boolean} -- Initialize the fan to on (true) or off (false)
        """
        self.name = name
        self.power_pin = LED(power_pin, initial_value=initial_power_state)
        self.tach_pin = DigitalInputDevice(tach_pin, pull_up=True)
        self.rpm_readings = []
        self.tach_counter_lock = threading.Lock()
        self.tach_reader_lock = threading.Lock()
        self.tach_time = time.time()
        logging.debug("Fan %s is now initialized to %s", self.name, self.power_pin.is_lit)

    def turn_on(self):
        """Turn on the fan."""

        self.power_pin.on()
        logging.debug("Turning on fan %s", self.name)

    def turn_off(self):
        """Turn off the fan."""

        self.power_pin.off()
        logging.debug("Turning off fan %s", self.name)

    def power_status(self):
        """

        Return whether the fan is on or off.

        Returns:
            Boolean -- Returns True if the fan is on.  False if the fan is off.
        """
        return self.power_pin.is_lit

    def get_rpm(self):
        """

        Record fan pulses for 2 seconds, storing an RPM reading twice every revolution of the fan.
        The method is wrapped in a lock to make it thread safe.

        Returns:
            int -- Two second average of fan RPMs
        """
        with self.tach_reader_lock:  # pylint: disable=not-context-manager
            self.rpm_readings = []
            self.tach_pin.when_deactivated = self.tach_inter
            time.sleep(2)
            self.tach_pin.when_deactivated = None

            try:
                avg_rpm = sum(self.rpm_readings) / len(self.rpm_readings)
            except ZeroDivisionError:
                return int(0)

            return int(avg_rpm)

    def tach_inter(self):
        """
        This method is called everytime the tach pin falls. The fan pulses twice every revolution.
        When called, the time since the last call is computed and turned into an RPM.  That RPM
        is appended to a list.
        """
        with self.tach_counter_lock:  # pylint: disable=not-context-manager
            time_since_last_pulse = time.time() - self.tach_time
            if time_since_last_pulse < 0.01:
                return  # reject spuriously short pulses

            freq = 1 / time_since_last_pulse
            rpm = (freq / 2) * 60
            self.rpm_readings.append(rpm)
            self.tach_time = time.time()

    def close(self):
        """Free up the pins used by the fan"""
        self.power_pin.close()
        self.tach_pin.close()
Example #7
0
        schedule.every().day.at(time).do(actions,
                                         timesheet=timesheet.timesheet,
                                         time=time)
    schedule.every().day.at(utils.time_to_string(
        timesheet.end_time)).do(data_management)

    while True:
        schedule.run_pending()


def loop():
    while True:
        print(light_sensor.value)
        if light_sensor.value == 1:
            print("light is on")
        else:
            print("light is off")
        sleep(1)


if __name__ == "__main__":
    print(collected_data)
    try:
        run(collected_data)
    except (KeyboardInterrupt, EndSchedule):
        light_sensor.close()
        data_management()
        print(light_sense.complete_data)
        print("End")
        exit()