示例#1
0
        /// <summary>
        ///     Create a new instance of the ADXL345 communicating over the I2C interface.
        /// </summary>
        /// <param name="address">Address of the I2C sensor</param>
        /// <param name="i2cBus">I2C bus</param>
        /// <param name="updateInterval">How frequently this sensor should be updated.</param>
        /// <param name="accelerationChangeNotificationThreshold">Notification threshold, changes greater than +/- this value will generate and interrupt.</param>
        public ADXL345(II2cBus i2cBus, byte address = 0x53, ushort updateInterval = 100,
                       double accelerationChangeNotificationThreshold = 5.0F)
        {
            if ((address != 0x1d) && (address != 0x53))
            {
                throw new ArgumentOutOfRangeException(nameof(address), "ADXL345 address can only be 0x1d or 0x53.");
            }
            if ((updateInterval != 0) && (updateInterval < MinimumPollingPeriod))
            {
                throw new ArgumentOutOfRangeException(nameof(updateInterval),
                                                      "Update interval should be 0 or greater than " + MinimumPollingPeriod);
            }

            _updateInterval = updateInterval;
            AccelerationChangeNotificationThreshold = accelerationChangeNotificationThreshold;

            var device = new I2cPeripheral(i2cBus, address);

            _adxl345 = device;
            if (DeviceID != 0xe5)
            {
                throw new Exception("Invalid device ID.");
            }
            if (updateInterval > 0)
            {
                StartUpdating();
            }
            else
            {
                Update();
            }
        }
        public APDS9301_LightSensor(I2cPeripheral lightDevice, TimeSpan updateInterval)
        {
            if (updateInterval.TotalMilliseconds > ushort.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(updateInterval), $"Update Interval must be less than {ushort.MaxValue} milliseconds");
            }
            else if (updateInterval.TotalMilliseconds <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(updateInterval), $"Update Interval must be greater than 0 but it's {updateInterval.TotalMilliseconds} milliseconds");
            }

            _updateInterval = (ushort)updateInterval.TotalMilliseconds;

            _lightDevice = lightDevice;
            _i2cHelper   = new I2CHelper(_lightDevice);

            TurnOn();
            SensorGain = Gain.Low;
            Timing     = IntegrationTiming.Ms13;
            DisableInterrupt();

            // Wait for the sensor to prepare the first reading (402ms after power on).
            Thread.Sleep(410);
            _updateThread = new Thread(() =>
            {
                while (true)
                {
                    UpdateLumosity();
                    Thread.Sleep(_updateInterval);
                }
            });
            _updateThread.Start();
        }
示例#3
0
        /// <summary>
        ///     Create a new instance of the TSL2561 class with the specified I2C address.
        /// </summary>
        /// <remarks>
        ///     By default the sensor will be set to low gain.
        /// <remarks>
        /// <param name="address">I2C address of the TSL2561</param>
        /// <param name="i2cBus">I2C bus (default = 100 KHz).</param>
        /// <param name="updateInterval">Update interval for the sensor (in milliseconds).</param>
        /// <param name="lightLevelChangeNotificationThreshold">Changes in light level greater than this value will generate an interrupt in auto-update mode.</param>
        public Tsl2561(II2cBus i2cBus, byte address = (byte)Addresses.Default, ushort updateInterval = MinimumPollingPeriod,
                       float lightLevelChangeNotificationThreshold = 10.0F)
        {
            if (lightLevelChangeNotificationThreshold < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(lightLevelChangeNotificationThreshold), "Light level threshold change values should be >= 0");
            }

            LightLevelChangeNotificationThreshold = lightLevelChangeNotificationThreshold;
            this.updateInterval = updateInterval;

            var device = new I2cPeripheral(i2cBus, address);

            tsl2561 = device;
            //
            //  Wait for the sensor to prepare the first reading (402ms after power on).
            //
            Thread.Sleep(410);
            if (updateInterval > 0)
            {
                StartUpdating();
            }
            else
            {
                Update();
            }
        }
示例#4
0
        /// <summary>
        ///     Create a new AT24Cxx object using the default parameters for the component.
        /// </summary>
        /// <param name="address">Address of the At24Cxx (default = 0x50).</param>
        /// <param name="pageSize">Number of bytes in a page (default = 32 - AT24C32).</param>
        /// <param name="memorySize">Total number of bytes in the EEPROM (default = 8192 - AT24C32).</param>
        public At24Cxx(II2cBus i2cBus, byte address = 0x50, ushort pageSize = 32, ushort memorySize = 8192)
        {
            var device = new I2cPeripheral(i2cBus, address);

            _eeprom     = device;
            _pageSize   = pageSize;
            _memorySize = memorySize;
        }
        public I2CHelper(I2cPeripheral device)
        {
            _device                 = device;
            _readTransaction        = I2cPeripheral.CreateReadTransaction(_readWriteIndividualValueBuffer);
            _writeTransaction       = I2cPeripheral.CreateWriteTransaction(_addressWriteIndividualValueBuffer);
            _writeUshortTransaction = I2cPeripheral.CreateWriteTransaction(_ushortWriteValueBuffer);

            _readTransactions        = new[] { _readTransaction };
            _writeTransactions       = new[] { _writeTransaction };
            _writeUshortTransactions = new[] { _writeUshortTransaction };
        }
        public byte[] ReadRegisters(byte registerAddress, ushort length)
        {
            _readWriteIndividualValueBuffer[0] = registerAddress;
            byte[] registerReadBuffer      = new byte[length];
            var    registerReadTransaction = I2cPeripheral.CreateReadTransaction(registerReadBuffer);

            var readRegistersTransactions = new[] { _readTransaction, registerReadTransaction };

            _device.Execute(readRegistersTransactions, 1000);

            return(registerReadBuffer);
        }
示例#7
0
        /// <summary>
        /// Create a new MAG3110 object using the default parameters for the component.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="interruptPin">Digital pin connected to the alarm interrupt pin on the RTC.</param>
        public Ds3231(IIODevice device, II2cBus i2cBus, IPin interruptPin, byte address = 0x68, ushort speed = 100)
        {
            _ds323x = new I2cPeripheral(i2cBus, address);

            // samples will need to pass null
            if (interruptPin != null)
            {
                _interruptPort = device.CreateDigitalInputPort(interruptPin);

                _interruptPort.Changed += InterruptPort_Changed;
            }
        }
示例#8
0
        protected Ds323x(I2cPeripheral peripheral, IIODevice device, IPin interruptPin)
        {
            ds323x = peripheral;

            if (interruptPin != null)
            {
                var interruptPort = device.CreateDigitalInputPort(interruptPin, InterruptMode.EdgeFalling, ResistorMode.InternalPullUp, 10, 10);
                _interruptCreatedInternally = true;

                Initialize(interruptPort);
            }
        }
示例#9
0
        /// <summary>
        /// Create a new Ds3231 object using the default parameters for the component.
        /// </summary>
        /// <param name="address">Address of the DS3231 (default = 0x68).</param>
        /// <param name="speed">Speed of the I2C bus (default = 100 KHz).</param>
        /// <param name="interruptPort">Digital port connected to the alarm interrupt pin on the RTC.</param>
        public Ds3231(II2cBus i2cBus, IDigitalInputPort interruptPort, byte address = 0x68, ushort speed = 100)
        {
            _ds323x = new I2cPeripheral(i2cBus, address);

            // samples will need to pass null
            if (interruptPort != null)
            {
                _interruptPort = interruptPort;

                _interruptPort.Changed += InterruptPort_Changed;
            }
        }
示例#10
0
        public App()
        {
            //TODO: Find out if this is even right for finding the pin
            var ledPin = (IDigitalPin)Device.Pins.AllPins.Single(x => x.Name == LedPinName);

            _sleepTimer = new BlockingTimer(TimeSpan.FromMilliseconds(100));
            _ledControl = new LedControl(ledPin, _sleepTimer);

            var lightSensorI2cConfig = new I2cPeripheral.Configuration(LightSensorDeviceAddress, I2cDeviceClockHz);
            var lightI2cPeripheral   = new I2cPeripheral(lightSensorI2cConfig);

            _lightSensor = new APDS9301_LightSensor(lightI2cPeripheral, APDS9301_LightSensor.MinimumPollingPeriod);
        }
示例#11
0
        /// <summary>
        ///     Create a new MPL3115A2 object with the default address and speed settings.
        /// </summary>
        /// <param name="address">Address of the sensor (default = 0x60).</param>
        /// <param name="i2cBus">I2cBus (Maximum is 400 kHz).</param>
        public Mpl3115A2(II2cBus i2cBus, byte address = 0x60)
        {
            var device = new I2cPeripheral(i2cBus, address);

            _mpl3115a2 = device;
            if (_mpl3115a2.ReadRegister(Registers.WhoAmI) != 0xc4)
            {
                throw new Exception("Unexpected device ID, expected 0xc4");
            }
            _mpl3115a2.WriteRegister(Registers.Control1,
                                     (byte)(ControlRegisterBits.Active | ControlRegisterBits.OverSample128));
            _mpl3115a2.WriteRegister(Registers.DataConfiguration,
                                     (byte)(ConfigurationRegisterBits.DataReadyEvent |
                                            ConfigurationRegisterBits.EnablePressureEvent |
                                            ConfigurationRegisterBits.EnableTemperatureEvent));
        }
示例#12
0
            public static SensorReading CreateFromDevice(I2cPeripheral device, SensorSettings sensorSettings)
            {
                // Read the current control register
                var status = device.ReadRegister(RegisterAddresses.ControlTemperatureAndPressure.Address);

                // Force a sample
                status = BitHelpers.SetBit(status, 0x00, true);
                device.WriteRegister(RegisterAddresses.ControlTemperatureAndPressure.Address, status);
                // Wait for the sample to be taken.
                do
                {
                    status = device.ReadRegister(RegisterAddresses.ControlTemperatureAndPressure.Address);
                } while (BitHelpers.GetBitValue(status, 0x00));

                var sensorData = device.ReadRegisters(
                    RegisterAddresses.AllSensors.Address,
                    RegisterAddresses.AllSensors.Length)
                                 .AsSpan();

                var rawPressure    = GetRawValue(sensorData.Slice(0, 3));
                var rawTemperature = GetRawValue(sensorData.Slice(3, 3));
                var rawHumidity    = GetRawValue(sensorData.Slice(6, 2));
                //var rawVoc = GetRawValue(sensorData.Slice(8, 2));
                var compensationData1 = device.ReadRegisters(RegisterAddresses.CompensationData1.Address,
                                                             RegisterAddresses.CompensationData1.Length);
                var compensationData2 = device.ReadRegisters(RegisterAddresses.CompensationData2.Address,
                                                             RegisterAddresses.CompensationData2.Length);
                var compensationData = ArrayPool <byte> .Shared.Rent(64);

                try {
                    Array.Copy(compensationData1, 0, compensationData, 0, compensationData1.Length);
                    Array.Copy(compensationData2, 0, compensationData, 25, compensationData2.Length);

                    var temp = RawToTemp(rawTemperature,
                                         new TemperatureCompensation(compensationData));

                    var pressure = RawToPressure(temp, rawPressure,
                                                 new PressureCompensation(compensationData));
                    var humidity = RawToHumidity(temp, rawHumidity,
                                                 new HumidityCompensation(compensationData));

                    return(new SensorReading(pressure, temp, humidity, 0, sensorSettings));
                } finally {
                    ArrayPool <byte> .Shared.Return(compensationData, true);
                }
            }
示例#13
0
        public Qmc5883(II2cBus i2cBus, byte address = 0x0D,
                       Gain gain = Gain.Gain1090,
                       MeasuringMode measuringMode = MeasuringMode.Continuous,
                       OutputRate outputRate       = OutputRate.Rate15,
                       SamplesAmount samplesAmount = SamplesAmount.One,
                       MeasurementConfiguration measurementConfig = MeasurementConfiguration.Normal)
        {
            i2cPeripheral = new I2cPeripheral(i2cBus, address);

            base.gain              = (byte)gain;
            base.measuringMode     = (byte)measuringMode;
            base.outputRate        = (byte)outputRate;
            sampleAmount           = (byte)samplesAmount;
            base.measurementConfig = (byte)measurementConfig;

            Initialize();
        }
示例#14
0
        /// <summary>
        ///     Create a new MPL115A2 temperature and humidity sensor object.
        /// </summary>
        /// <param name="address">Sensor address (default to 0x60).</param>
        /// <param name="i2cBus">I2CBus (default to 100 KHz).</param>
        public Mpl115a2(II2cBus i2cBus, byte address = 0x60)
        {
            var device = new I2cPeripheral(i2cBus, address);

            mpl115a2 = device;
            //
            //  Update the compensation data from the sensor.  The location and format of the
            //  compensation data can be found on pages 5 and 6 of the datasheet.
            //
            var data = mpl115a2.ReadRegisters(Registers.A0MSB, 8);
            var a0   = (short)(ushort)((data[0] << 8) | data[1]);
            var b1   = (short)(ushort)((data[2] << 8) | data[3]);
            var b2   = (short)(ushort)((data[4] << 8) | data[5]);
            var c12  = (short)(ushort)(((data[6] << 8) | data[7]) >> 2);

            //
            //  Convert the raw compensation coefficients from the sensor into the
            //  doubleing point equivalents to speed up the calculations when readings
            //  are made.
            //
            //  Datasheet, section 3.1
            //  a0 is signed with 12 integer bits followed by 3 fractional bits so divide by 2^3 (8)
            //
            coefficients.A0 = (double)a0 / 8;
            //
            //  b1 is 2 integer bits followed by 7 fractional bits.  The lower bits are all 0
            //  so the format is:
            //      sign i1 I0 F12...F0
            //
            //  So we need to divide by 2^13 (8192)
            //
            coefficients.B1 = (double)b1 / 8192;
            //
            //  b2 is signed integer (1 bit) followed by 14 fractional bits so divide by 2^14 (16384).
            //
            coefficients.B2 = (double)b2 / 16384;
            //
            //  c12 is signed with no integer bits but padded with 9 zeroes:
            //      sign 0.000 000 000 f12...f0
            //
            //  So we need to divide by 2^22 (4,194,304) - 13 doubleing point bits
            //  plus 9 leading zeroes.
            //
            coefficients.C12 = (double)c12 / 4194304;
        }
示例#15
0
        protected Ds323x(I2cPeripheral peripheral, IDigitalInputPort interruptPort)
        {
            ds323x = peripheral;

            Initialize(interruptPort);
        }
示例#16
0
        /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
        /// <summary>
        /// A function to provide the calls to test the LCD. 2 rows by 16 col version
        /// </summary>
        /// <history>
        ///    13 Jun 20  Cynic - Started
        /// </history>
        public void LCD_Test_2x16()
        {
            II2cBus        i2cBus        = Device.CreateI2cBus();
            II2cPeripheral i2cPeripheral = new I2cPeripheral(i2cBus, 0x27);

            Meadow_LCD lcdAPI = new Meadow_LCD(i2cPeripheral, 2, 16);

            // initialize now
            Console.WriteLine("Begin LCD_Test");
            lcdAPI.InitLCD();

            // title bit
            lcdAPI.MoveTo(0, 1);
            lcdAPI.WriteString("CS_LCD Library");
            lcdAPI.MoveTo(1, 2);
            lcdAPI.WriteString("Tests Begin");

            Thread.Sleep(3000);
            lcdAPI.Clear();

            // set values in all four corners
            lcdAPI.MoveTo(1, 2);
            lcdAPI.WriteString("TestCorners");

            lcdAPI.MoveTo(0, 0);
            lcdAPI.WriteChar('A');
            lcdAPI.MoveTo(1, 0);
            lcdAPI.WriteChar('B');

            lcdAPI.MoveTo(0, 15);
            lcdAPI.WriteChar('1');
            lcdAPI.MoveTo(1, 15);
            lcdAPI.WriteChar('2');

            Thread.Sleep(3000);
            lcdAPI.Clear();

            lcdAPI.MoveTo(2, 2);
            lcdAPI.WriteString("AutoWrapTest");
            Thread.Sleep(2000);

            lcdAPI.MoveTo(0, 14);
            lcdAPI.WriteString("ABC");
            Thread.Sleep(1000);
            lcdAPI.MoveTo(1, 14);
            lcdAPI.WriteString("DEF");
            Thread.Sleep(1000);

            Thread.Sleep(3000);
            lcdAPI.Clear();

            // now test the backlight
            lcdAPI.MoveTo(1, 1);
            lcdAPI.WriteString("BacklightOff+On");
            Thread.Sleep(2000);
            lcdAPI.BacklightOff();
            Thread.Sleep(2000);
            lcdAPI.BacklightOn();

            Thread.Sleep(3000);
            lcdAPI.Clear();

            // now test the display
            lcdAPI.MoveTo(1, 1);
            lcdAPI.WriteString("DisplayOff+On");
            Thread.Sleep(2000);
            lcdAPI.DisplayOff();
            Thread.Sleep(2000);
            lcdAPI.DisplayOn();

            Thread.Sleep(3000);
            lcdAPI.Clear();

            // now test the display
            lcdAPI.MoveTo(1, 1);
            lcdAPI.WriteString("Show Cursor");
            Thread.Sleep(2000);
            lcdAPI.ShowCursor();
            Thread.Sleep(2000);
            lcdAPI.MoveTo(1, 1);
            lcdAPI.WriteString("Blink Cursor");
            lcdAPI.BlinkCursorOn();
            Thread.Sleep(2000);
            lcdAPI.MoveTo(1, 1);
            lcdAPI.WriteString("Cursor Off  ");
            lcdAPI.HideCursor();

            Thread.Sleep(3000);
            lcdAPI.Clear();

            lcdAPI.MoveTo(1, 0);
            lcdAPI.WriteString("Custom Char Test");
            lcdAPI.HideCursor();

            Thread.Sleep(2000);

            // now custom char test
            byte[] happyFace  = new byte[] { 0x00, 0x0A, 0x00, 0x04, 0x00, 0x11, 0x0E, 0x00 };
            byte[] sadFace    = new byte[] { 0x00, 0x0A, 0x00, 0x04, 0x00, 0x0E, 0x11, 0x00 };
            byte[] grinFace   = new byte[] { 0x00, 0x00, 0x0A, 0x00, 0x1F, 0x11, 0x0E, 0x00 };
            byte[] shockFace  = new byte[] { 0x0A, 0x00, 0x04, 0x00, 0x0E, 0x11, 0x11, 0x0E };
            byte[] mehFace    = new byte[] { 0x00, 0x0A, 0x00, 0x04, 0x00, 0x1F, 0x00, 0x00 };
            byte[] angryFace  = new byte[] { 0x11, 0x0A, 0x11, 0x04, 0x00, 0x0E, 0x11, 0x00 };
            byte[] tongueFace = new byte[] { 0x00, 0x0A, 0x00, 0x04, 0x00, 0x1F, 0x05, 0x02 };

            lcdAPI.CustomChar(0, happyFace);
            lcdAPI.CustomChar(1, sadFace);
            lcdAPI.CustomChar(2, grinFace);
            lcdAPI.CustomChar(3, shockFace);
            lcdAPI.CustomChar(4, mehFace);
            lcdAPI.CustomChar(5, angryFace);
            lcdAPI.CustomChar(6, tongueFace);

            lcdAPI.MoveTo(0, 2);
            lcdAPI.WriteChar((char)0x00);
            lcdAPI.WriteChar((char)0x01);
            lcdAPI.WriteChar((char)0x02);
            lcdAPI.WriteChar((char)0x03);
            lcdAPI.WriteChar((char)0x04);
            lcdAPI.WriteChar((char)0x05);
            lcdAPI.WriteChar((char)0x06);

            Thread.Sleep(3000);
            lcdAPI.Clear();

            lcdAPI.MoveTo(0, 1);
            lcdAPI.WriteString("CS_LCD Library");
            lcdAPI.MoveTo(1, 1);
            lcdAPI.WriteString("Test Complete");

            Console.WriteLine("End LCD_Test");

            // we just let the i2cPeripheral and i2cbus go out of scope and be
            // garbage collected normally
        }
示例#17
0
        //private int headingCorrection = 180;

        /// <summary>
        /// Basic constructor
        /// </summary>
        /// <param name="bus">I2C bus</param>
        /// <param name="address">I2C device address</param>
        public BNO055(II2cBus bus, byte address = 40)
        {
            sensor = new Bno055(bus, address);
            sensor.OperatingMode = Bno055.OperatingModes.NINE_DEGREES_OF_FREEDOM;
            bno = new I2cPeripheral(bus, address);
        }