示例#1
0
class DS1307:
    """Interface to the DS1307 RTC."""

    disable_oscillator = i2c_bit.RWBit(0x0, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    def __init__(self, i2c_bus):
        self.i2c_device = I2CDevice(i2c_bus, 0x68)

        # Try and verify this is the RTC we expect by checking the rate select
        # control bits which are 1 on reset and shouldn't ever be changed.
        buf = bytearray(2)
        buf[0] = 0x07
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

        if (buf[1] & 0b00000011) != 0b00000011:
            raise ValueError("Unable to find DS1307 at i2c address 0x68.")

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time then starts the
           clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        self.disable_oscillator = False
        self.datetime_register = value
示例#2
0
class DS3231:
    """Interface to the DS3231 RTC."""

    lost_power = i2c_bit.RWBit(0x0f, 7)
    """True if the device has lost power since the time was set."""

    disable_oscillator = i2c_bit.RWBit(0x0e, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    alarm1 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x07)
    """Alarm time for the first alarm."""

    alarm1_interrupt = i2c_bit.RWBit(0x0e, 0)
    """True if the interrupt pin will output when alarm1 is alarming."""

    alarm1_status = i2c_bit.RWBit(0x0f, 0)
    """True if alarm1 is alarming. Set to False to reset."""

    alarm2 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0b, has_seconds=False)
    """Alarm time for the second alarm."""

    alarm2_interrupt = i2c_bit.RWBit(0x0e, 1)
    """True if the interrupt pin will output when alarm2 is alarming."""

    alarm2_status = i2c_bit.RWBit(0x0f, 1)
    """True if alarm2 is alarming. Set to False to reset."""

    def __init__(self, i2c):
        self.i2c_device = I2CDevice(i2c, 0x68)

        # Try and verify this is the RTC we expect by checking the rate select
        # control bits which are 1 on reset and shouldn't ever be changed.
        buf = bytearray(2)
        buf[0] = 0x0e
        with self.i2c_device as i2c_device:
            i2c_device.write(buf, end=1, stop=False)
            i2c_device.readinto(buf, start=1)

        if (buf[1] & 0b00011000) != 0b00011000:
            raise ValueError("Unable to find DS3231 at i2c address 0x68.")

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time
        then starts the clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        self.datetime_register = value
        self.disable_oscillator = False
        self.lost_power = False
示例#3
0
    class Chip:
        _r13b0 = i2c_bit.ROBit(0x13, 0)
        _r3fb0 = i2c_bit.RWBit(0x3f, 0)

        def __init__(self, i2c_bus):
            self.i2c_device = I2CDevice(i2c_bus, 0x68)

        def identify(self):
            Clock_chip = None
            chip = self._identity()
            log.message("Clock chip identified as {}".format(chip))
            if chip == 'DS3231':
                from adafruit_ds3231 import DS3231 as Clock_chip
            elif chip == 'DS1307':
                from adafruit_ds1307 import DS1307 as Clock_chip
            elif chip == 'PCF8523':
                from adafruit_pcf8523 import PCF8523 as Clock_chip
            else:
                log.message("Can not identify the device at i2c address 0x68")

            return Clock_chip

        def _identity(self):
            try:
                r13b0 = self._r13b0
            except OSError:
                dev_id = 'DS3231'
            else:
                try:
                    r3fb0 = self._r3fb0
                    self._r3fb0 = not r3fb0
                    if r3fb0 == self._r3fb0:
                        dev_id = 'PCF8523'
                    else:
                        dev_id = 'DS1307'
                        self._r3fb0 = r3fb0
                except OSError:
                    print("OSError accessing reg 0x3F")

            return dev_id
示例#4
0
class DS3231:
    """Interface to the DS3231 RTC."""

    lost_power = i2c_bit.RWBit(0x0F, 7)
    """True if the device has lost power since the time was set."""

    disable_oscillator = i2c_bit.RWBit(0x0E, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    alarm1 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x07)
    """Alarm time for the first alarm."""

    alarm1_interrupt = i2c_bit.RWBit(0x0E, 0)
    """True if the interrupt pin will output when alarm1 is alarming."""

    alarm1_status = i2c_bit.RWBit(0x0F, 0)
    """True if alarm1 is alarming. Set to False to reset."""

    alarm2 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0B, has_seconds=False)
    """Alarm time for the second alarm."""

    alarm2_interrupt = i2c_bit.RWBit(0x0E, 1)
    """True if the interrupt pin will output when alarm2 is alarming."""

    alarm2_status = i2c_bit.RWBit(0x0F, 1)
    """True if alarm2 is alarming. Set to False to reset."""

    def __init__(self, i2c):
        self.i2c_device = I2CDevice(i2c, 0x68)

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time
        then starts the clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        self.datetime_register = value
        self.disable_oscillator = False
        self.lost_power = False
示例#5
0
class AMG88XX:
    """Driver for the AMG88xx GRID-Eye IR 8x8 thermal camera."""

    # Set up the registers
    _pctl = i2c_bits.RWBits(8, 0x00, 0)
    _rst = i2c_bits.RWBits(8, 0x01, 0)
    _fps = i2c_bit.RWBit(0x02, 0)
    _inten = i2c_bit.RWBit(0x03, 0)
    _intmod = i2c_bit.RWBit(0x03, 1)

    _intf = i2c_bit.RWBit(0x04, 1)
    _ovf_irs = i2c_bit.RWBit(0x04, 2)
    _ovf_ths = i2c_bit.RWBit(0x04, 3)

    _intclr = i2c_bit.RWBit(0x05, 1)
    _ovs_clr = i2c_bit.RWBit(0x05, 2)
    _ovt_clr = i2c_bit.RWBit(0x05, 3)

    _mamod = i2c_bit.RWBit(0x07, 5)

    _inthl = i2c_bits.RWBits(8, 0x08, 0)
    _inthh = i2c_bits.RWBits(4, 0x09, 0)
    _intll = i2c_bits.RWBits(8, 0x0A, 0)
    _intlh = i2c_bits.RWBits(4, 0x0B, 0)
    _ihysl = i2c_bits.RWBits(8, 0x0C, 0)
    _ihysh = i2c_bits.RWBits(4, 0x0D, 0)

    _tthl = i2c_bits.RWBits(8, 0x0E, 0)

    _tthh = i2c_bits.RWBits(4, 0x0F, 0)

    def __init__(self, i2c, addr=0x69):
        self.i2c_device = I2CDevice(i2c, addr)

        # enter normal mode
        self._pctl = _NORMAL_MODE

        # software reset
        self._rst = _INITIAL_RESET

        # disable interrupts by default
        self._inten = False

        # set to 10 FPS
        self._fps = _FPS_10

    @property
    def temperature(self):
        """Temperature of the sensor in Celsius"""
        raw = (self._tthh << 8) | self._tthl
        return _signed_12bit_to_float(raw) * _THERMISTOR_CONVERSION

    @property
    def pixels(self):
        """Temperature of each pixel across the sensor in Celsius.

           Temperatures are stored in a two dimensional list where the first index is the row and
           the second is the column. The first row is on the side closest to the writing on the
           sensor."""
        retbuf = [[0] * _PIXEL_ARRAY_WIDTH for _ in range(_PIXEL_ARRAY_HEIGHT)]
        buf = bytearray(3)

        with self.i2c_device as i2c:
            for row in range(0, _PIXEL_ARRAY_HEIGHT):
                for col in range(0, _PIXEL_ARRAY_WIDTH):
                    i = row * _PIXEL_ARRAY_HEIGHT + col
                    buf[0] = _PIXEL_OFFSET + (i << 1)
                    i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

                    raw = (buf[2] << 8) | buf[1]
                    retbuf[row][col] = _twos_comp_to_float(
                        raw) * _PIXEL_TEMP_CONVERSION

        return retbuf
示例#6
0
class CCS811:
    """CCS811 gas sensor driver.

    :param ~busio.I2C i2c: The I2C bus.
    :param int addr: The I2C address of the CCS811.
    """

    # set up the registers
    error = i2c_bit.ROBit(0x00, 0)
    """True when an error has occured."""
    data_ready = i2c_bit.ROBit(0x00, 3)
    """True when new data has been read."""
    app_valid = i2c_bit.ROBit(0x00, 4)
    fw_mode = i2c_bit.ROBit(0x00, 7)

    hw_id = i2c_bits.ROBits(8, 0x20, 0)

    int_thresh = i2c_bit.RWBit(0x01, 2)
    interrupt_enabled = i2c_bit.RWBit(0x01, 3)
    drive_mode = i2c_bits.RWBits(3, 0x01, 4)

    temp_offset = 0.0
    """Temperature offset."""
    def __init__(self, i2c_bus, address=0x5A):
        self.i2c_device = I2CDevice(i2c_bus, address)

        # check that the HW id is correct
        if self.hw_id != _HW_ID_CODE:
            raise RuntimeError(
                "Device ID returned is not correct! Please check your wiring.")

        # try to start the app
        buf = bytearray(1)
        buf[0] = 0xF4
        with self.i2c_device as i2c:
            i2c.write(buf, end=1)
        time.sleep(0.1)

        # make sure there are no errors and we have entered application mode
        if self.error:
            raise RuntimeError(
                "Device returned a error! Try removing and reapplying power to "
                "the device and running the code again.")
        if not self.fw_mode:
            raise RuntimeError(
                "Device did not enter application mode! If you got here, there may "
                "be a problem with the firmware on your sensor.")

        self.interrupt_enabled = False

        # default to read every second
        self.drive_mode = DRIVE_MODE_1SEC

        self._eco2 = None  # pylint: disable=invalid-name
        self._tvoc = None  # pylint: disable=invalid-name

    @property
    def error_code(self):
        """Error code"""
        buf = bytearray(2)
        buf[0] = 0xE0
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)
        return buf[1]

    def _update_data(self):
        if self.data_ready:
            buf = bytearray(9)
            buf[0] = _ALG_RESULT_DATA
            with self.i2c_device as i2c:
                i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

            self._eco2 = (buf[1] << 8) | (buf[2])
            self._tvoc = (buf[3] << 8) | (buf[4])

            if self.error:
                raise RuntimeError("Error:" + str(self.error_code))

    @property
    def tvoc(self):  # pylint: disable=invalid-name
        """Total Volatile Organic Compound in parts per billion."""
        self._update_data()
        return self._tvoc

    @property
    def eco2(self):  # pylint: disable=invalid-name
        """Equivalent Carbon Dioxide in parts per million. Clipped to 400 to 8192ppm."""
        self._update_data()
        return self._eco2

    @property
    def temperature(self):
        """
        .. deprecated:: 1.1.5
           Hardware support removed by vendor

        Temperature based on optional thermistor in Celsius."""
        buf = bytearray(5)
        buf[0] = _NTC
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

        vref = (buf[1] << 8) | buf[2]
        vntc = (buf[3] << 8) | buf[4]

        # From ams ccs811 app note 000925
        # https://download.ams.com/content/download/9059/13027/version/1/file/CCS811_Doc_cAppNote-Connecting-NTC-Thermistor_AN000372_v1..pdf
        rntc = float(vntc) * _REF_RESISTOR / float(vref)

        ntc_temp = math.log(rntc / 10000.0)
        ntc_temp /= 3380.0
        ntc_temp += 1.0 / (25 + 273.15)
        ntc_temp = 1.0 / ntc_temp
        ntc_temp -= 273.15
        return ntc_temp - self.temp_offset

    def set_environmental_data(self, humidity, temperature):
        """Set the temperature and humidity used when computing eCO2 and TVOC values.

        :param int humidity: The current relative humidity in percent.
        :param float temperature: The current temperature in Celsius."""
        # Humidity is stored as an unsigned 16 bits in 1/512%RH. The default
        # value is 50% = 0x64, 0x00. As an example 48.5% humidity would be 0x61,
        # 0x00.
        humidity = int(humidity * 512)

        # Temperature is stored as an unsigned 16 bits integer in 1/512 degrees
        # there is an offset: 0 maps to -25C. The default value is 25C = 0x64,
        # 0x00. As an example 23.5% temperature would be 0x61, 0x00.
        temperature = int((temperature + 25) * 512)

        buf = bytearray(5)
        buf[0] = _ENV_DATA
        struct.pack_into(">HH", buf, 1, humidity, temperature)

        with self.i2c_device as i2c:
            i2c.write(buf)

    def set_interrupt_thresholds(self, low_med, med_high, hysteresis):
        """Set the thresholds used for triggering the interrupt based on eCO2.
        The interrupt is triggered when the value crossed a boundary value by the
        minimum hysteresis value.

        :param int low_med: Boundary between low and medium ranges
        :param int med_high: Boundary between medium and high ranges
        :param int hysteresis: Minimum difference between reads"""
        buf = bytearray([
            _THRESHOLDS,
            ((low_med >> 8) & 0xF),
            (low_med & 0xF),
            ((med_high >> 8) & 0xF),
            (med_high & 0xF),
            hysteresis,
        ])
        with self.i2c_device as i2c:
            i2c.write(buf)

    def reset(self):
        """Initiate a software reset."""
        # reset sequence from the datasheet
        seq = bytearray([_SW_RESET, 0x11, 0xE5, 0x72, 0x8A])
        with self.i2c_device as i2c:
            i2c.write(seq)
class CCS811:
    """CCS811 gas sensor driver.

    :param ~busio.I2C i2c: The I2C bus.
    :param int addr: The I2C address of the CCS811.
    """

    # set up the registers
    error = i2c_bit.ROBit(0x00, 0)
    """True when an error has occured."""
    data_ready = i2c_bit.ROBit(0x00, 3)
    """True when new data has been read."""
    app_valid = i2c_bit.ROBit(0x00, 4)
    fw_mode = i2c_bit.ROBit(0x00, 7)

    hw_id = i2c_bits.ROBits(8, 0x20, 0)

    int_thresh = i2c_bit.RWBit(0x01, 2)
    interrupt_enabled = i2c_bit.RWBit(0x01, 3)
    drive_mode = i2c_bits.RWBits(3, 0x01, 4)

    def __init__(self, i2c_bus, address=0x5A):
        self.i2c_device = I2CDevice(i2c_bus, address)

        # check that the HW id is correct
        if self.hw_id != _HW_ID_CODE:
            raise RuntimeError(
                "Device ID returned is not correct! Please check your wiring.")
        # reset before starting
        Print("Reseting")
        self.reset()
        time.sleep(10)

        # try to start the app
        buf = bytearray(1)
        buf[0] = 0xF4
        with self.i2c_device as i2c:
            i2c.write(buf, end=1)
        time.sleep(10)

        # make sure there are no errors and we have entered application mode
        if self.error:
            raise RuntimeError(
                "Device returned a error! Try removing and reapplying power to "
                "the device and running the code again.")
        if not self.fw_mode:
            raise RuntimeError(
                "Device did not enter application mode! If you got here, there may "
                "be a problem with the firmware on your sensor.")

        self.interrupt_enabled = False

        # default to read every minute
        self.drive_mode = DRIVE_MODE_60SEC

        self._eco2 = None  # pylint: disable=invalid-name
        self._tvoc = None  # pylint: disable=invalid-name

    @property
    def error_code(self):
        """Error code"""
        buf = bytearray(2)
        buf[0] = 0xE0
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)
        return buf[1]

    def _update_data(self):
        if self.data_ready:
            buf = bytearray(9)
            buf[0] = _ALG_RESULT_DATA
            with self.i2c_device as i2c:
                i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

            self._eco2 = (buf[1] << 8) | (buf[2])
            self._tvoc = (buf[3] << 8) | (buf[4])

            if self.error:
                raise RuntimeError("Error:" + str(self.error_code))

    @property
    def baseline(self):
        """
        The propery reads and returns the current baseline value.
        The returned value is packed into an integer.
        Later the same integer can be used in order
        to set a new baseline.
        """
        buf = bytearray(3)
        buf[0] = _BASELINE
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)
        return struct.unpack("<H", buf[1:])[0]

    @baseline.setter
    def baseline(self, baseline_int):
        """
        The property lets you set a new baseline. As a value accepts
        integer which represents packed baseline 2 bytes value.
        """
        buf = bytearray(3)
        buf[0] = _BASELINE
        struct.pack_into("<H", buf, 1, baseline_int)
        with self.i2c_device as i2c:
            i2c.write(buf)

    @property
    def tvoc(self):  # pylint: disable=invalid-name
        """Total Volatile Organic Compound in parts per billion."""
        self._update_data()
        return self._tvoc

    @property
    def eco2(self):  # pylint: disable=invalid-name
        """Equivalent Carbon Dioxide in parts per million. Clipped to 400 to 8192ppm."""
        self._update_data()
        return self._eco2

    def set_mode(self, mode):  # change operating mode
        print("Idle for 20min before changing to new mode")
        self.drive_mode = DRIVE_MODE_IDLE
        time.sleep(1200)
        self.drive_mode = mode

    def set_environmental_data(self, humidity, temperature):
        """Set the temperature and humidity used when computing eCO2 and TVOC values.

        :param int humidity: The current relative humidity in percent.
        :param float temperature: The current temperature in Celsius."""
        # Humidity is stored as an unsigned 16 bits in 1/512%RH. The default
        # value is 50% = 0x64, 0x00. As an example 48.5% humidity would be 0x61,
        # 0x00.
        humidity = int(humidity * 512)

        # Temperature is stored as an unsigned 16 bits integer in 1/512 degrees
        # there is an offset: 0 maps to -25C. The default value is 25C = 0x64,
        # 0x00. As an example 23.5% temperature would be 0x61, 0x00.
        temperature = int((temperature + 25) * 512)

        buf = bytearray(5)
        buf[0] = _ENV_DATA
        struct.pack_into(">HH", buf, 1, humidity, temperature)

        with self.i2c_device as i2c:
            i2c.write(buf)

    def set_interrupt_thresholds(self, low_med, med_high, hysteresis):
        """Set the thresholds used for triggering the interrupt based on eCO2.
        The interrupt is triggered when the value crossed a boundary value by the
        minimum hysteresis value.

        :param int low_med: Boundary between low and medium ranges
        :param int med_high: Boundary between medium and high ranges
        :param int hysteresis: Minimum difference between reads"""
        buf = bytearray([
            _THRESHOLDS,
            ((low_med >> 8) & 0xF),
            (low_med & 0xF),
            ((med_high >> 8) & 0xF),
            (med_high & 0xF),
            hysteresis,
        ])
        with self.i2c_device as i2c:
            i2c.write(buf)

    def reset(self):
        """Initiate a software reset."""
        # reset sequence from the datasheet
        seq = bytearray([_SW_RESET, 0x11, 0xE5, 0x72, 0x8A])
        with self.i2c_device as i2c:
            i2c.write(seq)
示例#8
0
class DS3231:
    """Interface to the DS3231 RTC."""

    lost_power = i2c_bit.RWBit(0x0F, 7)
    """True if the device has lost power since the time was set."""

    disable_oscillator = i2c_bit.RWBit(0x0E, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    alarm1 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x07)
    """Alarm time for the first alarm."""

    alarm1_interrupt = i2c_bit.RWBit(0x0E, 0)
    """True if the interrupt pin will output when alarm1 is alarming."""

    alarm1_status = i2c_bit.RWBit(0x0F, 0)
    """True if alarm1 is alarming. Set to False to reset."""

    alarm2 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0B, has_seconds=False)
    """Alarm time for the second alarm."""

    alarm2_interrupt = i2c_bit.RWBit(0x0E, 1)
    """True if the interrupt pin will output when alarm2 is alarming."""

    alarm2_status = i2c_bit.RWBit(0x0F, 1)
    """True if alarm2 is alarming. Set to False to reset."""

    _calibration = i2c_bits.RWBits(8, 0x10, 0, 8, signed=True)

    _temperature = i2c_bits.RWBits(
        10, 0x11, 6, register_width=2, lsb_first=False, signed=True
    )

    _busy = i2c_bit.ROBit(0x0F, 2)
    _conv = i2c_bit.RWBit(0x0E, 5)

    def __init__(self, i2c):
        self.i2c_device = I2CDevice(i2c, 0x68)

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time
        then starts the clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        self.datetime_register = value
        self.disable_oscillator = False
        self.lost_power = False

    @property
    def temperature(self):
        """Returns the last temperature measurement.  Temperature is updated
        only every 64 seconds, or when a conversion is forced."""
        return self._temperature / 4

    def force_temperature_conversion(self):
        """Forces a conversion and returns the new temperature"""
        while self._busy:
            pass  # Wait for any normal in-progress conversion to complete
        self._conv = True
        while self._conv:
            pass  # Wait for manual conversion request to complete
        return self.temperature

    @property
    def calibration(self):
        """Calibrate the frequency of the crystal oscillator by adding or
        removing capacitance.  The datasheet calls this the Aging Offset.
        Calibration values range from -128 to 127; each step is approximately
        0.1ppm, and positive values decrease the frequency (increase the
        period).  When set, a temperature conversion is forced so the result of
        calibration can be seen directly at the 32kHz pin immediately"""
        return self._calibration

    @calibration.setter
    def calibration(self, value):
        self._calibration = value
        self.force_temperature_conversion()
class PCF8523:
    """Interface to the PCF8523 RTC."""

    lost_power = i2c_bit.RWBit(0x03, 7)
    """True if the device has lost power since the time was set."""

    power_management = i2c_bits.RWBits(3, 0x02, 5)
    """Power management state that dictates battery switchover, power sources
    and low battery detection. Defaults to BATTERY_SWITCHOVER_OFF (0b000)."""

    # The False means that day comes before weekday in the registers. The 0 is
    # that the first day of the week is value 0 and not 1.
    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x03, False, 0)
    """Current date and time."""

    # The False means that day and weekday share a register. The 0 is that the
    # first day of the week is value 0 and not 1.
    alarm = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0A,
                                               has_seconds=False,
                                               weekday_shared=False,
                                               weekday_start=0)
    """Alarm time for the first alarm."""

    alarm_interrupt = i2c_bit.RWBit(0x00, 1)
    """True if the interrupt pin will output when alarm is alarming."""

    alarm_status = i2c_bit.RWBit(0x01, 3)
    """True if alarm is alarming. Set to False to reset."""

    battery_low = i2c_bit.ROBit(0x02, 2)
    """True if the battery is low and should be replaced."""

    high_capacitance = i2c_bit.RWBit(0x00, 7)
    """True for high oscillator capacitance (12.5pF), otherwise lower (7pF)"""

    calibration_schedule_per_minute = i2c_bit.RWBit(0x0E, 7)
    """False to apply the calibration offset every 2 hours (1 LSB = 4.340ppm);
    True to offset every minute (1 LSB = 4.069ppm).  The default, False,
    consumes less power.  See datasheet figures 28-31 for details."""

    calibration = i2c_bits.RWBits(7, 0xE, 0, signed=True)
    """Calibration offset to apply, from -64 to +63.  See the PCF8523 datasheet
    figure 18 for the offset calibration calculation workflow."""
    def __init__(self, i2c_bus):
        self.i2c_device = I2CDevice(i2c_bus, 0x68)

        # Try and verify this is the RTC we expect by checking the timer B
        # frequency control bits which are 1 on reset and shouldn't ever be
        # changed.
        buf = bytearray(2)
        buf[0] = 0x12
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

        if (buf[1] & 0b00000111) != 0b00000111:
            raise ValueError("Unable to find PCF8523 at i2c address 0x68.")

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time then starts the
           clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        # Automatically sets lost_power to false.
        self.power_management = STANDARD_BATTERY_SWITCHOVER_AND_DETECTION
        self.datetime_register = value
class PCF8523:
    """Interface to the PCF8523 RTC.

    :param ~busio.I2C i2c_bus: The I2C bus the device is connected to

    **Quickstart: Importing and using the device**

        Here is an example of using the :class:`PCF8523` class.
        First you will need to import the libraries to use the sensor

        .. code-block:: python

            import time
            import board
            import adafruit_pcf8523

        Once this is done you can define your `board.I2C` object and define your sensor object

        .. code-block:: python

            i2c = board.I2C()  # uses board.SCL and board.SDA
            rtc = adafruit_pcf8523.PCF8523(i2c)

        Now you can give the current time to the device.

        .. code-block:: python

            t = time.struct_time((2017, 10, 29, 15, 14, 15, 0, -1, -1))
            rtc.datetime = t

        You can access the current time accessing the :attr:`datetime` attribute.

        .. code-block:: python

            current_time = rtc.datetime

    """

    lost_power = i2c_bit.RWBit(0x03, 7)
    """True if the device has lost power since the time was set."""

    power_management = i2c_bits.RWBits(3, 0x02, 5)
    """Power management state that dictates battery switchover, power sources
    and low battery detection. Defaults to BATTERY_SWITCHOVER_OFF (0b000)."""

    # The False means that day comes before weekday in the registers. The 0 is
    # that the first day of the week is value 0 and not 1.
    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x03, False, 0)
    """Current date and time."""

    # The False means that day and weekday share a register. The 0 is that the
    # first day of the week is value 0 and not 1.
    alarm = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0A,
                                               has_seconds=False,
                                               weekday_shared=False,
                                               weekday_start=0)
    """Alarm time for the first alarm."""

    alarm_interrupt = i2c_bit.RWBit(0x00, 1)
    """True if the interrupt pin will output when alarm is alarming."""

    alarm_status = i2c_bit.RWBit(0x01, 3)
    """True if alarm is alarming. Set to False to reset."""

    battery_low = i2c_bit.ROBit(0x02, 2)
    """True if the battery is low and should be replaced."""

    high_capacitance = i2c_bit.RWBit(0x00, 7)
    """True for high oscillator capacitance (12.5pF), otherwise lower (7pF)"""

    calibration_schedule_per_minute = i2c_bit.RWBit(0x0E, 7)
    """False to apply the calibration offset every 2 hours (1 LSB = 4.340ppm);
    True to offset every minute (1 LSB = 4.069ppm).  The default, False,
    consumes less power.  See datasheet figures 28-31 for details."""

    calibration = i2c_bits.RWBits(  # pylint: disable=unexpected-keyword-arg
        7, 0xE, 0, signed=True)
    """Calibration offset to apply, from -64 to +63.  See the PCF8523 datasheet
    figure 18 for the offset calibration calculation workflow."""
    def __init__(self, i2c_bus: I2C):
        self.i2c_device = I2CDevice(i2c_bus, 0x68)

        # Try and verify this is the RTC we expect by checking the timer B
        # frequency control bits which are 1 on reset and shouldn't ever be
        # changed.
        buf = bytearray(2)
        buf[0] = 0x12
        with self.i2c_device as i2c:
            i2c.write_then_readinto(buf, buf, out_end=1, in_start=1)

        if (buf[1] & 0b00000111) != 0b00000111:
            raise ValueError("Unable to find PCF8523 at i2c address 0x68.")

    @property
    def datetime(self) -> struct_time:
        """Gets the current date and time or sets the current date and time then starts the
        clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value: struct_time):
        # Automatically sets lost_power to false.
        self.power_management = STANDARD_BATTERY_SWITCHOVER_AND_DETECTION
        self.datetime_register = value
class Encoder:
    def __init__(self, i2c, device_address):
        self.i2c_device = I2CDevice(i2c, device_address)

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False

    # GCONF
    gconf_dtype = i2c_bit.RWBit(_REG_GCONF, 0x00)
    gconf_wrape = i2c_bit.RWBit(_REG_GCONF, 0x01)
    gconf_dire = i2c_bit.RWBit(_REG_GCONF, 0x02)
    gconf_ipud = i2c_bit.RWBit(_REG_GCONF, 0x03)
    gconf_rmod = i2c_bit.RWBit(_REG_GCONF, 0x04)
    gconf_etype = i2c_bit.RWBit(_REG_GCONF, 0x05)
    gconf_mbank = i2c_bit.RWBit(_REG_GCONF, 0x06)
    gconf_rst = i2c_bit.RWBit(_REG_GCONF, 0x07)

    # GCONF2
    gconf2_cksrc = i2c_bit.RWBit(_REG_GCONF, 0x00)
    gconf2_relmod = i2c_bit.RWBit(_REG_GCONF, 0x01)

    # GP1CONF
    gp1conf = i2c_bits.RWBits(8, _REG_GP1CONF, 0x00)
    gp1conf_mode = i2c_bits.RWBits(2, _REG_GP1CONF, 0x00)
    gp1conf_pul = i2c_bit.RWBit(_REG_GP1CONF, 0x02)
    gp1conf_int = i2c_bits.RWBits(2, _REG_GP1CONF, 0x03)

    # GP2CONF
    gp2conf = i2c_bits.RWBits(8, _REG_GP2CONF, 0x00)
    gp2conf_mode = i2c_bits.RWBits(2, _REG_GP2CONF, 0x00)
    gp2conf_pul = i2c_bit.RWBit(_REG_GP2CONF, 0x02)
    gp2conf_int = i2c_bits.RWBits(2, _REG_GP2CONF, 0x03)

    # GP3CONF
    gp3conf = i2c_bits.RWBits(8, _REG_GP3CONF, 0x00)
    gp3conf_mode = i2c_bits.RWBits(2, _REG_GP3CONF, 0x00)
    gp3conf_pul = i2c_bit.RWBit(_REG_GP3CONF, 0x02)
    gp3conf_int = i2c_bits.RWBits(2, _REG_GP3CONF, 0x03)

    # INTCONF
    intconf_ipushr = i2c_bit.RWBit(_REG_INTCONF, 0x00)
    intconf_ipushp = i2c_bit.RWBit(_REG_INTCONF, 0x01)
    intconf_ipushd = i2c_bit.RWBit(_REG_INTCONF, 0x02)
    intconf_irinc = i2c_bit.RWBit(_REG_INTCONF, 0x03)
    intconf_irdec = i2c_bit.RWBit(_REG_INTCONF, 0x04)
    intconf_irmax = i2c_bit.RWBit(_REG_INTCONF, 0x05)
    intconf_irmin = i2c_bit.RWBit(_REG_INTCONF, 0x06)
    intconf_int2 = i2c_bit.RWBit(_REG_INTCONF, 0x07)

    # ESTATUS - TODO: Break this into a set of flags
    estatus = i2c_bits.ROBits(8, _REG_ESTATUS, 0x00)

    # I2STATUS - TODO: Break this into a set of flags
    i2status = i2c_bits.ROBits(8, _REG_I2STATUS, 0x00)

    # FSTATUS - TODO: Break this into a set of flags
    fstatus = i2c_bits.ROBits(8, _REG_FSTATUS, 0x00)

    # CVAL FLOAT
    cval_float = i2c_struct.UnaryStruct(_REG_CVAL, ">f")

    # CVAL LONG
    cval_long = i2c_struct.UnaryStruct(_REG_CVAL, ">l")

    # CMAX FLOAT
    cmax_float = i2c_struct.UnaryStruct(_REG_CMAX, ">f")

    # CMAX LONG
    cmax_long = i2c_struct.UnaryStruct(_REG_CMAX, ">l")

    # CMIN FLOAT
    cmin_float = i2c_struct.UnaryStruct(_REG_CMIN, ">f")

    # CMIN LONG
    cmin_long = i2c_struct.UnaryStruct(_REG_CMIN, ">l")

    # ISTEP FLOAT
    istep_float = i2c_struct.UnaryStruct(_REG_ISTEP, ">f")

    # ISTEP INT
    istep_long = i2c_struct.UnaryStruct(_REG_ISTEP, ">l")

    # R/G/B LED
    rled = i2c_bits.RWBits(8, _REG_RLED, 0x00)
    gled = i2c_bits.RWBits(8, _REG_GLED, 0x00)
    bled = i2c_bits.RWBits(8, _REG_BLED, 0x00)

    # GP 1/2/3
    gp1 = i2c_bits.RWBits(8, _REG_GP1, 0x00)
    gp2 = i2c_bits.RWBits(8, _REG_GP2, 0x00)
    gp3 = i2c_bits.RWBits(8, _REG_GP3, 0x00)

    # ANTI BOUNCE
    antbounc = i2c_bits.RWBits(8, _REG_ANTBOUNC, 0x00)

    # DP PERIOD
    dpperiod = i2c_bits.RWBits(8, _REG_DPPERIOD, 0x00)

    # FADE RGB
    fadergb = i2c_bits.RWBits(8, _REG_FADERGB, 0x00)

    # FADE GP
    fadegp = i2c_bits.RWBits(8, _REG_FADEGP, 0x00)

    # GAMMA R/G/B
    gamrled = i2c_bits.RWBits(3, _REG_GAMRLED, 0x00)
    gamgled = i2c_bits.RWBits(3, _REG_GAMGLED, 0x00)
    gambled = i2c_bits.RWBits(3, _REG_GAMBLED, 0x00)

    # GAMMA GP 1/2/3
    gammagp1 = i2c_bits.RWBits(3, _REG_GAMMAGP1, 0x00)
    gammagp2 = i2c_bits.RWBits(3, _REG_GAMMAGP2, 0x00)
    gammagp3 = i2c_bits.RWBits(3, _REG_GAMMAGP3, 0x00)

    # ID CODE
    idcode = i2c_bits.ROBits(8, _REG_IDCODE, 0x00)

    # VERSION
    version = i2c_bits.ROBits(8, _REG_VERSION, 0x00)

    # EEPROM
    eeprom = i2c_bits.ROBits(1024, _REG_EEPROM, 0x00, register_width=128)
class DS3231:
    """Interface to the DS3231 RTC.

    :param ~busio.I2C i2c: The I2C bus the device is connected to

    **Quickstart: Importing and using the device**

        Here is an example of using the :class:`DS3231` class.
        First you will need to import the libraries to use the sensor

        .. code-block:: python

            import time
            import board
            import adafruit_ds3231

        Once this is done you can define your `board.I2C` object and define your sensor object

        .. code-block:: python

            i2c = board.I2C()  # uses board.SCL and board.SDA
            rtc = adafruit_ds3231.DS3231(i2c)

        Now you can give the current time to the device.

        .. code-block:: python

            t = time.struct_time((2017, 10, 29, 15, 14, 15, 0, -1, -1))
            rtc.datetime = t

        You can access the current time accessing the :attr:`datetime` attribute.

        .. code-block:: python

            current_time = rtc.datetime

    """

    lost_power = i2c_bit.RWBit(0x0F, 7)
    """True if the device has lost power since the time was set."""

    disable_oscillator = i2c_bit.RWBit(0x0E, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    alarm1 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x07)
    """Alarm time for the first alarm."""

    alarm1_interrupt = i2c_bit.RWBit(0x0E, 0)
    """True if the interrupt pin will output when alarm1 is alarming."""

    alarm1_status = i2c_bit.RWBit(0x0F, 0)
    """True if alarm1 is alarming. Set to False to reset."""

    alarm2 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0B, has_seconds=False)
    """Alarm time for the second alarm."""

    alarm2_interrupt = i2c_bit.RWBit(0x0E, 1)
    """True if the interrupt pin will output when alarm2 is alarming."""

    alarm2_status = i2c_bit.RWBit(0x0F, 1)
    """True if alarm2 is alarming. Set to False to reset."""

    # pylint: disable=unexpected-keyword-arg
    _calibration = i2c_bits.RWBits(8, 0x10, 0, 1, signed=True)

    _temperature = i2c_bits.RWBits(
        10, 0x11, 6, register_width=2, lsb_first=False, signed=True
    )
    # pylint: enable=unexpected-keyword-arg

    _busy = i2c_bit.ROBit(0x0F, 2)
    _conv = i2c_bit.RWBit(0x0E, 5)

    def __init__(self, i2c: I2C) -> None:
        self.i2c_device = I2CDevice(i2c, 0x68)

    @property
    def datetime(self) -> struct_time:
        """Gets the current date and time or sets the current date and time
        then starts the clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value: struct_time) -> None:
        self.datetime_register = value
        self.disable_oscillator = False
        self.lost_power = False

    @property
    def temperature(self) -> float:
        """Returns the last temperature measurement.  Temperature is updated
        only every 64 seconds, or when a conversion is forced."""
        return self._temperature / 4

    def force_temperature_conversion(self) -> float:
        """Forces a conversion and returns the new temperature"""
        while self._busy:
            pass  # Wait for any normal in-progress conversion to complete
        self._conv = True
        while self._conv:
            pass  # Wait for manual conversion request to complete
        return self.temperature

    @property
    def calibration(self) -> int:
        """Calibrate the frequency of the crystal oscillator by adding or
        removing capacitance.  The datasheet calls this the Aging Offset.
        Calibration values range from -128 to 127; each step is approximately
        0.1ppm, and positive values decrease the frequency (increase the
        period).  When set, a temperature conversion is forced so the result of
        calibration can be seen directly at the 32kHz pin immediately"""
        return self._calibration

    @calibration.setter
    def calibration(self, value: int) -> None:
        self._calibration = value
        self.force_temperature_conversion()
示例#13
0
class PCF8523:
    """Interface to the PCF8523 RTC."""

    lost_power = i2c_bit.RWBit(0x03, 7)
    """True if the device has lost power since the time was set."""

    disable_oscillator = i2c_bit.RWBit(0x00, 5)
    """True if the oscillator is disabled."""

    _square_wave_control = i2c_bits.RWBits(3, 0x0F, 3)
    """reg 0x0F, bits 3:5 identify the square wave frequency"""

    _r13b0 = i2c_bit.ROBit(0x13, 0)
    """reg 0x13, bit 0 used to distinguish ds3231"""
    _r3fb0 = i2c_bit.RWBit(0x3f, 0)
    """reg 0x3f, bit 0 used to distinguish between ds1307 and pcf8523"""

    power_management = i2c_bits.RWBits(3, 0x02, 5)
    """Power management state that dictates battery switchover, power sources
    and low battery detection. Defaults to BATTERY_SWITCHOVER_OFF (0b111)."""

    # The False means that day comes before weekday in the registers. The 0 is
    # that the first day of the week is value 0 and not 1.
    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x03, False, 0)
    """Current date and time."""

    # The False means that day and weekday share a register. The 0 is that the
    # first day of the week is value 0 and not 1.
    alarm = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0A,
                                               has_seconds=False,
                                               weekday_shared=False,
                                               weekday_start=0)
    """Alarm time for the first alarm."""

    alarm_interrupt = i2c_bit.RWBit(0x00, 1)
    """True if the interrupt pin will output when alarm is alarming."""

    alarm_status = i2c_bit.RWBit(0x01, 3)
    """True if alarm is alarming. Set to False to reset."""

    battery_low = i2c_bit.ROBit(0x02, 2)
    """True if the battery is low and should be replaced."""

    high_capacitance = i2c_bit.RWBit(0x00, 7)
    """True for high oscillator capacitance (12.5pF), otherwise lower (7pF)"""

    calibration_schedule_per_minute = i2c_bit.RWBit(0x0E, 7)
    """False to apply the calibration offset every 2 hours (1 LSB = 4.340ppm);
    True to offset every minute (1 LSB = 4.069ppm).  The default, False,
    consumes less power.  See datasheet figures 28-31 for details."""

    calibration = i2c_bits.RWBits(  # pylint: disable=unexpected-keyword-arg
        7, 0xE, 0, signed=True)
    """Calibration offset to apply, from -64 to +63.  See the PCF8523 datasheet
    figure 18 for the offset calibration calculation workflow."""
    def __init__(self, i2c_bus):
        self.i2c_device = I2CDevice(i2c_bus, 0x68)
        chip = self.chip_identity
        expected = self.__class__.__name__
        if chip != expected:
            raise RuntimeError(
                'Expected {}, found {} at i2c address 0x68'.format(
                    expected, chip))

    @property
    def chip_identity(self):
        """identify the RTC chip (distinguishes among DS1307, PCF8523 and DS3231)"""
        try:
            r13b0 = self._r13b0
        except OSError:
            return 'DS3231'
        else:
            r3fb0 = self._r3fb0
            self._r3fb0 = not r3fb0
            if r3fb0 != self._r3fb0:
                self._r3fb0 = r3fb0
                return 'DS1307'
        return 'PCF8523'

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time then starts the
        clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        # Required to enable switching to battery
        self.power_management = STANDARD_BATTERY_SWITCHOVER_AND_DETECTION
        # Automatically sets lost_power to false.
        self.datetime_register = value
        self.disable_oscillator = False

    @property
    def square_wave_frequency(self):
        """Return the square wave frequency, 0 if not enabled"""
        value = self._square_wave_control
        freqs = (1, 32, 1024, 4096, 8192, 16384, 32768, 0)
        return freqs[value]

    @square_wave_frequency.setter
    def square_wave_frequency(self, frequency):
        available_frequencies = {
            0: 7,
            1: 6,
            32: 5,
            1024: 4,
            4096: 3,
            8192: 2,
            16384: 1,
            32768: 0
        }
        try:
            code = available_frequencies[frequency]
            self._square_wave_control = code
        except KeyError:
            raise ValueError(
                'square wave frequency {} not available'.format(frequency))
class Adafruit_CCS811:
    #set up the registers
    #self.status = Adafruit_bitfield([('ERROR' , 1), ('unused', 2), ('DATA_READY' , 1), ('APP_VALID', 1), ('unused2' , 2), ('FW_MODE' , 1)])
    error = i2c_bit.ROBit(0x00, 0)
    data_ready = i2c_bit.ROBit(0x00, 3)
    app_valid = i2c_bit.ROBit(0x00, 4)
    fw_mode = i2c_bit.ROBit(0x00, 7)

    hw_id = i2c_bits.ROBits(8, 0x20, 0)

    #self.meas_mode = Adafruit_bitfield([('unused', 2), ('INT_THRESH', 1), ('INT_DATARDY', 1), ('DRIVE_MODE', 3)])
    int_thresh = i2c_bit.RWBit(0x01, 2)
    interrupt_enabled = i2c_bit.RWBit(0x01, 3)
    drive_mode = i2c_bits.RWBits(3, 0x01, 4)

    #self.error_id = Adafruit_bitfield([('WRITE_REG_INVALID', 1), ('READ_REG_INVALID', 1), ('MEASMODE_INVALID', 1), ('MAX_RESISTANCE', 1), ('HEATER_FAULT', 1), ('HEATER_SUPPLY', 1)])

    TVOC = 0
    eCO2 = 0

    tempOffset = 0.0

    def __init__(self, i2c, addr=0x5A):
        self.i2c_device = I2CDevice(i2c, addr)

        #check that the HW id is correct
        if self.hw_id != CCS811_HW_ID_CODE:
            raise RuntimeError(
                "Device ID returned is not correct! Please check your wiring.")

        #try to start the app
        buf = bytearray(1)
        buf[0] = 0xF4
        self.i2c_device.write(buf, end=1, stop=True)
        time.sleep(.1)

        #make sure there are no errors and we have entered application mode
        if self.checkError():
            raise RuntimeError(
                "Device returned an Error! Try removing and reapplying power to the device and running the code again."
            )
        if not self.fw_mode:
            raise RuntimeError(
                "Device did not enter application mode! If you got here, there may be a problem with the firmware on your sensor."
            )

        self.interrupt_enabled = False

        #default to read every second
        self.setDriveMode(CCS811_DRIVE_MODE_1SEC)

    def setDriveMode(self, mode):
        self.drive_mode = mode

    def available(self):
        return self.data_ready

    def readData(self):

        if not self.data_ready:
            return False
        else:
            buf = bytearray(9)
            buf[0] = CCS811_ALG_RESULT_DATA
            self.i2c_device.write(buf, end=1, stop=False)
            self.i2c_device.read_into(buf, start=1)

            self.eCO2 = (buf[1] << 8) | (buf[2])
            self.TVOC = (buf[3] << 8) | (buf[4])

            if self.error:
                return buf[6]

            else:
                return 0

    def setEnvironmentalData(self, humidity, temperature):
        ''' Humidity is stored as an unsigned 16 bits in 1/512%RH. The
		default value is 50% = 0x64, 0x00. As an example 48.5%
		humidity would be 0x61, 0x00.'''
        ''' Temperature is stored as an unsigned 16 bits integer in 1/512
		degrees there is an offset: 0 maps to -25C. The default value is
		25C = 0x64, 0x00. As an example 23.5% temperature would be
		0x61, 0x00.
		The internal algorithm uses these values (or default values if
		not set by the application) to compensate for changes in
		relative humidity and ambient temperature.'''

        hum_perc = humidity << 1

        parts = math.fmod(temperature)
        fractional = parts[0]
        temperature = parts[1]

        temp_high = ((temperature + 25) << 9)
        temp_low = ((fractional / 0.001953125) & 0x1FF)

        temp_conv = (temp_high | temp_low)

        buf = bytearray([
            CCS811_ENV_DATA, hum_perc, 0x00, ((temp_conv >> 8) & 0xFF),
            (temp_conv & 0xFF)
        ])

        self.i2c_device.write(buf)

    #calculate temperature based on the NTC register
    def calculateTemperature(self):
        buf = bytearray(5)
        buf[0] = CCS811_NTC
        self.i2c_device.write(buf, end=1, stop=False)
        self.i2c_device.read_into(buf, start=1)

        vref = (buf[1] << 8) | buf[2]
        vntc = (buf[3] << 8) | buf[4]

        #from ams ccs811 app note
        rntc = float(vntc) * CCS811_REF_RESISTOR / float(vref)

        ntc_temp = math.log(rntc / 10000.0)
        ntc_temp /= 3380.0
        ntc_temp += 1.0 / (25 + 273.15)
        ntc_temp = 1.0 / ntc_temp
        ntc_temp -= 273.15
        return ntc_temp - self.tempOffset

    def setThresholds(self, low_med, med_high, hysteresis):
        buf = bytearray([
            CCS811_THRESHOLDS, ((low_med >> 8) & 0xF), (low_med & 0xF),
            ((med_high >> 8) & 0xF), (med_high & 0xF), hysteresis
        ])
        self.i2c_device.write(buf)

    def SWReset(self):

        #reset sequence from the datasheet
        seq = bytearray([CCS811_SW_RESET, 0x11, 0xE5, 0x72, 0x8A])
        self.i2c_device.write(seq)

    def checkError(self):
        return self.error
示例#15
0
class DS3231:
    """Interface to the DS3231 RTC."""

    lost_power = i2c_bit.RWBit(0x0F, 7)
    """True if the device has lost power since the time was set."""

    disable_oscillator = i2c_bit.RWBit(0x0E, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    alarm1 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x07)
    """Alarm time for the first alarm."""

    alarm1_interrupt = i2c_bit.RWBit(0x0E, 0)
    """True if the interrupt pin will output when alarm1 is alarming."""

    alarm1_status = i2c_bit.RWBit(0x0F, 0)
    """True if alarm1 is alarming. Set to False to reset."""

    alarm2 = i2c_bcd_alarm.BCDAlarmTimeRegister(0x0B, has_seconds=False)
    """Alarm time for the second alarm."""

    alarm2_interrupt = i2c_bit.RWBit(0x0E, 1)
    """True if the interrupt pin will output when alarm2 is alarming."""

    alarm2_status = i2c_bit.RWBit(0x0F, 1)
    """True if alarm2 is alarming. Set to False to reset."""

    _square_wave_control = i2c_bits.RWBits(3, 0x0E, 2)
    """reg 0x0e, bits 3:4 identify the square wave frequency, bit 2 is disable"""

    _r13b0 = i2c_bit.ROBit(0x13, 0)
    """reg 0x13, bit 0 used to distinguish ds3231"""
    _r3fb0 = i2c_bit.RWBit(0x3f, 0)
    """reg 0x3f, bit 0 used to distinguish between ds1307 and pcf8523"""

    # pylint: disable=unexpected-keyword-arg
    _calibration = i2c_bits.RWBits(8, 0x10, 0, 1, signed=True)

    _temperature = i2c_bits.RWBits(
        10, 0x11, 6, register_width=2, lsb_first=False, signed=True
    )
    # pylint: enable=unexpected-keyword-arg

    _busy = i2c_bit.ROBit(0x0F, 2)
    _conv = i2c_bit.RWBit(0x0E, 5)

    def __init__(self, i2c):
        self.i2c_device = I2CDevice(i2c, 0x68)
        chip = self.chip_identity
        expected = self.__class__.__name__
        if chip != expected:
            raise RuntimeError('Expected {}, found {}'.format(expected, chip))

    @property
    def chip_identity(self):
        """identify the RTC chip (distinguishes among DS1307, PCF8523 and DS3231)"""
        try:
            r13b0 = self._r13b0
        except OSError:
            return 'DS3231'
        else:
            r3fb0 = self._r3fb0
            self._r3fb0 = not r3fb0
            if r3fb0 != self._r3fb0:
                self._r3fb0 = r3fb0
                return 'DS1307'
        return 'PCF8523'
        
    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time
        then starts the clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        self.datetime_register = value
        self.disable_oscillator = False
        self.lost_power = False

    @property
    def temperature(self):
        """Returns the last temperature measurement.  Temperature is updated
        only every 64 seconds, or when a conversion is forced."""
        return self._temperature / 4

    def force_temperature_conversion(self):
        """Forces a conversion and returns the new temperature"""
        while self._busy:
            pass  # Wait for any normal in-progress conversion to complete
        self._conv = True
        while self._conv:
            pass  # Wait for manual conversion request to complete
        return self.temperature

    @property
    def square_wave_frequency(self):
        """Return the square wave frequency, 0 if not enabled"""
        value = self._square_wave_control
        freqs = (1, 0, 1024, 0, 4096, 0, 8192, 0)
        return freqs[value]

    @square_wave_frequency.setter
    def square_wave_frequency(self, frequency):
        available_frequencies = {0: 1, 1: 0, 1024: 2, 4096: 4, 8192: 6}
        try:
            code = available_frequencies[frequency]
            self._square_wave_control = code
        except KeyError:
            raise ValueError('square wave frequency {} not available'.format(frequency))

    @property
    def calibration(self):
        """Calibrate the frequency of the crystal oscillator by adding or
        removing capacitance.  The datasheet calls this the Aging Offset.
        Calibration values range from -128 to 127; each step is approximately
        0.1ppm, and positive values decrease the frequency (increase the
        period).  When set, a temperature conversion is forced so the result of
        calibration can be seen directly at the 32kHz pin immediately"""
        return self._calibration

    @calibration.setter
    def calibration(self, value):
        self._calibration = value
        self.force_temperature_conversion()
示例#16
0
class DS1307:
    """Interface to the DS1307 RTC."""

    disable_oscillator = i2c_bit.RWBit(0x0, 7)
    """True if the oscillator is disabled."""

    datetime_register = i2c_bcd_datetime.BCDDateTimeRegister(0x00)
    """Current date and time."""

    _square_wave_control = i2c_bits.RWBits(5, 0x07, 0)
    """reg 0x07, bits 0:1 identify the square wave frequency, bit 4 = 1"""

    _r13b0 = i2c_bit.ROBit(0x13, 0)
    """reg 0x13, bit 0 used to distinguish ds3231"""
    _r3fb0 = i2c_bit.RWBit(0x3f, 0)
    """reg 0x3f, bit 0 used to distinguish between ds1307 and pcf8523"""
    def __init__(self, i2c_bus):
        self.i2c_device = I2CDevice(i2c_bus, 0x68)
        chip = self.chip_identity
        expected = self.__class__.__name__
        if chip != expected:
            raise RuntimeError('Expected {}, found {}'.format(expected, chip))

    @property
    def chip_identity(self):
        """identify the RTC chip (distinguishes among DS1307, PCF8523 and DS3231)"""
        try:
            r13b0 = self._r13b0
        except OSError:
            return 'DS3231'
        else:
            r3fb0 = self._r3fb0
            self._r3fb0 = not r3fb0
            if r3fb0 != self._r3fb0:
                self._r3fb0 = r3fb0
                return 'DS1307'
        return 'PCF8523'

    @property
    def datetime(self):
        """Gets the current date and time or sets the current date and time then starts the
        clock."""
        return self.datetime_register

    @datetime.setter
    def datetime(self, value):
        # automatically starts the oscillator
        self.datetime_register = value

    @property
    def square_wave_frequency(self):
        """Return the square wave frequency, 0 if disabled"""
        value = self._square_wave_control
        freq_bits = value & 0x3
        if value == freq_bits:  # if square wave is disabled
            return 0
        freqs = (1, 4096, 8192, 32768)
        return freqs[freq_bits]

    @square_wave_frequency.setter
    def square_wave_frequency(self, frequency):
        """Select the frequency and enable the square wave output"""
        available_frequencies = {
            0: 0x00,
            1: 0x10,
            4096: 0x11,
            8192: 0x12,
            32768: 0x13
        }
        try:
            code = available_frequencies[frequency]
            self._square_wave_control = code
        except KeyError:
            raise ValueError(
                'square wave frequency {} not available'.format(frequency))