Ejemplo n.º 1
0
    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()
Ejemplo n.º 2
0
    def __init__(self, sig_pin, unit=1.0, timeout=1.0):
        self.unit = unit
        self.timeout = timeout

        self.echo = PulseIn(sig_pin)
        self.echo.pause()
        self.echo.clear()
Ejemplo n.º 3
0
 def __init__(self,
              dht11: bool,
              pin: Pin,
              trig_wait: int,
              use_pulseio: bool,
              *,
              max_pulses: int = 81):
     self._dht11 = dht11
     self._pin = pin
     self._trig_wait = trig_wait
     self._max_pulses = max_pulses
     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,
                                 maxlen=self._max_pulses,
                                 idle_state=True)
         self.pulse_in.pause()
Ejemplo n.º 4
0
 def __init__(self,
              dht11: bool,
              pin: Pin,
              trig_wait: int,
              use_pulseio: bool,
              *,
              max_pulses: int = 81):
     """
     :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._max_pulses = max_pulses
     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,
                                 maxlen=self._max_pulses,
                                 idle_state=True)
         self.pulse_in.pause()
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
 def __init__(self, dht11, pin, trig_wait):
     """
     :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)
     """
     self._dht11 = dht11
     self._pin = pin
     self._trig_wait = trig_wait
     self._last_called = 0
     self._humidity = None
     self._temperature = None
     # We don't use a context because linux-based systems are sluggish
     # and we're better off having a running process
     if _USE_PULSEIO:
         self.pulse_in = PulseIn(self._pin, 81, True)
Ejemplo n.º 7
0
 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
Ejemplo n.º 8
0
    def __init__(self, enButtons=True):
        self._buttonA = None
        self._buttonB = None
        self._enbuttons = False
        if enButtons:
            self._enbuttons = True
            self._buttonA = DigitalInOut(board.IO43)
            self._buttonA.switch_to_input(pull=Pull.UP)
            self._db_buttonA = Debouncer(self._buttonA, 0.01, True)
            self._buttonB = DigitalInOut(board.IO44)
            self._buttonB.switch_to_input(pull=Pull.UP)
            self._db_buttonB = Debouncer(self._buttonB, 0.01, True)

        # 3x Neopixels RGB pixels: IO0
        self._pixels = neopixel.NeoPixel( board.IO0, 3,  \
                    brightness=0.5, auto_write=False, pixel_order=neopixel.GRB )
        self._colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
        for i in range(3):
            self._pixels[i] = self._colors[i]
        self._pixels.show()
        self._pixelsRotationDt = 0.2
        self._pixelsRotationSt = time.monotonic()
        # Sense color Sensor (颜色传感器):  IO7
        self._colorSensor = AnalogIn(board.IO7)
        # Lighting Sensor (光强度传感器):  IO8--leftLightSensor, IO9--rightLightSensor
        self._leftLightSensor = AnalogIn(board.IO8)
        self._rightLightSensor = AnalogIn(board.IO9)
        # left and right head-LED: IO17--rightHeadLED, IO18--leftHeadLED
        self._leftHeadLED = DigitalInOut(board.IO18)
        self._leftHeadLED.direction = Direction.OUTPUT
        self._leftHeadLED.value = 0
        self._rightHeadLED = DigitalInOut(board.IO17)
        self._rightHeadLED.direction = Direction.OUTPUT
        self._rightHeadLED.value = 0
        # Ultrasonic module (超声波模块):  IO11--trig, IO10--echo
        self._timeout = 0.1
        self._trig = DigitalInOut(board.IO11)
        self._trig.direction = Direction.OUTPUT
        self._trig.value = 0
        if _USE_PULSEIO:
            self._echo = PulseIn(board.IO10)
            self._echo.pause()
            self._echo.clear()
        else:
            self._echo = DigitalInOut(board.IO10)
            self._echo.direction = Direction.INPUT
        # Tracking sensors (循迹传感器): IO4--rightTracker, IO3--rightTracker
        self._leftTracker = DigitalInOut(board.IO4)
        self._leftTracker.direction = Direction.INPUT
        self._rightTracker = DigitalInOut(board.IO3)
        self._rightTracker.direction = Direction.INPUT
        # Motor (Right):  IO41--rightMotor1IN, IO42--rightMotor2IN
        self._rightMotor1IN = PWMOut(board.IO41, frequency=100, duty_cycle=0)
        self._rightMotor2IN = PWMOut(board.IO42, frequency=100, duty_cycle=0)
        # Motor (Left):  IO12--leftMotor1IN, IO40--leftMotor2IN
        self._leftMotor1IN = PWMOut(board.IO12, frequency=100, duty_cycle=0)
        self._leftMotor2IN = PWMOut(board.IO40, frequency=100, duty_cycle=0)
Ejemplo n.º 9
0
    def __init__(self, name, pwmpin, channelpin, directionpin=None, value=REMOTE_STOP_PULSE, frequency=60, duty_cycle=0):
        self.name = name
        self.pwm = PWMOut(pwmpin, frequency=frequency, duty_cycle=duty_cycle)
        self.channel = PulseIn(channelpin, maxlen=64, idle_state=0)

        # extra motor control things for PWM Motors
        if directionpin not None:
            self.direction = DigitalInOut(directionpin)
            self.direction.direction = Direction.OUTPUT
            self.direction.value = False
            self.update_function = motor_duty_cycle
Ejemplo n.º 10
0
class RCInput():
	def __init__(self, rcPin, updateCallback = None):
		self._pulse = 1500 # center
		self.rc = PulseIn(rcPin, maxlen=16, idle_state=0)
		self.update_callback = updateCallback
	@property
	def pulse(self):
		return self._pulse
	@pulse.setter
	def pulse(self, pulse):
		self._pulse = pulse
		if(self.update_callback is not None):
			self.update_callback(pulse)

	def run(self, update = True):
		valid_pulse = False
		self.rc.pause()
		samples = len(self.rc)
		if(samples == 0):
			self.rc.resume()
			if(DEBUG):
				print("RCInput: No input from RC received (this might happen if you call run() too frequently and can be ignored in this case).")
			return False

		value = avg = self.pulse
		for i in range(0, samples):
			val = self.rc[i]
			# we (seem to) capture the length of the 0 pulse too (about 6000ms), filter for valid pulses
			if(val < 900 or val > 2100): # pulses get normalized afterwards anyways, but we want to filter invalid ones really
				continue
			valid_pulse = True
			value = val
			avg = (self.pulse + value) / 2 # average over the collected samples
		self.rc.clear()
		self.rc.resume()
		if DEBUG:
			print(f'RCInput: Got {samples} samples, last val={value}, current avg={self.pulse}{", valid" if valid_pulse else ""}{", update callback" if update else ""}')
		if(update):
			self.pulse = avg
		else:
			self._pulse = avg # don't call the update callback to change the attached servo/motor
		return valid_pulse
Ejemplo n.º 11
0
    def __init__(self, sig_pin, unit=1.0, timeout=1.0):
        """
		:param sig_pin: The pin on the microcontroller that's connected to the
			``Sig`` pin on the GroveUltrasonicRanger.
		:type sig_pin: microcontroller.Pin
		:param float unit: pass in conversion factor for unit conversions from cm
			for example 2.54 would convert to inches.
		:param float timeout: 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!
		"""
        self._unit = unit
        self._timeout = timeout * TICKS_PER_SEC

        if _USE_PULSEIO:
            self._sig = PulseIn(sig_pin)
            self._sig.pause()
            self._sig.clear()
        else:
            self._sig = DigitalInOut(sig_pin)
            self._sig.direction = Direction.OUTPUT
            self._sig.value = False  # Set trig low
Ejemplo n.º 12
0
    def __init__(self, trigger_pin, echo_pin, *, timeout=0.1):
        """
        :param trigger_pin: The pin on the microcontroller that's connected to the
            ``Trig`` pin on the HC-SR04.
        :type trig_pin: microcontroller.Pin
        :param echo_pin: The pin on the microcontroller that's connected to the
            ``Echo`` pin on the HC-SR04.
        :type echo_pin: microcontroller.Pin
        :param float timeout: 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!
        """
        self._timeout = timeout
        self._trig = DigitalInOut(trigger_pin)
        self._trig.direction = Direction.OUTPUT

        if _USE_PULSEIO:
            self._echo = PulseIn(echo_pin)
            self._echo.pause()
            self._echo.clear()
        else:
            self._echo = DigitalInOut(echo_pin)
            self._echo.direction = Direction.INPUT
Ejemplo n.º 13
0
	def __init__(self, rcPin, updateCallback = None):
		self._pulse = 1500 # center
		self.rc = PulseIn(rcPin, maxlen=16, idle_state=0)
		self.update_callback = updateCallback
Ejemplo n.º 14
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
Ejemplo n.º 15
0
class DHTBase:
    """base support for DHT11 and DHT22 devices

    :param bool 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 bool use_pulseio: False to force bitbang when pulseio available (only with Blinka)
    """

    __hiLevel = 51

    def __init__(self,
                 dht11: bool,
                 pin: Pin,
                 trig_wait: int,
                 use_pulseio: bool,
                 *,
                 max_pulses: int = 81):
        self._dht11 = dht11
        self._pin = pin
        self._trig_wait = trig_wait
        self._max_pulses = max_pulses
        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,
                                    maxlen=self._max_pulses,
                                    idle_state=True)
            self.pulse_in.pause()

    def exit(self) -> None:
        """Cleans up the PulseIn process. Must be called explicitly"""
        if self._use_pulseio:
            print("De-initializing self.pulse_in")
            self.pulse_in.deinit()

    def _pulses_to_binary(self, pulses: array.array, start: int,
                          stop: int) -> int:
        """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) -> array.array:
        """_get_pulses implements the communication protocol 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) -> array.array:
        """_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
            # Using the time to pull-down the line according to DHT Model
            time.sleep(self._trig_wait / 1000000)
            timestamp = time.monotonic()  # take timestamp
            dhtval = True  # start with dht pin true because its pulled up
            dhtpin.direction = Direction.INPUT

            try:
                dhtpin.pull = Pull.UP
            # Catch the NotImplementedError raised because
            # blinka.microcontroller.generic_linux.libgpiod_pin does not support
            # internal pull resistors.
            except NotImplementedError:
                dhtpin.pull = None

            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) - self._max_pulses)
            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) -> None:
        """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 insufficient
        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) -> Union[int, float, None]:
        """temperature current reading.  It makes sure a reading is available

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

    @property
    def humidity(self) -> Union[int, float, None]:
        """humidity current reading. It makes sure a reading is available

        Raises RuntimeError exception for checksum failure and for insufficient
        data returned from the device (try again)
        """
        self.measure()
        return self._humidity
Ejemplo n.º 16
0

# set up on-board LED
led = DigitalInOut(board.LED)
led.direction = Direction.OUTPUT

# set up serial UART to Raspberry Pi
# note UART(TX, RX, baudrate)
uart = busio.UART(board.TX1, board.RX1, baudrate=115200, timeout=0.001)

# set up servos
steering_pwm = PWMOut(board.SERVO2, duty_cycle=2 ** 15, frequency=60)
throttle_pwm = PWMOut(board.SERVO1, duty_cycle=2 ** 15, frequency=60)

# set up RC channels.  NOTE: input channels are RCC3 & RCC4 (not RCC1 & RCC2)
steering_channel = PulseIn(board.RCC4, maxlen=64, idle_state=0)
throttle_channel = PulseIn(board.RCC3, maxlen=64, idle_state=0)

# setup Control objects.  1500 pulse is off and center steering
steering = Control("Steering", steering_pwm, steering_channel, 1500)
throttle = Control("Throttle", throttle_pwm, throttle_channel, 1500)

# Hardware Notification: starting
logger.info("preparing to start...")
for i in range(0, 2):
    led.value = True
    time.sleep(0.5)
    led.value = False
    time.sleep(0.5)

last_update = time.monotonic()
from array import array

# set up on-board LED
led = DigitalInOut(board.LED)
led.direction = Direction.OUTPUT

# set up servos and radio control channels

pwm1 = PWMOut(board.SERVO1, duty_cycle=2**15, frequency=50)
pwm2 = PWMOut(board.SERVO2, duty_cycle=2**15, frequency=50)
#steering_servo = servo.Servo(pwm1)
#throttle_servo = servo.Servo(pwm2)
steering_servo = PulseOut(pwm1)
throttle_servo = PulseOut(pwm2)

steering_channel = PulseIn(board.RCH1)
throttle_channel = PulseIn(board.RCH2)


# functions
def get_voltage(pin):
    return (pin.value * 3.3) / 65536


def get_angle(time):
    return (time) / (18) + 7.5


def get_range(pulse):
    if 1540 < pulse < 1580:
        return 1566
Ejemplo n.º 18
0
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)
Ejemplo n.º 19
0
from adafruit_crickit import crickit
import time
from pulseio import PulseIn

pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.1)
pixels.fill((0, 0, 255))

# declare a crickit seesaw object
ss = crickit.seesaw

# declare a servo objet
servo = crickit.continuous_servo_1
servo.set_pulse_width_range(min_pulse=1220, max_pulse=1720)

# declare a pulseio object for the servo feedback
servo_fb = PulseIn(board.D5)

# declare four digital inputs
PIR = [crickit.SIGNAL1, crickit.SIGNAL2, crickit.SIGNAL3, crickit.SIGNAL4]
for pir in PIR:
    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
Ejemplo n.º 20
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"
Ejemplo n.º 21
0
#----G.Rougeaux 21 mars 2019------
import time
import board
import digitalio
from pulseio import PulseIn
from analogio import AnalogIn
pulses = PulseIn(board.D3, maxlen=2) # correspond a la patte OUT
lecture = AnalogIn(board.A0)
# -------------pilotage de la lumiere ----------------
led = digitalio.DigitalInOut(board.D2)
led.direction = digitalio.Direction.OUTPUT
led.value = False
# -----------config de la frequence -------------
# laisser la frequence la plus basse soit (S0,S1)=(0,1)
S0 = digitalio.DigitalInOut(board.D8)
S0.direction = digitalio.Direction.OUTPUT
S1 = digitalio.DigitalInOut(board.D9)
S1.direction = digitalio.Direction.OUTPUT
S0.value = False  # frequence 2%
S1.value = True
# 2% 0 1 - 20% 1 0 - 100 % 1 1 -coupure 0 0
# 1.3 kHz - 13 kHz  - 70 kHz 
# ------------config des filtres -----------------
S2 = digitalio.DigitalInOut(board.D10)
S2.direction = digitalio.Direction.OUTPUT
S3 = digitalio.DigitalInOut(board.D11)
S3.direction = digitalio.Direction.OUTPUT
S2.value = False  # red
S3.value = False
# red 0 0  - bleu 0 1 - green 1 1 - sans filtres 1 0
# --------------parametre du temps--------------
Ejemplo n.º 22
0
class GroveUltrasonicRanger:
    def __init__(self, sig_pin, unit=1.0, timeout=1.0):
        self.unit = unit
        self.timeout = timeout

        self.echo = PulseIn(sig_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 sig pin."""
        self.echo.deinit()

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

        return (self.echo[0] / 2) / (291 / 10)

    def distance(self):
        return self.dist_two_wire()